← All lessons

Core concepts

Caching

A cache is a second copy of your data that is allowed to be wrong. Every design decision about it is a decision about how wrong, for how long, and who notices.

17 min readUpdated November 2026Free

Caching is the easiest performance win in system design and the most common source of bugs that only appear in production. The win is obvious: memory is ~1,000× faster than a disk round trip and a cache hit never touches the database. The bugs come from the sentence nobody says out loud — a cache is a copy, and copies go stale.

This lesson is the general theory: where caches live, how data gets in and out, and how to reason about staleness. The Redis lesson is the specifics of the cache most designs use.

Where caches live

From the user outwards:

Layer Example Typical hit latency What it is good at
Browser Cache-Control: max-age 0 ms Static assets, a user’s own repeated requests
CDN edge CloudFront, Fastly, Cloudflare 5–30 ms Static files, public pages, anything identical for every user
Reverse proxy nginx, Varnish under 1 ms + network Whole responses in front of an app
In-process Caffeine, a Map with a TTL ~100 ns Tiny, hot, read-mostly data: config, feature flags, hot keys
Distributed Redis, Memcached ~0.5 ms Shared state across app instances; the default “cache” in a design
Database Postgres buffer pool, MySQL InnoDB pool ~µs once in RAM Everything — and you get it for free
The point

The cheapest cache is the one you already have. A Postgres instance with enough RAM keeps the hot working set in its buffer pool and serves an indexed lookup in well under a millisecond. Before adding Redis to “fix” a slow query, check the query has an index and the box has memory. A cache in front of a missing index hides the bug and adds a consistency problem.

Getting data in: the four strategies

Cache-aside (lazy loading)

The application checks the cache; on a miss it reads the database, then writes the cache.

value = cache.get(key)
if value is null:
    value = db.query(key)
    cache.set(key, value, ttl)
return value

It is the default for good reason: only data someone asked for gets cached, and a cache outage degrades to slower reads, not errors. The costs are a slow first request per key, and the races in the next section.

Read-through

Same flow, but the cache loads from the database on a miss, so application code only ever talks to the cache. Common in libraries (Caffeine’s LoadingCache) and some managed caches. Behaviourally it is cache-aside with the logic moved.

Write-through

Every write goes to the cache and the database together, before acknowledging. The cache is always warm for data that has been written, and reads after writes see fresh values. The cost is write latency and caching data that may never be read.

Write-behind (write-back)

Writes go to the cache and are acknowledged; the cache flushes to the database later, often batched. Fastest writes of all, and anything not yet flushed is lost if the cache node dies. Only for data you can afford to lose or rebuild — view counters, analytics events — never for orders or money.

Invalidation: the hard part

The famous joke is about cache invalidation being one of the two hard problems, and it is hard for a concrete reason: the database and the cache are two systems updated by separate operations, and there is no transaction that spans both.

Update the cache, or delete it? On a write, delete the key and let the next read reload it. Setting the new value directly races: two writers can update the database in one order and the cache in the other, leaving the cache permanently wrong until its TTL. A delete can’t be reordered into a wrong value.

Delete before or after the database write? After. Delete-then-write lets a concurrent reader reload the old value into the cache in the gap, and it stays there.

Where candidates lose it

Even “write the database, then delete the cache” has a race. A reader misses, reads the old value from the database, pauses; a writer updates the database and deletes the key; the reader wakes and writes the old value into the cache. It is rare, it is real, and the answer an interviewer wants is that a TTL bounds the damage — every cached entry expires eventually, so a stale value cannot live forever. Never cache without a TTL.

For stronger guarantees:

Choosing a TTL

A TTL is a statement about how stale this data is allowed to be. Ask the product question, not the technical one:

Add jitter — a random ±10% on each TTL. Keys written together otherwise expire together, and a deploy that warms the cache at 09:00 schedules a mass expiry for 10:00.

When the cache hurts you

Stampede

A hot key expires and every concurrent request misses at once and hits the database together. The fix is to let exactly one request reload it while the rest wait or serve the stale value.

A popular key expires and many concurrent requests miss at once. Without protection every one of them queries the database. With one loader admitted per key, the database is touched once and the remaining requests read the cache the loader fills. one popular key expires — 20 concurrent requests…20 of themRediskey expired1 loader admitted19 poll for the filled cachePostgres1 queryUnprotected, the same picture sends 20 queries — at the exact moment the key is hottest.A fixed sleep for the waiters is not enough: if the loader is slower, the herd arrives anyway.
Cache stampede: one loader per key is admitted to the source; the rest read what it writes.

The mechanics — SET NX as a loader lock, probabilistic early refresh, serving stale while revalidating — are in the Redis lesson.

Penetration

Requests for keys that don’t exist always miss, because there is nothing to cache, so each one hits the database. A scraper enumerating random ids becomes a database load test. Cache the absence too: store a short-TTL tombstone for “not found”, or put a Bloom filter of valid ids in front.

Cold start

A cache restart or a new region starts at a 0% hit rate, and the database receives the full read load it was sized to never see. Warm critical keys before taking traffic, and size the database to survive a cold cache at reduced traffic, not at peak.

The arithmetic of hit rate

Effective latency is hit_rate × cache_latency + miss_rate × db_latency. With a 1 ms cache and a 20 ms database:

Going from 90% to 99% looks like a 10% improvement. It is a 10× drop in database load. That is why hit rate is the metric to graph, and why a deploy that drops it from 99% to 90% can take the database down without changing a line of query code.

Eviction policies, briefly

When the cache is full, something goes. LRU (least recently used) is the default and right for most workloads. LFU (least frequently used) is better when a few keys are reliably popular and a one-off scan should not push them out. TTL-only with no eviction is wrong for a cache — when it fills, writes fail. In Redis, that is allkeys-lru or allkeys-lfu, never noeviction, for a cache.

Saying it in an interview

Say it like this

“Product pages read-through from Redis, cache-aside, 60-second TTL with jitter. Writes go to Postgres and then delete the key, and a CDC consumer deletes it again so admin edits can’t leave it stale. Hot keys get a single-loader lock so an expiry doesn’t stampede the database, and unknown ids get a 30-second tombstone. At checkout I read the price from Postgres, not the cache — that’s the one place a stale value costs money.”

The follow-ups, and the one-line answers

  1. “How do you keep the cache consistent with the database?” Write the database, delete the key, TTL as a backstop; CDC-driven invalidation for writes that bypass the service.
  2. “Why delete instead of update?” Concurrent updates can land in the cache out of order; a delete can’t leave a wrong value behind.
  3. “What happens when the cache goes down?” Cache-aside degrades to the database, so the database must survive that load, possibly with rate limiting in front.
  4. “Write-behind?” Only for data you can lose: counters, analytics. Never for orders.
  5. “How do you pick the TTL?” From how stale the product can tolerate, per data type, with jitter.
  6. “How would you cache a personalised page?” Cache the shared fragments (product details) and assemble per user; don’t cache the whole page per user unless the hit rate justifies the memory.