Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

RD
Redis
0/10 completed
Beginner
What is Redis?Strings, numbers and keysExpiry and TTL
Intermediate
Lists and hashesSets and sorted setsCaching patterns
Advanced
Rate limiters, locks and transactionsPub/Sub and Streams
Pro
Memory, eviction and persistenceReplication, Sentinel and Cluster
Tracks / Redis / Intermediate

Caching patterns

Caching is Redis's most common job. A cache stores the result of slow work (a database query, an API call, a rendered page) so the next request can reuse it. Done well, it makes pages load in milliseconds and cuts database load dramatically. Done badly, it shows users stale or wrong data.

"There are only two hard things in computer science: cache invalidation and naming things." (Phil Karlton)

Cache-aside (lazy loading)

The most common pattern. The app manages the cache:

  1. Look in Redis.
  2. Hit: return it.
  3. Miss: load from the database, store it in Redis with a TTL, return it.
js
async function getProduct(id) {
  const key = `cache:product:${id}`;

  const cached = await redis.get(key);                  // 1. try the cache
  if (cached) return JSON.parse(cached);                // 2. hit

  const product = await db.query('SELECT * FROM products WHERE id = $1', [id]);  // 3. miss
  await redis.set(key, JSON.stringify(product), { EX: 300 });                    // keep 5 minutes
  return product;
}

Here's what that sequence looks like on the Redis side:

redis-cli (simulator) · editable

keyspace_hits and keyspace_misses let you calculate your hit ratio, the most important cache metric. A good cache serves most requests from memory.

Keeping the cache correct: invalidation

When the underlying data changes, the cached copy is stale. Options:

Strategy How Trade-off
TTL only Let entries expire Simple; data can be stale for up to the TTL
Delete on write After updating the DB, DEL the cache key Fresh data; the next read reloads it
Write-through After updating the DB, SET the new value in the cache Always warm; must serialise the same way everywhere
js
async function updateProductPrice(id, price) {
  await db.query('UPDATE products SET price = $1 WHERE id = $2', [price, id]);
  await redis.del(`cache:product:${id}`);               // the next read loads fresh data
}

Delete after the database write, not before. Otherwise another request could re-cache the old value in between. Most teams combine delete-on-write with a TTL as a safety net, so even a missed invalidation heals itself.

Invalidating groups of keys

A product appears in many cached lists (cache:category:kitchen:page:1, …). Two common approaches:

  • Tag sets: record which keys depend on what, then delete them all together.
  • Versioned keys: include a version number in the key; bump the version to invalidate everything at once, and let old keys expire.
redis-cli (simulator) · editable
redis-cli (simulator) · editable

Choosing TTLs

  • Data that changes rarely (product catalogue, settings): minutes to hours.
  • Data that changes often but can be slightly stale (view counts, "trending"): seconds.
  • Per-user data: short, and include the user id in the key so users never see each other's data.
  • Add jitter (randomness): if 10,000 keys were cached at the same moment with the same TTL, they all expire together and the database gets hammered. EX 300 + random(0..60) spreads expiries out.

Cache stampede

A popular key expires, and 500 requests miss at the same moment: 500 identical expensive queries hit the database. Defences:

  1. Lock while rebuilding: the first request takes a short lock with SET … NX; others wait briefly or serve stale data.
  2. Refresh early: refresh popular keys in the background before they expire.
  3. Stale-while-revalidate: store a "soft" expiry inside the value; serve the old value while one request refreshes it.
redis-cli (simulator) · editable

What to cache, and what not to

✅ Results of expensive queries and API calls, rendered fragments, configuration, sessions, computed recommendations.

❌ Data that must be exactly current (account balances in a payment flow), huge values (multi-MB blobs: keep values small), or anything only ever read once.

Sessions in Redis

Storing web sessions in Redis lets any server in a cluster handle any request, and sessions expire automatically:

redis-cli (simulator) · editable

Libraries like connect-redis (Express) and Django's cache-based sessions do exactly this.

Practice

  1. Simulate cache-aside for cache:user:7: a miss, then a SET with a 60-second TTL, then a hit. Check INFO stats.
  2. Implement versioned keys for a blog cache, and invalidate all pages with one command.
  3. Use SET … NX EX to make sure only one of three "requests" rebuilds an expired key.
redis-cli (simulator) · editable
✎ Check your understanding

1.In cache-aside, what happens on a cache miss?

2.Why add random jitter to TTLs?

3.When updating a product, what's the safest order?

← Sets and sorted sets