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:
- Look in Redis.
- Hit: return it.
- Miss: load from the database, store it in Redis with a TTL, return it.
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:
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 |
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.
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:
- Lock while rebuilding: the first request takes a short lock with
SET … NX; others wait briefly or serve stale data. - Refresh early: refresh popular keys in the background before they expire.
- Stale-while-revalidate: store a "soft" expiry inside the value; serve the old value while one request refreshes it.
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:
Libraries like connect-redis (Express) and Django's cache-based sessions do exactly this.
Practice
- Simulate cache-aside for
cache:user:7: a miss, then aSETwith a 60-second TTL, then a hit. CheckINFO stats. - Implement versioned keys for a
blogcache, and invalidate all pages with one command. - Use
SET … NX EXto make sure only one of three "requests" rebuilds an expired key.
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?