Difficulty: Intermediate
Explain Cache-Aside vs. Write-Through caching. When would you choose each, and where do Read-Through and Write-Behind fit?
In cache-aside (lazy loading) the application reads from the cache first, and on a miss it reads the database, then writes the result into the cache with a TTL. In write-through, every write goes to the cache and the database as part of the same operation, so the cache is always populated and fresh for keys that were written. Cache-aside is the most common pattern with Redis because it is simple and the app keeps working if Redis goes down; write-through trades slower writes for fewer stale reads.
GET product:101.SET product:101 <json> EX 300, then return.DEL product:101) so the next read reloads it.Deleting on write is preferred over updating the cache, because two concurrent writers updating the cache in different orders can leave it permanently stale. Only data that is actually read ends up in cache, which keeps memory usage proportional to the hot set.
| Pattern | Write latency | Stale read risk | Survives cache outage | Good for |
|---|---|---|---|---|
| Cache-aside | Low (DB only) | Short window after write | Yes, falls back to DB | Most read-heavy APIs |
| Write-through | Higher (DB + cache) | Very low | Depends on implementation | Data read right after it is written |
| Write-behind | Lowest (cache only) | Low | No, risk of data loss | Counters, analytics, likes |
| Read-through | Same as cache-aside | Same as cache-aside | Depends on layer | Teams that want caching hidden from business code |
A product catalogue at Flipkart scale is a classic cache-aside case: reads massively outnumber writes and a few seconds of staleness is fine. Wallet balances or UPI transaction status should not be served from a write-behind cache; the database stays the source of truth and the cache, if any, is invalidated on every change. Change data capture (Debezium reading the DB log and deleting Redis keys) is a popular way to make invalidation reliable without touching every write path.
import { createClient } from 'redis';
const redis = await createClient().connect();
export async function getProduct(id) {
const key = `product:${id}`;
const cached = await redis.get(key);
if (cached) return JSON.parse(cached); // hit
const product = await db.products.findById(id); // miss: go to DB
if (product) {
// TTL is a safety net even though we invalidate on write
await redis.set(key, JSON.stringify(product), { EX: 300 });
}
return product;
}
export async function updatePrice(id, pricePaise) {
await db.products.update(id, { pricePaise }); // 1. source of truth first
await redis.del(`product:${id}`); // 2. then invalidate
}
Reads populate the cache lazily and writes delete the key instead of updating it, which avoids two writers leaving the cache in the wrong order.
Cache-Aside, Write-Through, Write-Behind, Read-Through, Cache Invalidation