Skip to content

Caching ​

Put the cache in the right layer, know what a hit ratio is worth, and have an answer for how each entry becomes wrong.

In this chapter: hit ratio as a capacity multiplier · the four patterns · what not to cache · the stampede · warm-up and TTL jitter

💡 The Core Idea ​

A cache keeps a copy of expensive-to-produce data somewhere cheap to read. That is the whole mechanism. The arithmetic makes it the strongest move in system design. A cache does not make the database faster. It stops most requests from reaching the database at all.

That changes how to see it. Caching is not a performance trick you add later. It is a capacity decision you make before you buy servers. The hard part was never the storing. It is knowing when the copy you stored stopped being true.

How It Works ​

The arithmetic that justifies it ​

Hit ratio is hits divided by total lookups, and the number behind the origin is what matters:

text
10,000 req/s with no cache        -> 10,000 database queries/s
10,000 req/s at 90% hit ratio     ->  1,000 database queries/s
10,000 req/s at 95% hit ratio     ->    500 database queries/s

Going from 90% to 95% halves the load on the database. That is the shape of the curve, and it is why "raise the hit ratio" beats "add a replica" almost every time. Below 50%, the cache is not earning its complexity. Either the TTL is too short, the cache is too small for the working set (the keys in active use), or the data really is not repeated.

The four patterns ​

PatternWho writes the cacheConsistencyReach for it when
Cache-asideThe application, on a missEventualRead-heavy, general purpose — the default
Read-throughThe cache itself, on a missEventualYou want the miss logic in one place, not in every caller
Write-throughThe application writes bothStrong on read-after-writeLow write volume where a stale read is unacceptable
Write-behindThe cache flushes asynchronouslyEventual, and lossy on crashWrite-heavy counters and metrics

Cache-aside, with the invalidation that has to come with it:

typescript
interface CacheClient {
  get<T>(key: string): Promise<T | null>;
  set<T>(key: string, value: T, ttlSeconds: number): Promise<void>;
  setIfAbsent(key: string, value: string, ttlSeconds: number): Promise<boolean>;
  del(key: string): Promise<void>;
}

interface Product {
  id: string;
  name: string;
  price: number;
}

async function getProduct(
  cache: CacheClient,
  db: DatabaseClient,
  productId: string,
): Promise<Product> {
  const key = `product:${productId}`; // keyed per entity, never `product:latest`

  const cached = await cache.get<Product>(key);
  if (cached) return cached;

  const product = await db.findProduct(productId);
  await cache.set(key, product, 300);
  return product;
}

// The write path owns the eviction. Skipping this line is how staleness ships.
async function updateProduct(
  cache: CacheClient,
  db: DatabaseClient,
  productId: string,
  updates: Partial<Product>,
): Promise<void> {
  await db.updateProduct(productId, updates);
  await cache.del(`product:${productId}`);
}

What to cache, and what not to ​

The decision is two questions: how often is it read, and how fast does it change.

DataReadChangesVerdict
Product catalogueHighRarelyCache, 5–30 min TTL, evict on update
Homepage aggregationHighRarelyCache, 1–5 min TTL — the query is expensive, the answer is shared
User profileHighSometimesCache per user, 5–15 min, evict on update
Live price or stock levelHighConstantlyDo not cache — stale within seconds, and wrong is worse than slow
A user's balance or order stateMediumSometimesNever in a shared cache; per-user key only, short TTL
One-time tokensOnce—Nothing to gain; a cache read is a second place to leak from

Eviction and store choice ​

When memory fills, something has to go. LRU (evict the least recently used) is the right default. Redis needs maxmemory-policy allkeys-lru for it: with only maxmemory set, it rejects writes instead. LFU (least frequently used) wins for long-running caches with a stable hot set, where recency misleads. TTL expiry is not really eviction. It is your statement of how long a copy may be wrong.

Redis is the default cache store for new systems. It has data structures beyond strings, replication, clustering and persistence. Memcached wins only on raw throughput for pure key-value work at extreme scale, and gives up everything else.

The stampede ​

When a hot key expires, every in-flight request misses at the same moment, and they all hit the database together. There are two defences, and they work together:

typescript
// 1. Jitter, so related keys stop expiring in the same second.
function jitteredTtl(baseSeconds: number, jitter = 0.1): number {
  const spread = baseSeconds * jitter;
  return Math.round(baseSeconds + (Math.random() * 2 - 1) * spread);
}

