Databases for Developers

Lesson 7 of 10 · 20 min

x
70%

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
async function getProduct(id: string) {
  return await db.query(
    'SELECT * FROM products WHERE id = $1', [id]
  );
}
After
Cache-aside pattern with Redis
async function getProduct(id: string) {
  const cached = await redis.get(`product:${id}`);
  if (cached) return JSON.parse(cached);

  const product = await db.query(
    'SELECT * FROM products WHERE id = $1', [id]
  );
  await redis.setex(`product:${id}`, 300, JSON.stringify(product));
  return product;
}

Key Takeaway

Cache hot, rarely changing data in Redis with a TTL — your database stays fast and uncrowded.

PreviousNext Lesson