All posts
System Design Mastermind · F07
  • System design
  • Interview prep
  • Caching
  • Redis

Caching: hit ratios, invalidation and stampedes

Foundations F07. What to say after you draw the cache box: why the hit ratio decides everything, where caches live, cache-aside and read-through, write-through vs write-behind vs delete-on-write, TTLs and invalidation (and the race that leaves stale data), LRU and LFU eviction and sizing, stampedes when a hot key expires, and hot keys and cold caches. Each idea is told as a story you'll remember, with a lab that turns cache size, popularity and TTL into a hit ratio, database load and herd size.

22 Oct 2026 · 24 min read · interactive

Share

Start here

A cache keeps a copy of an answer somewhere faster and closer than where the answer really lives, so the next person who asks gets it without the slow trip. Almost every design in an interview has one, and almost every candidate draws it. What separates a Senior answer is everything around the box: how many reads it actually catches, what happens when the data changes, what happens when a popular entry expires, and what happens when the cache itself goes away.

This page covers eight ideas: the hit ratio (why it decides everything), where caches live, reading through a cache (cache-aside and read-through), writing (write-through, write-behind, write-around and delete-on-write), invalidation and staleness, eviction and sizing, stampedes when a hot key expires, and the failure modes: hot keys, cold caches and a cache the system can no longer live without. CDNs and HTTP caching were introduced on the request-journey page; consistent hashing for spreading keys over cache nodes was on the replication and sharding page.

The one story for this page

Diwali week at a mithai shop

Picture a busy sweet shop in the week before Diwali. The kitchen at the back makes everything fresh, but slowly. So the shop keeps a glass counter at the front, stocked with packed boxes of what people buy most. One week touches every idea on this page:

  • Nine customers in ten want kaju katli, soan papdi or motichoor laddoo; the counter holds only those, and most people are served in seconds. (hit ratio)
  • Boxes on the counter, more on a back shelf, the kitchen behind that. (layers)
  • The counter boy checks the counter first, and only walks to the kitchen if it's empty, bringing back an extra box. (cache-aside)
  • The owner raises the price of kaju katli. Does he relabel the boxes now, later, or throw them out? (writes)
  • A customer pays yesterday's price because an old label is still on a box. (invalidation)
  • The counter is small. When a new sweet arrives, which tray goes to the back? (eviction)
  • The jalebi tray empties at 7 pm and twenty customers shout at the kitchen at once. (stampede)
  • Everyone wants the same dry-fruit gift box; and on the first morning after a holiday the counter is empty and the kitchen is swamped. (hot keys, cold cache)

The shop is made up for teaching; it is not any real business.

✅ Seen: a company said so (cited)🔶 Inferred / typical🧭 Interview choice

Why cache: the hit ratio decides everything

A cache is worth exactly as much as the share of reads it answers; the database feels the misses, so going from a 90% to a 99% hit ratio cuts its load ten times.

The story · remember it like this

The chaiwala on platform 4

At a busy railway station, the chaiwala on platform 4 doesn't brew a fresh cup for each passenger. He keeps a big kettle of ready chai on the stove. When a train pulls in, he pours a hundred cups in two minutes. That's a hit: the answer was already made.

Now and then someone asks for black coffee with no sugar. He has to make it from scratch, and while he does, three other customers wait. That's a miss. The kettle is only worth having because almost everyone orders the same thing.

If the platform were full of people who each wanted something different, the kettle would be useless however big it was.

What it really is
  • A cache stores the result of something slow or expensive (a database query, a computed page, a remote API call) in fast memory, keyed by what was asked.
  • Hit ratio = hits ÷ all lookups. Miss ratio = 1 − hit ratio. Average latency ≈ cache time + miss ratio × backend time.
  • The backend's load is reads × miss ratio. At a 90% hit ratio the database sees 10% of reads; at 99% it sees 1%. Ten times less from nine more points.
  • Caches only help reads that repeat. Real traffic is usually skewed: a few items get most reads (often modelled as a Zipf-like distribution). With strong skew a small cache catches most reads; with flat, long-tail traffic even a huge cache catches little.
  • What to cache: things read far more often than they change, that are expensive to build, and where a slightly old answer is acceptable.

Precise point: a cache with a low hit ratio can make things slower on average, because every miss pays for the cache lookup and the database.

In a real system ✅ Seen · Meta, Jun 2022

Meta's TAO (the cache in front of its social graph) "serves more than one quadrillion queries a day". Meta notes that even with a 99% hit rate, that is more than 10 trillion cache fills a day: the 1% still has to come from somewhere (Meta Engineering, Jun 2022).

Facebook's 2013 memcache paper describes a cache handling "billions of requests per second" over "trillions of items" for over a billion users (NSDI, Apr 2013).

Web request traces follow Zipf-like popularity "with the exponent varying from trace to trace" (Breslau et al., 1999); that skew is why caches work at all.

Trade-offs
  • Speed and lower database load, paid for with memory, another system to run, and data that can be stale.
  • Before adding a cache, check the cheaper fixes: a missing index, a bad query, or a read replica. A well-indexed database answering in a few milliseconds may be fast enough.
Say it in the interview

Reads are 100× writes and the top 20% of products get about 90% of views, so a cache holding those should hit around 90%. That turns 200,000 reads a second into about 20,000 at the database. The miss rate is what I size the database for.