// 2. A lock, so exactly one request recomputes and the rest wait, then retry.
async function getWithLock(cache: CacheClient, db: DatabaseClient, productId: string): Promise<Product> {
  const key = `product:${productId}`;
  const cached = await cache.get<Product>(key);
  if (cached) return cached;

  // SET NX EX — the first caller wins the lock; the others wait and read what it wrote.
  if (!(await cache.setIfAbsent(`${key}:lock`, "1", 10))) {
    await new Promise((resolve) => setTimeout(resolve, 50));
    return getWithLock(cache, db, productId);
  }
  const fresh = await db.findProduct(productId);
  await cache.set(key, fresh, jitteredTtl(300));
  await cache.del(`${key}:lock`);
  return fresh;
}

⚠️ A deploy is a stampede in disguise. New instances start with cold local caches. If the shared cache was also flushed, the first minute of traffic goes entirely to the database. At peak, that is the moment it falls over.

Warm-up on deploy ​

Fill the handful of keys you know will be hit: the homepage query, feature flags, the configuration blob. Do it as a readiness gate, not as a background task after cutover. An instance that takes traffic before its cache is warm sends all of its first requests to the database. A rolling deploy repeats that once per instance.

When to Use It ​

ScenarioWhere the cache goes
The same query serves thousands of usersShared cache, keyed by entity, TTL in minutes
Expensive aggregation, tolerant of a minute of lagShared cache, short TTL, no invalidation needed
Per-user data read repeatedly in a sessionPer-user key, short TTL, evicted on write
Public responses to unauthenticated clientsFurther out still — the CDN, not your cache
Data that must be exactly rightNo cache; solve it with an index or a read replica

Common Mistakes ​

❌ No TTL. A key with no expiry is stale forever once the invalidation path misses it once. ✅ Always set a TTL, even a generous one. It is the backstop for the invalidation you forgot.

❌ A shared key for per-user data. cart:latest serves one customer's basket to the next. ✅ The user or entity id goes in the key, always.

❌ Invalidating nowhere. The read path is written, the write path is not, and updates take a full TTL to appear. ✅ Eviction belongs in the same function as the write.

❌ Treating the cache as a store. Redis restarts. If the data does not also exist in the database, it is simply gone. ✅ Everything in the cache must be re-derivable from the source of truth.

❌ Uniform TTLs set at deploy. Every key expires in the same second and the stampede is self-inflicted. ✅ Jitter by ten percent.

🔑 Key Takeaways ​

  • A cache is a capacity multiplier: 90% to 95% hit ratio halves the load reaching the database.
  • Cache-aside plus TTL covers most systems. Reach for the other patterns only when it fails you.
  • The write path owns invalidation. A read path written alone is how stale data ships.
  • Below a 50% hit ratio the cache costs more than it saves. Fix the TTL, the size, or the key.
  • Jitter the TTLs and warm the hot keys, or a deploy will hand the whole load to the database at once.

Interview Questions ​

Q: Which caching pattern would you start with, and why?

Cache-aside. The application checks the cache, falls back to the database on a miss, and writes what it found. It keeps the cache out of the write path, so a cache outage hurts latency, not correctness. It also caches only what is actually read. The cost is that every caller has to remember the invalidation. That is why the eviction belongs inside the update function, not at the call site.

Q: How do you decide the TTL?

Start from how wrong the data is allowed to be, not from how long you would like to cache it. A product listing that is five minutes stale is fine. An account balance is not cacheable at any TTL. Then check the hit ratio. If it is low, the TTL is expiring keys before they are reused. Explicit eviction on write lets you run a longer TTL safely. The TTL stops being the main freshness mechanism and becomes the backstop.

Q: A hot key expires and the database falls over. What happened, and what do you do?

A cache stampede. Every concurrent request missed at the same instant and went to the origin together. Three fixes apply. A lock lets only one request recompute while the others wait or serve stale. Jittered TTLs stop related keys expiring in the same second. And pre-warming the known-hot keys protects cold instances before a deploy sends them traffic.

Q: When is caching the wrong answer?

When the data changes faster than it is read, or when it must be correct at the instant of reading. Also when the traffic has no repetition. If every request is unique, every lookup is a miss, and you pay to store something nobody asks for again. The real fix is then usually an index, a read replica, or a cheaper query.

The whole book, free to read. Generated from the manuscript on every change.

Your progress

Tick each chapter in the sidebar once you have read and understood it. Your name and email keep the ticks on any device.

Your name and email are stored to save your progress. Nothing else is done with them.