Skip to content
Databases for Developers

Lesson 7 of 10 · 20 min

x
7/10

Lesson position in the course — not completion. Use Mark Complete to track finished lessons (saved in this browser).

NoSQL: Key-Value & Caching with Redis

Key-value stores are the simplest database model: you store a value under a key and retrieve it by that key. Redis is the dominant in-memory key-value store — it lives entirely in RAM, which is why operations complete in sub-millisecond time.

Redis supports more than simple strings. Hashes store structured objects, sorted sets power leaderboards and rate limiters, lists work as queues, and pub/sub enables real-time messaging. The most common pattern is a cache in front of a slower database: check Redis first, fall through to Postgres on a miss, then write the result back to Redis with a TTL so stale data eventually expires.

Before
Every request hits the database
1async function getProduct(id: string) {2  return await db.query(3    'SELECT * FROM products WHERE id = $1', [id]4  );5}
After
Cache-aside pattern with Redis
1async function getProduct(id: string) {2  const cached = await redis.get(`product:${id}`);3  if (cached) return JSON.parse(cached);4 5  const product = await db.query(6    'SELECT * FROM products WHERE id = $1', [id]7  );8  await redis.setex(`product:${id}`, 300, JSON.stringify(product));9  return product;10}

Exercise

Implement cache-aside for a getById: check Redis, on miss query the DB, SETEX with a TTL, return the value. Add a note on what happens if the DB row is updated while the key is still cached.

Previous

Progress is saved in this browser.

Next Lesson