Trap

Drawing a cache box without saying what's in it, the expected hit ratio, or why the reads repeat. "Add Redis" isn't a design; "cache the top products for five minutes, ~90% hits" is.

Where caches live: from the phone to the database

Caches sit at every layer (client, CDN, app memory, a shared cache cluster, the database's own memory); the closer to the user, the faster, but the harder to update and the fewer people share it.

The story · remember it like this

Your mother's kitchen

Salt, haldi and chilli live in the masala dabba next to the stove: one reach, no walking. Rice and dal live in the pantry: a few steps away, much more of it. Anything else comes from the kirana shop down the road: slow, but it has everything.

Nobody keeps the whole kirana shop next to the stove. The dabba is tiny and holds what's used every day. And when the price of haldi changes at the shop, the haldi in the dabba doesn't know.

Each layer is closer and faster than the one behind it, holds less, and goes out of date on its own schedule.

What it really is

From closest to the user to furthest:

  • Client cache (browser, mobile app): zero network. You can't reach in to clear it; rely on expiry and versioned URLs.
  • CDN / edge: static files and cacheable API responses near users (the request-journey page covers it).
  • In-process cache (a map inside each app server): nanoseconds to microseconds, no network hop. Each server has its own copy, so copies disagree and every server warms up separately. Good for small, hot, rarely-changing data (config, feature flags, the top match's score for one second).
  • Distributed cache (Redis, Memcached, a managed service): one shared pool across all app servers, around a millisecond per round trip in the same zone, scaled by adding nodes. The usual answer in interviews.
  • Database buffer cache: the database keeps hot pages in RAM on its own. Often enough before you add anything.

Typical design: CDN for media, a distributed cache for hot reads, and a small in-process layer only for the very hottest keys.

In a real system ✅ Seen · Netflix, Oct 2024

Netflix's EVCache (built on Memcached) runs about 22,000 server instances in 200 clusters, handles 400 million operations a second and holds about 2 trillion items (14.3 PB), replicated across four regions (InfoQ, Oct 2024).

In-process caches stay small for a reason: with 50 app servers you keep 50 copies, each warmed and invalidated separately (🔶 typical, not a company figure).

Trade-offs
  • In-process: fastest and no extra system, but each server holds its own copy, which wastes memory, warms up slowly and can disagree with the others.
  • Distributed: one copy everyone shares and can invalidate, at the cost of a network hop and another cluster to run and keep alive.
Say it in the interview

Media goes through the CDN. Product data sits in a Redis cluster shared by all API servers. For the one or two keys everyone reads every second I'd add a one-second in-process cache on each server, so those reads never leave the box.

Trap

Putting a large or user-specific cache in each app server's memory. With 50 servers you have 50 cold, inconsistent copies, and the load balancer sends the same user to a different one each time.

Reading: cache-aside and read-through

Cache-aside: the app asks the cache, and on a miss reads the database and fills the cache itself; read-through is the same, but the cache does the database read for you.

The story · remember it like this

The student's notebook

Meera keeps a notebook of answers she has looked up. When a question comes, she checks her notebook first. If the answer's there, done in seconds.

If not, she walks to the library, finds the book, and copies the answer into her notebook before she goes back to her desk. Next time, it's in the notebook.

She only writes down what someone actually asked, so the notebook never fills with answers nobody needs. But the first person to ask each question always waits for the library trip. And if the library book is corrected, her notebook still has the old answer.

What it really is

Cache-aside (also called lazy loading or look-aside), the default:

  • get(key) from the cache. Hit → return it.
  • Miss → read the database, set(key, value, TTL) in the cache, return it.
  • On a write, update the database, then delete the key (next section).

Read-through: the app only talks to the cache; on a miss the cache library or service loads from the database itself. Same behaviour, cleaner app code; CDNs work this way.

Properties of both:

  • Only data someone asked for is cached, so memory isn't wasted.
  • If the cache dies, the app still works (slower), because the database has everything.
  • Every first read of a key is a miss, and cached data can be stale until it expires or is deleted.
In a real system ✅ Seen · AWS docs

AWS's ElastiCache guide describes lazy loading: on a miss the app reads the database and writes the result to the cache. Its advantages: only requested data is cached, and a failed node isn't fatal, just slower. Its disadvantages: a miss costs three trips (cache, database, cache write), and data can be stale (AWS docs, checked Oct 2026).

Facebook's memcache is "demand-filled look-aside": web servers read memcache, fall back to the database on a miss, then set the value (NSDI, Apr 2013).

Trade-offs
  • Cache-aside: simple, resilient to cache failure, works with any database. The app owns the cache logic in every service that reads that data.
  • Read-through: one place for the loading logic, but the cache layer must understand your database, and it's more infrastructure.
Say it in the interview

Cache-aside with a TTL: read the cache, on a miss read Postgres and set the key for five minutes. If Redis is down we fall through to the database, which is sized to survive that for a while.

Trap

Forgetting the miss path's cost. On a miss, the user waits for cache + database + cache write, and a cache that is often cold makes the average worse, not better.

Writing: write-through, write-behind, write-around

When data changes you can update the cache along with the database (write-through), update the cache and the database later (write-behind), or skip the cache and just delete the old entry (write-around with delete-on-write, the usual choice).

The story · remember it like this

The waiter's order pad

At a dhaba, a waiter takes your order. Three ways to handle it:

He types it into the billing system at the counter before he leaves your table, and also writes it on his pad. Slower for you, but the system and his pad always match. (write-through)

He writes it on his pad and walks away; he'll enter it into the system when the rush dies down. Very fast. But if he loses the pad, those orders never happened. (write-behind)

He enters it straight into the system and tears out the old page from his pad. Next time anyone asks about your table, he looks it up fresh. (write-around, delete on write)

What it really is
  • Write-through: write the database and the cache together, on every write. Reads are fresh (if both writes succeed) and never miss on recently written data. Costs: slower writes, and the cache fills with data that may never be read.
  • Write-behind (write-back): write the cache and return; flush to the database later in batches. Fastest writes and fewer database writes. Risk: if the cache dies before the flush, data is lost. Use only where that's acceptable (counters, metrics, view counts).
  • Write-around: write only the database; the cache fills on the next read (cache-aside). Pairs naturally with delete-on-write.
  • Delete, don't set: after the database commit, delete the cache key rather than writing the new value into it. Deletes are idempotent and safe to retry; two concurrent sets can land in the wrong order and leave the older value.

The real problem in all of these: the database and the cache are two systems, and no single transaction covers both. One write can succeed and the other fail. That's why TTLs stay on as a backstop even with careful invalidation.

In a real system ✅ Seen · Facebook, 2013

Facebook's memcache: a web server updates the database, then deletes the key. "We choose to delete cached data instead of updating it because deletes are idempotent" (NSDI, Apr 2013).

AWS's ElastiCache guide shows write-through with a 300-second TTL, and recommends combining write-through with lazy loading, because a new or replaced node starts empty (AWS docs, checked Oct 2026).

Caches are not always read-heavy: in Twitter's study of 153 production cache clusters, more than 35% were write-heavy (over 30% of operations were writes) (OSDI, Nov 2020).

Trade-offs
  • Write-through: fresher reads, slower writes, cache full of things nobody reads. Write-behind: fastest writes, real risk of losing data.
  • Delete-on-write is the safest default for data in a database; write-behind only for data you can afford to lose or rebuild.
Say it in the interview

Writes go to Postgres; after the commit we delete the product's key and let the next read refill it. Every key also has a TTL, so if a delete is ever lost the entry corrects itself within five minutes.

Trap

Proposing write-behind for orders or payments because it's fast. If the cache node dies before the flush, a customer's order disappears. Name what can be lost before choosing it.

Invalidation: how stale is too stale?

Every cached copy can be out of date; decide how stale each kind of data may be, then use TTLs as the floor and delete-on-change (ideally driven by the database's commit log) for anything that must be fresh.

The story · remember it like this

The old price sticker

The mango seller marks a box "₹600 a dozen" in the morning. At noon, a fresh truck arrives and he drops the price to ₹500. He changes the board but forgets the sticker on one box.

A customer picks up that box, pays ₹600, and is annoyed when she sees the board. Nothing was lost from the shop; the sticker just went on telling an old truth.

His fixes: write the date on every sticker and peel off anything older than a day (a TTL); peel the sticker off whenever the price changes (invalidation); for the expensive Alphonso box, check the board every time (don't cache it).

What it really is

Three tools, usually together:

  • TTL: every entry expires after N seconds. Bounds staleness to at most N, needs no coordination, and fixes any invalidation you missed. Shorter TTL = fresher but more misses.
  • Delete on change: when data changes, delete the cached key. Best done from the database's commit log or change stream (change data capture), so invalidation can't be forgotten by one code path and can be replayed if lost.
  • Versioned keys: put a version in the key (product:42:v7). A change bumps the version; old entries are never read again and age out.

The famous race in cache-aside: reader A misses and reads value 42 from the database; a writer changes it to 43 and deletes the key; A then sets the old 42 into the cache. Now the cache is wrong until the TTL. Fixes: leases or version checks on set, and a short TTL as the backstop.

Precise point: a cache in front of a database gives eventual consistency at best. If a read must be exactly current (a balance before a payment, a seat before booking), read the database for it.

In a real system ✅ Seen · Meta, Jun 2022

Meta describes exactly that race: a cache fill of x = 42 arrives after the invalidation for x = 43, leaving the cache wrong. Its Polaris service measures it, and TAO went from six nines (99.9999%) to ten nines (99.99999999%) of cache writes consistent within five minutes (Meta Engineering, Jun 2022).

Facebook's memcache uses leases to stop stale sets: a miss gets a lease token, a delete invalidates it, and a set with an invalid token is rejected. Invalidations come from the database commit log through a daemon (mcsqueal), so they can be replayed if lost (NSDI, Apr 2013).

HTTP caches have their own tools: Cache-Control: max-age=600, stale-while-revalidate=30 lets a cache serve a slightly stale copy while it refreshes in the background (RFC 5861, May 2010).

Trade-offs
  • Short TTLs: simple and fresh, more misses. Long TTLs with delete-on-change: high hit ratio, but every write path must invalidate correctly.
  • Commit-log-driven invalidation is the most reliable, and more infrastructure (a CDC pipeline) to build and run.
Say it in the interview

Product details can be a minute stale, so a 60-second TTL is enough. Price and stock change the order total, so we delete those keys from the change stream on every update and re-read stock from the database at checkout.

Trap

Saying "we'll invalidate on write, so the cache is always consistent". Two systems, no shared transaction, races between fills and deletes: say what staleness you accept and where you go to the database instead.

Eviction and sizing: what stays when memory is full

A full cache must drop something; LRU (drop the least recently used) is the safe default, LFU suits steady favourites, and TTL expiry is a separate thing. Size the cache for the hot set, not the whole dataset.

The story · remember it like this

The fridge door

The fridge door has six slots. Milk, curd, butter, water bottles, the green chutney, the pickle. When someone brings home a new jar of jam, something has to move inside the fridge to make room.

Most families move the thing nobody has touched for longest: the pickle that's been sitting since last month (least recently used). Some move the thing used least often overall, even if someone took it out yesterday (least frequently used). And the milk is thrown out on its date whether there's room or not (expiry).

Nobody tries to fit the whole kitchen on the fridge door. It holds what the family reaches for every day.

What it really is
  • Eviction happens when memory is full; expiry (TTL) happens when time is up. They're different: an entry can be evicted before its TTL, and an expired entry is dropped even with room to spare.
  • LRU: evict what was used least recently. Good default; one big scan of rarely-used keys can push out the hot ones.
  • LFU: evict what is used least often. Keeps steady favourites; slow to forget something that used to be popular, so real implementations decay counts over time.
  • FIFO / random: simpler; surprisingly often close to LRU when the cache is not tiny.
  • Sizing: estimate the hot set (the data that gets most reads), not the whole dataset. Memory per node gives node count; check throughput too, and take the larger.
  • If the cache keeps evicting hot items (hit ratio falls as traffic grows), you need more memory or smaller values, not a cleverer policy.
In a real system ✅ Seen · Redis docs

Redis lets you choose with maxmemory-policy: noeviction (return errors when full), allkeys-lru, allkeys-lfu, allkeys-random, and volatile-* versions that only evict keys with a TTL, plus volatile-ttl. Its LRU and LFU are approximated: Redis "samples a small number of keys at random and then evicts the ones with the longest time since last access", tunable with maxmemory-samples (Redis docs, checked Oct 2026).

In Twitter's study of 153 cache clusters, FIFO "often shows similar performance as LRU" at reasonable cache sizes, and TTLs were often short: over a quarter of workloads had a mean TTL under twenty minutes (OSDI, Nov 2020).

Trade-offs
  • Bigger cache: higher hit ratio, but with diminishing returns: the last items you add are the least popular.
  • noeviction protects data but turns a full cache into errors; for a pure cache, an allkeys-* policy is usually right.
Say it in the interview

The hot set is the top 20% of products, about 20 GB: one node by memory, but 200,000 reads a second needs two by throughput, so two, plus a replica each. LRU eviction, and a TTL on every key so stale entries leave even if memory is free.

Trap

Treating TTL as the eviction policy, or sizing the cache to hold the entire database. Caches are sized for the hot set; the rest stays on disk.

Stampede: when a hot key expires

When a popular entry expires, everyone who asks in the next few milliseconds misses together and sends the same query to the database; coalesce those misses into one fetch, refresh before expiry, and add jitter to TTLs.

The story · remember it like this

The prasad counter

At a temple fair, volunteers hand out prasad from a big tray. When the tray empties, two hundred people turn and shout at the kitchen at once. The cooks can't make two hundred trays; they can barely make one, and now they can't hear each other.

The temple's fixes:

  • One volunteer goes to the kitchen; everyone else waits for that one tray. (coalescing)
  • Someone brings the next tray while the current one is still a quarter full. (early refresh)
  • Two counters' trays are refilled at different times, not both at 7:00 sharp. (jitter)
What it really is

Also called the thundering herd or dogpile. Size of the herd ≈ the key's reads per second × the time one database fetch takes. 50,000 reads/s on one key × a 20 ms query = 1,000 identical queries at once.

Fixes, most important first:

  • Request coalescing (single flight): the first miss for a key fetches; other requests for that key wait for its result. Done per app process, or across processes with a short lock or lease in the cache.
  • Refresh before expiry: refresh hot keys in the background, or probabilistically: each reader near the end of the TTL has a small, rising chance to refresh early (the XFetch approach). Serve the slightly old value meanwhile (stale-while-revalidate).
  • Jitter: add randomness to TTLs (300 s ± 10%) so keys written together don't expire together.
  • Don't let the herd through: rate-limit fills per key, and keep serving stale data if the database is struggling.
In a real system ✅ Seen · Facebook, 2013

Facebook's memcache leases also tame the herd: a server hands out a lease token for a key "only once every 10 seconds per key"; other clients are told to wait briefly and retry. For keys prone to this, peak database queries fell from 17K/s to 1.3K/s (NSDI, Apr 2013).

Discord's data services in front of its message database: "The big feature our data services provide is request coalescing." When many users request the same row at once, the database is queried once and the result goes to every waiting request (Discord, Mar 2023).

Vattani, Chierichetti and Lowenstein showed that a simple probabilistic early-refresh rule (refresh with a chance that rises as expiry nears) is optimal for preventing stampedes (PVLDB vol. 8, 2015).

Trade-offs
  • Coalescing makes waiting requests a little slower (they wait for one fetch) and protects the database completely for that key.
  • Serving stale while refreshing keeps latency flat but shows slightly old data; fine for a score that's one second old, not for a seat count at checkout.
Say it in the interview

The live score key gets 50,000 reads a second, so if it expires, a thousand identical queries hit the database. We coalesce misses per key, refresh it in the background every second before it expires, and jitter TTLs on everything else.

Trap

Thinking a high hit ratio means the database is safe. A 99.9% hit ratio can still hide a herd of a thousand queries every time the one hot key expires.

Try it: How much does the cache really catch?

Enter a workload. The lab works out the hit ratio from cache size and popularity, what the TTL costs, how many reads still reach the database and how fast the average read is, how big a herd the hottest key sends when it expires (with and without coalescing), and what the database faces if the cache restarts empty.

Start from

A shopping app's product pages during a festive sale: 5M products, 200,000 page reads a second, popularity heavily skewed towards the deals on the home page. Cache holds the top 1M products (20%) for 5 minutes; the database and its replicas handle 40,000 reads a second.

What we're sizingNumberHow we got itSo we decide
1 · Hit ratio: size, then expiry
Hit ratioA cache only helps reads that repeat. With skewed popularity a small cache catches most reads; with flat popularity it catches little. A TTL then costs one miss per item per TTL, which matters only for items read less often than once per TTL.88.5%
cache holds 1.0M of 5.0M items = 20% of items
with skew 1, the top 20% of items get 89.9% of reads → best possible hit ratio 89.9%
each cached item misses once per TTL: hit share = λ × 300 s ÷ (1 + λ × 300 s), λ = that item's reads/s
summed over the cached items → 88.5% (1.5% lost to expiry)
Useful but leaky. Check the table: more memory buys less and less, so compare a bigger cache against making each miss cheaper.
Cache holdsBest hit ratioDB reads/s
1.0% of items71.2%58K
5.0% of items81.3%37K
10% of items85.6%29K
20% of items89.9%20K
50% of items95.7%8.7K
2 · What reaches the database, and how fast reads are
Database readsEvery point of hit ratio near the top is worth a lot: going from 90% to 99% cuts database reads by ten times. The miss rate, not the hit rate, is the number the database feels.23K/s · 57.7% of capacity
misses = 200K/s × (1 − 88.5%) = 23K/s vs 40K/s the database handles
average read = 500 µs (cache) + 11.5% × 5.0 ms (database) = 1.1 ms, vs 5.0 ms with no cache
cache size: 1.0M × 20 KB = 20.0 GB → 1 node by memory (100 GB each), 2 by throughput (100K ops/s each)
The database runs at 57.7%. Run 2 cache nodes (plus replicas), sized by throughput.
3 · The hottest key expires
Same query sent to the database at onceA key always lives on one cache node, so adding nodes doesn't spread it. And at the moment it expires, everyone asking for it misses together: a stampede. Coalescing, early refresh and a copy in each app server's memory are the fixes.62
On a miss
hottest key = 200K/s ÷ H(5.0M, 1) = 12K reads/s (6.2% of all reads)
uncoalesced: misses during one 5.0 ms fetch = 12K/s × 0.005 s = 62 identical queries
one cache node takes about 100K ops/s; this key alone needs 0.1× that
No herd worth worrying about at these numbers. Add jitter to TTLs anyway so many keys don't expire in the same second.
4 · The cache restarts empty
Database load, first seconds after a cold startOnce a cache carries most of the load, the database is sized for the misses, not for the traffic. The cache has quietly become something the system can't run without.5.0× capacity
every read misses: 200K/s ÷ 40K/s = 5.0×
Treat the cache as critical: replicate it, warm a new node from a warm one before it takes traffic, and shed or rate-limit load to the database while it fills.
5 · Verdict for these numbers
Our pickCache-aside works: 2 cache nodes88.5% of reads hit, so the database sees 23K reads a second (57.7% of what it handles) and the average read drops from 5.0 ms to 1.1 ms. Size the cache by throughput. Watch the one risk left: if the cache restarts empty, the database would get 5.0× its comfortable load, so warm it up or let traffic back in gradually.

Try: on Product pages, a cache holding a fifth of the products catches about nine reads in ten; halve it and database reads rise by about a third. On Order history, multiply the cache size by ten and watch how little the hit ratio moves; the average read is even slower than with no cache, because every miss pays the cache trip too. On Live cricket score, the hit ratio is near perfect, yet every 2-second expiry of the top match sends over a thousand identical queries to the database: switch on coalescing. The hit ratio assumes an ideal cache that keeps the most popular items and reads that arrive at random (Zipf popularity); real LRU caches do a little worse. Cache and database limits are rounded, typical teaching values.

Hot keys, cold caches, and a cache you can't live without

One key always lives on one cache node, so a hot key overloads it however many nodes you add; and once the cache carries most of the load, losing it (or restarting it empty) can take the database down with it.

The story · remember it like this

The first morning after the holidays

During the wedding season, every customer at the sweet shop asks for the same silver-foil dry-fruit box. One counter boy handles that box, and his queue goes out of the door while the others stand idle. More counter boys don't help unless they all get that box. (hot key)

Then the shop closes for three days. On the first morning back, the counter is empty. Every single customer has to wait for the kitchen, which was only ever staffed to fill the gaps on the counter, not to serve the whole street. The queue takes the whole morning to clear. (cold cache)

The owner learns two things: give the popular box to every counter, and never open with an empty counter; fill it from the back shelf first.

What it really is

Hot keys

  • Hashing spreads keys, not load: one celebrity post or one live match is still one key on one node.
  • Fixes: replicate the hot key to several nodes (or key#1 … key#N copies) and read a random one; keep it in each app server's memory for a second; split the value if it's large.

Cold cache and the cache as a dependency

  • Once the hit ratio is high, the database is sized for the misses. If the cache restarts empty, the database sees every read: often several times its capacity.
  • Protect it: replicate cache nodes; warm a new node or cluster from a warm one before it takes full traffic; bring traffic back gradually; rate-limit or shed load to the database during recovery.
  • When a cache node fails, don't rehash all its keys onto the survivors at once; that can overload them too.

Cache penetration (briefly): lookups for keys that don't exist always miss. Cache the "not found" result for a short time, or check a Bloom filter first.

In a real system ✅ Seen · Facebook, 2013

Facebook replicates hot keys within a memcache pool: when one server handling 500K requests/s isn't enough, two replicas each take 500K/s, whereas splitting the key space would leave both at 1M/s. Failed servers are covered by a small "Gutter" pool, about 1% of a cluster's memcache servers, which cut client-visible failures by 99%; Gutter exists partly because rehashing a failed server's keys onto the others could overload them with hot keys (NSDI, Apr 2013).

The same paper warms a new, cold cluster by reading from a warm cluster instead of the database, which brings it back to full capacity in hours rather than days.

Trade-offs
  • Replicating hot keys or caching them in-process spreads load, at the cost of more copies to invalidate.
  • A highly effective cache is a critical dependency: plan its replication and warm-up like a database's, not like an optional speed-up.
Say it in the interview

Once the cache takes 95% of reads, the database is sized for the 5%. So the cache is replicated across zones, new nodes are warmed from a replica before taking traffic, and the hot keys are copied to several nodes and held for a second in each app server.

Trap

"If the cache goes down, we just read from the database." At a 95% hit ratio that's 20× the database's normal load. Say how you'd survive it, or admit the cache is now critical.

Remember it

One line per idea. Read this the night before.

  1. Hit ratio: the database feels the misses; 90% → 99% hits is 10× less database load. Caches only help reads that repeat.
  2. Layers: client, CDN, in-process, distributed cache, database memory; closer is faster but harder to update. Default to a shared Redis/Memcached.
  3. Cache-aside: check cache, on a miss read the database and fill; survives a dead cache, pays a slow first read.
  4. Writes: update the database, then delete the key (deletes are idempotent); write-through for freshness, write-behind only for data you can lose.
  5. Invalidation: TTL as the floor, delete on change (from the commit log) for what must be fresh; read the database when it must be exact.
  6. Eviction: LRU by default, LFU for steady favourites; TTL is not eviction. Size for the hot set, by memory and by throughput.
  7. Stampede: herd = hot key's reads/s × fetch time; coalesce misses, refresh early, jitter TTLs.
  8. Failure: a hot key lives on one node, so replicate it; a cold or dead cache sends every read to the database, so treat the cache as critical.

Check yourself

Answer out loud, then open.

Your API serves 100,000 reads a second, and the database handles 15,000. What hit ratio do you need, and what would make you doubt you'll get it?

At least 85%, and more like 90–95% for headroom.

  • Misses = 100,000 × (1 − hit ratio) must stay under 15,000, so hit ratio ≥ 85%. At 95%, the database sees 5,000/s, a third of its capacity.
  • Doubt it if reads don't repeat: many distinct items with flat popularity (search over a long tail, per-user data read rarely). Then a cache barely helps.
  • Doubt it if TTLs are short compared to how often each item is read.

Say it I size the database for the misses, and I can show the hit ratio from the popularity of the data.

Walk through cache-aside for a product page, including the write path. What can go wrong?

Read: get product:42 from Redis; hit → return. Miss → read Postgres, set product:42 with a 5-minute TTL, return.

Write: update Postgres, commit, then delete product:42.

What can go wrong:

  • The delete fails or is lost: stale until the TTL, which is why the TTL stays.
  • The fill-after-delete race: a slow reader sets an old value just after the delete. Leases or version checks on set, plus the TTL, cover it.
  • A cold cache sends every read to Postgres.
Why delete the cache key on a write instead of setting the new value?

Because the database and cache can't be updated in one transaction, and sets can land out of order.

  • Two writers set v1 then v2 in the database, but their cache sets arrive v2 then v1: the cache now holds the old value indefinitely.
  • A delete has no order problem: deleting twice is the same as once (idempotent), and the next read fetches the current value.
  • The cost is one extra miss after each write, which is cheap unless the key is very hot.

Facebook's memcache made the same choice for the same reason.

A live-score key gets 50,000 reads a second and a 1-second TTL; the query takes 20 ms. What happens every second, and how do you fix it?

Every time it expires, about 50,000 × 0.02 = 1,000 requests miss together and send the same query to the database: a stampede, every second.

Fixes:

  • Coalesce misses: one fetch per key (per process, or with a short lock in the cache); the others wait 20 ms for its result.
  • Refresh the key in the background before it expires, and serve the current value meanwhile.
  • Keep it in each app server's memory for a second, so most reads never reach the cache at all.
When would you choose write-behind, and when would you refuse it?

Choose it when writes are very frequent, each one is small, and losing the last few seconds is acceptable: view counts, like counters, metrics, "last seen" timestamps.

Refuse it for anything a customer would notice losing: orders, payments, messages, bookings. A cache node dying before the flush loses those writes.

Say it Write-behind trades durability for write speed, so I only use it where I could rebuild or shrug off the loss.

Your Redis cluster restarts and comes back empty. The hit ratio was 95%. What happens and how do you prevent it next time?

The database suddenly sees 20× its normal read load (100% of reads instead of 5%), slows down, times out, and retries make it worse. The site can go down even though the database is healthy.

Prevention:

  • Replicate cache nodes so one failure doesn't empty the cache.
  • Warm new nodes from a replica or a warm cluster before they take traffic.
  • Bring traffic back gradually, rate-limit fills to the database, and serve stale or degraded pages meanwhile.

Say it At a 95% hit ratio the cache is no longer optional; I plan its failure like the database's.

An interviewer asks: "Can a cache in front of the database be strongly consistent?" What's an honest answer?

Not cheaply, and usually not worth trying.

  • The cache and database are separate systems with no shared transaction, so there's always a window where one has changed and the other hasn't, and races between fills and deletes.
  • You can shrink the window a lot: delete on commit from the change log, leases or versions on set, short TTLs. Meta measures ten nines of consistency within five minutes, which is still not "always".
  • For reads that must be exact (balance before payment, seat at booking), read the database, or the leader, directly.

Say it The cache is eventually consistent by design; I choose per kind of data how stale is acceptable.

Where you'll use this in the series

Sources

Checked October 2026. Cache behaviour comes from the Redis and Amazon ElastiCache docs, RFC 5861 and the papers listed (Facebook memcache 2013, Twitter cache workloads 2020, XFetch 2015, Breslau et al. 1999); company figures are as published on the dates shown (Meta 2022, Discord 2023, Netflix via InfoQ 2024) and may have changed since. The lab's hit ratios assume Zipf popularity and an ideal cache; its cache and database limits are rounded, typical teaching values.

System Design Mastermind · Foundations

Series home

All of Foundations

18 publishedStart here: the concepts every design uses, each told as a story you'll remember.

F01

How a request travels: DNS, load balancers, gateways and open connections

Name → address (DNS) → open a secure line once and reuse it (TCP, TLS) → nearby copies for static files (CDN) → spread and guard the work (load balancer, gateway) → find colleagues inside (discovery) → keep a line open for live updates.

20 min · interactive Preview
F02

The interview framework: requirements, numbers and scope before boxes

Agree what users must do (three core requirements) → put numbers on how well (p99 latency, availability, durability, staleness) → say what's out of scope → sketch the simple end-to-end design → go deep only where a number breaks it.

22 min · interactive Preview
F03

Back-of-envelope estimation: from users to servers in one minute

Users × actions ÷ 86,400 (≈10⁵) = average per second → × peak factor → split reads and writes → storage = count × size × time × copies → bandwidth × 8 bits → in flight = rate × latency → servers = peak ÷ (capacity × 60%) + 2 spares.

20 min · interactive Preview
F04

APIs and real-time communication: REST, gRPC, retries, webhooks and live updates

Nouns + HTTP verbs (user from the token) → REST outside, gRPC inside → cursor pagination → POST with an Idempotency-Key, retries with backoff and jitter → add, don't change → poll for rare updates, SSE for one-way live, WebSockets for both ways → webhooks are at-least-once → thin connection gateways with resume and push fallback.

22 min · interactive Preview
F05

Databases: data models, indexes and transactions

Relational by default (each fact once, keys, constraints) → key-value / document / wide-column / graph only for a named access pattern → B-tree for reads, LSM for heavy writes → composite index with equality columns first, then the sort → one transaction per local change, made durable by the write-ahead log → know your isolation level → win races with a conditional write and a unique constraint.

24 min · interactive Preview
F06

Replication and sharding: copying and splitting your data

Copies scale reads and survive failures (leader + followers); splits scale writes and size (shards). Replicate first; shard only when data size or write rate outgrows one leader → pick the shard key from the main query → hash it into many fixed slots so growth moves ~1/(N+1) → name your hot key and your one cross-shard query.

25 min · interactive Preview
F07

Caching: hit ratios, invalidation and stampedes

Cache what is read far more than it changes → say the expected hit ratio and size the database for the misses → cache-aside with a TTL; on writes, update the database then delete the key → coalesce misses on hot keys and jitter TTLs → plan for the cache failing or restarting empty, because by then the system depends on it.

You're reading this Preview
F08

Consistency, CAP and quorums: what replicas promise

Say what each operation needs, not what the system is: strong (linearizable) for money, stock, seats and uniqueness; read-your-writes for a user's own data; eventual for counts, feeds and pages → during a partition, strong operations fail on the minority side, the rest keep serving (CAP) → on a normal day, strong costs a round trip to a quorum (PACELC) → with N copies, W + R > N makes reads overlap the latest write, but it isn't linearizability.

25 min · interactive Preview
F09

Coordination: clocks, leaders, locks and consensus

Don't order events across machines by wall-clock time; let one leader assign the order → elect that leader by majority vote with increasing terms, so a split network can't elect two → give it a lease so a dead leader is replaced without anyone proving it died → and a fencing token the storage checks, so a paused old leader can't do harm → use consensus (Raft) for the few decisions that must be agreed, not for every request.

25 min · interactive Preview
F10

Queues and event streams

Put a queue between work that can wait and the caller, so a spike becomes lag instead of an outage → use a task queue for jobs and an event log (Kafka) when many consumers need every event, replay or per-key order → key by the entity whose order matters and size partitions for peak consumers → deliver at least once and make consumers idempotent → retry a few times with backoff, then dead-letter → scale on lag → publish through an outbox, never "save, then publish".

25 min · interactive Preview
F11

Idempotency, exactly-once and sagas

Treat a timeout as unknown, never as failed → make writes idempotent by design (set, don't add; client IDs; conditional writes) → for the rest, an idempotency key per intent, stored with the result in the same transaction as the effect → consumers deduplicate by message ID in the same transaction → exactly-once holds only inside one boundary → across services, use a saga of local steps with compensations, not 2PC → compensable steps first, the pivot (capture payment) next, retryable steps last, on a durable orchestrator.

25 min · interactive Preview
F12

Scaling and performance

State latency as a percentile at a stated load → size each tier to the utilisation where its p99 is still flat (pooled, least-request balancing lets you run hotter) → budget fan-out calls against the page deadline, hedge stragglers → scale up first, scale out stateless tiers → name the shared resource (database, lock, connections) that caps the speed-up → find the saturated resource and cut work per request → pre-scale known peaks, autoscale on the signal that saturates → under overload, shed the lowest-priority work fast and budget retries.

24 min · interactive Preview
F13

Reliability and disaster recovery

Turn the target into a downtime budget → cut hard dependencies, because chains multiply → spread copies across zones (cells for blast radius) → timeouts from the deadline, one layer of jittered retries under a budget → circuit breakers with fallbacks and a bulkhead per dependency → fast, non-flapping health checks (readiness checks dependencies, liveness doesn't) → statically stable: spare capacity already running, config cached → PITR plus tested restores, because replicas copy mistakes → the cheapest DR strategy that meets RTO and RPO, drilled.

25 min · interactive Preview
F14

Observability and safe deployments

Metrics to notice, traces to locate, logs to explain (joined by a trace ID) → watch latency percentiles, traffic, errors and saturation → set an SLO per user journey and treat 1 − SLO as an error budget → page on burn rate over two windows, not on CPU → canary every change on a slice with automated analysis against a baseline → keep every version compatible with its neighbours (expand, migrate, contract) so rollback is always possible → ship dark behind flags, and stage config like code → when it breaks: one commander, mitigate first, blameless postmortem.

25 min · interactive Preview
F15

Security essentials for system design

Prove who the caller is (slow salted hashes, MFA, passkeys, rate-limited login) → carry identity in short-lived signed tokens with revocable refresh tokens, or in sessions you look up → delegate with OAuth code flow + PKCE, sign in with OpenID Connect → check this user against this object on every request, least privilege for people and services, audit logs → TLS 1.3 at the edge, mTLS inside, no trust from network location → envelope encryption with a KMS, secrets in a vault, tokenise what you needn't keep → treat all input as data (parameterise, encode, CSRF tokens, no user-chosen fetches) → absorb floods and abuse at the edge.

26 min · interactive Preview
F16

Search, feeds and geo building blocks

Search: analyse text into terms → inverted index of sorted postings → BM25 or hybrid (BM25 + vectors via RRF) retrieval of ~1,000 candidates → learned ranker → shards with replicas, fed from the database by CDC, refreshed every second. Typeahead: precomputed top-k per prefix in memory. Feeds: push IDs into followers' timelines, pull celebrities at read time, hydrate, filter, rank, page with cursors. Geo: index by cell (geohash, S2, H3), search the cell plus neighbours, exact distance on the few candidates.

27 min · interactive Preview
F17

Data pipelines: batch and stream

Pick batch or stream by how fresh each output must be. Get data in with log-based CDC (snapshot, then the WAL) and schemas that evolve safely; land raw events as Parquet in lakehouse tables partitioned by date. Batch jobs map, shuffle and reduce one partition and overwrite it, so retries and backfills are safe. Stream jobs window by event time, fire on watermarks, decide whether late events wait, correct or drop, and checkpoint state with offsets for exactly-once effect, with transactional or idempotent sinks. Reprocess by replaying retained data (Kappa) rather than keeping two codebases (Lambda).

28 min · interactive Preview
F18

AI foundations: inference, RAG and agents

Latency is time to first token (prefill reads the prompt, compute-bound) plus output tokens × time per token (decode, memory-bound), so stream answers and limit by tokens. GPU memory is weights plus a KV cache per request; long prompts, not users, fill it. Continuous batching shares each weight read across many requests, cutting cost per token by 10× or more until time per token hits its target. Route easy requests to small models, cache shared prompt prefixes, quantize carefully. RAG retrieves, reranks and cites a few permission-filtered chunks; agents are tool-calling loops with budgets, idempotent tools and approval for irreversible steps. Evaluate every change on an eval set, and design so a model fooled by prompt injection still can't do damage.

30 min · interactive Preview

More posts