Why you are doing this at all
If you put a cache in front of a slow endpoint, the endpoint gets fast. Everybody knows this, and it's why caching is usually treated as performance work, like picking a better index.
Now do the arithmetic on what you've just built.
Say the endpoint takes 100,000 requests a second and the cache answers 99 percent of them. The database behind it sees 1,000 requests a second. So the database is sized for 1,000, because nobody pays for capacity they never use. If the cache goes away, the database is asked for 100,000 requests a second, and it can only do 1,000.
A cache stops being an optimisation the moment your backend cannot survive without it. At that point the cache isn't making the system fast. It's the only reason the system is up.
So what happens on the day the cache goes away? Every request misses, and all 100,000 a second arrive at a database sized for 1,000. That's 100 times its normal load.
The number you want is that 100: how many times more work your backend does when the cache stops answering. One division gives it to you. Before, the backend gets the miss rate times the traffic. After, it gets all of the traffic. If you divide the second by the first, the traffic cancels out and you're left with 1 / miss rate, which is 1 / (1 - hit rate). This multiple is the cache's blast radius: how much the load on the backend grows if the cache is lost. Do that division for every cache you put in a design.
Here it is at three hit rates. Each answer is a multiple of the backend's normal load.
- 90 percent hit rate. The miss rate is 0.10, and
1 / 0.10is 10. If you lose the cache, the backend takes 10 times its usual load. - 99 percent hit rate.
1 / 0.01is 100, so the backend takes 100 times its usual load. - 99.9 percent hit rate.
1 / 0.001is 1000, so it takes 1000 times.
A higher hit rate means a smaller miss rate, and a smaller miss rate makes this number bigger. Each nine you add to the hit rate, going from 90 to 99 to 99.9 percent, makes the system faster and makes the failure ten times bigger.
Caching has two parts: choosing a strategy, and invalidation. Invalidation means removing or replacing a cached entry when the data behind it changes.
There are only three ways to invalidate, and they differ in who pays. If you let the entry expire, the reader pays, because they sometimes see out-of-date, or stale, data. If you delete the entry when the data changes, the writer pays, with extra work and extra code. If you change the key when the data changes, nothing is ever invalid and nobody pays anything. The third is the best and the least used.
What are you buying
There are three reasons to cache, and each one leads to a different design.
Latency. The data is far away or slow to compute. You want the cache close to the reader. So you lean toward in-process caches, which live in the application's own memory, and edge caches, which sit in a content delivery network (CDN) near the user. Staleness becomes the main cost.
Load. The backend can't take the traffic. You want a high hit rate on the expensive queries, and those aren't always the popular ones. The main risk becomes the cache being unavailable.
Cost. The backend charges per request or per unit of compute. This works like load, except a miss costs money rather than time. That changes how long a TTL you can justify. The TTL, or time to live, is how long an entry stays in the cache before it expires.
When not to cache
If the data changes more often than it's read, the cache adds work instead of saving it, because every change rewrites an entry that almost nobody reads. If a miss costs about as much as a hit, you've added a network hop and a consistency problem and saved nothing. If correctness needs the current value every time, you need a linearizable read, one that is guaranteed to see the latest write, rather than a cache. If you cache it anyway, you serve a stale value and call it correct.
If you can't say what your hit rate will be, you can't say what you're buying. Measure first, then cache.
The toolkit
Where a cache can live
A cache isn't one thing in one place. A request can be answered from any of six layers. They differ in what a read costs, in how you invalidate them, and in who else can see what's in them.
| layer | read cost | invalidation | the catch |
|---|---|---|---|
| browser or client | free | you cannot. It is gone | once sent, it is stale until its TTL |
| CDN edge | ~10 to 50 ms | purge, propagates in seconds | shared across users, so per-user data needs care |
| reverse proxy | ~1 ms | purge, immediate | one more tier to operate |
| in-process | ~100 ns | per instance, needs a broadcast | N instances means N copies and N staleness windows |
| shared, Redis or Memcached | ~0.3 to 1 ms in one zone, up to 2 ms across zones | central, immediate | a network hop, and a new availability dependency |
| database buffer pool | free | automatic | you do not control it, and it is per node |
The best way to combine these layers is an in-process cache in front of a shared one. A small local cache with a very short TTL sits in front of a large shared cache, and it does two things. First, it turns a hot key, one that is read far more often than the rest, from a network hop into a memory read. Second, if the shared tier fails, the local cache keeps answering for as long as its own TTL lasts. It costs a few megabytes per instance. The other cost is that N instances now hold N slightly different views of the data. None of them is older than the local TTL, and that's a staleness you should be choosing on purpose anyway.
What to cache
Before you pick a strategy, ask whether the thing is worth caching at all. People often skip this question, and one ratio answers it.
Reads per change. Divide how often the thing is read by how often it changes.
Say a product record is read 5,000 times a second and edited once an hour. That's about 18 million reads per change, so cache it as hard as you can. Now say a per-user dashboard is viewed once a minute, and its inputs change eight times a minute. That's 0.125 reads per change, and caching it is more work than not caching it. You fill an entry, invalidate it and fill it again, and almost nobody reads a filled entry. Below about one read per change, a cache costs more work than it saves.
An entry built from several parts goes out of date as soon as any part changes, so its change rate is the sum of its parts' change rates. If you cache a page built from twenty fragments, the cached page changes twenty times as often as any one fragment. So when you choose how big a thing to cache, you're also choosing its reads-per-change ratio.
Same underlying data, cached at three different sizes. One product record read 5,000 /s changes 1 /hour = 0.00028 /s reads per change ≈ 18,000,000 → cache it, with a long TTL A category page composed of 20 such products, taking the same read traffic so only composition changes read 5,000 /s changes 20 x 0.00028 = 0.0056 /s reads per change ≈ 890,000 → still worth caching, at 1/20th the ratio A personalised dashboard, 8 live inputs, per user read 1 /minute changes 8 inputs x 1 /minute = 8 /minute reads per change = 0.125 → caching this costs more than it saves ──────────────────────────────────────────────────────── Composing n parts multiplies the change rate by n, so it divides reads per change by n. 18,000,000 became 890,000 on nothing but composition. That is the entire cost of coarse-grained caching, and it is why full-page caching holds up for anonymous pages and collapses for personalised ones. Rule of thumb: above ~10 reads per change, cache. Below ~1, do not. In between, measure before deciding.
That gives you a choice of size, often called granularity. If you cache fine, in small pieces, each entry is reused by many requests and rarely changes. The cost is many lookups to build one response. If you cache coarse, in large pieces, one lookup serves a whole response. The cost is that the entry is invalidated whenever anything inside it changes. The usual answer is to cache fine and make the many lookups cheap, and the in-process tier is there for exactly that. Twenty local memory reads cost less than one network round trip.
How data gets into the cache
There are three read strategies, and the first is by far the most common.
Cache-aside, also called lazy loading. The application checks the cache. On a miss, it queries the database and then writes the result into the cache. The cache knows nothing about the database. This is the default for three reasons: it's simple, it only caches what is asked for, and if the cache is down the system gets slow rather than broken. Its cost is a race between a reader and a writer, shown in the product page example below. The race is easy to miss, and it does happen in production.
Read-through. The cache itself knows how to fetch on a miss, so the application only ever talks to the cache. The application code is cleaner, and there's one place to put coalescing: when many requests miss the same key, one of them fetches it and the rest wait for its answer. The cost is that every request goes through the cache, including misses. If the cache is down, you're down. With cache-aside, you were only slow.
Refresh-ahead. Shortly before a popular entry expires, a background job refreshes it, so no reader ever waits for a miss. This works well for a small set of expensive keys that you know will stay popular. Applied to everything, it wastes work refreshing entries nobody asked for. Its advantage is that a miss a user would have waited for becomes a background job instead.
How writes interact with the cache
There are four write strategies, and they differ in what the write does to the cache entry.
Write-around. The write goes to the database and leaves the cache alone. The entry gets cached later, on the next read. This is simple, and it's correct when the entry wasn't in the cache. If the entry was already cached, the old value stays there until it expires.
Write-invalidate. The write goes to the database and then deletes the cache key, and the next read fills it again. This is the most common approach in practice. It's also the one with the race in the product page example below.
Write-through. The write updates the database and the cache in the same operation. The cache always holds the entry, and the entry is always current. Writes get slower, and the cache fills with things that may never be read. So it suits data that is read straight after it's written, and wastes memory otherwise.
Write-back, or write-behind. The write goes only to the cache and is acknowledged straight away. The cache copies it to the database later, in the background, and this copy is called a flush. These are by far the fastest writes. It's also the only strategy where the cache becomes a durability dependency: if the cache dies before a flush, the unflushed writes are gone. That's acceptable for counters, view tallies and metrics, where losing a few seconds of data is fine. It isn't acceptable for anything a user is told was saved.
The three ways to invalidate
Every invalidation strategy takes one of three shapes. To tell them apart, ask who pays.
Let it expire. Every entry has a TTL, and nothing removes entries early. Nothing can go wrong in the invalidation logic, because there isn't any. The cost is that readers can see data up to one TTL old. Twitter analysed 153 of its own cache clusters. It concluded that the TTL is an important, and sometimes the deciding, factor in a cache's working set, the data that readers touch in a given period.
Delete on write. When the data changes, the writer deletes the cache key, and staleness drops to near zero. The catch is that there's rarely just one key. A product's data sits in the entry for that product. It also sits in the category page that lists it, the search results that include it, and the homepage panel that features it. If the price changes, every one of those is now wrong, so the writer has to delete all of them. That means some code somewhere holds the list of entries a product change affects. Somebody writes that list by hand, and it goes out of date the first time someone adds a new cached view and forgets to update it. The delete can also fail, and then the entry stays wrong for a full TTL. If your TTL is a day, it stays wrong for a day.
CDNs have a way to keep that list from going out of date. When a response is cached, it declares what it was built from. So the /category/shoes response is stored with the tags product:42, product:87 and product:103. When product 42 changes, you purge the tag rather than the URLs, and the CDN drops every cached response carrying that tag, wherever it is stored. Fastly calls these surrogate keys, Cloudflare calls them cache tags, and Varnish has xkey. The list still exists. But the code that builds the response also writes the list, at the same moment, so nobody has to remember to update it.
Change the key. Put a version number in the key. When user 42 changes, user:42:v7 becomes user:42:v8. Nothing is invalidated. Nobody asks for the old entry again, and it leaves through normal eviction, which is the cache removing entries to make room. This shape has a property the other two lack: there is no invalidation step, so there is no invalidation step that can fail. If a writer crashes before it bumps the version, readers see the old data, which is exactly what a TTL would have given you. So a failure leaves you in the safe state.
It comes in two variants.
Namespace versioning. One counter covers a whole group, and its value goes into every key in the group. If ver:user:42 holds 7, the keys are user:42:v7:profile, user:42:v7:orders and user:42:v7:feed. To invalidate everything about user 42, you bump the counter to 8. That's one write, and it needs no list of what it affected. Readers now build user:42:v8:profile, which misses and gets filled, and nobody asks for the v7 entries again. It costs you in two ways. Every read needs the version number first, which is one more small lookup. And the v7 entries hold memory until eviction reaches them.
Content addressing. The key is a hash of the content itself. app.9f2c1a.js is named after the bytes it contains. If the file changes, the hash changes, and the file gets a different URL. The old URL still serves the old bytes, and that's correct, because whoever asked for 9f2c1a wanted exactly those bytes. A key can never hold a wrong value, because the key was calculated from the value. That's why you can serve these files with a one-year max-age and never purge anything. The invalidation doesn't disappear. It moves to whatever says which hash is current, and that's the HTML page that references the file. So the assets are cached forever, and the HTML is cached briefly or not at all. Every asset pipeline ships with this arrangement. It only works when the request asks for specific bytes. It's no use for a user's profile, where the reader wants whichever version is current.
Eviction, and why admission matters more
When the cache is full, something has to go, and choosing what goes is called eviction. Most people know LRU, least recently used, and stop there. Research from the last decade says that's the wrong place to look.
That research has two findings that matter here.
FIFO is often as good as LRU. FIFO, first in first out, evicts whatever was written longest ago and ignores how it's used. LRU looks smarter on paper, because it tracks which entries are being read and evicts the one nobody has touched for longest. Compare them on two separate things.
Hit rate. You'd expect LRU to win here, but Twitter's analysis of 153 production clusters found it mostly doesn't. FIFO matches it on a large number of workloads. LRU only pulls ahead when the cache is far too small for the working set. In that case the cache evicts constantly, so choosing the right entry to evict starts to matter. If you size the cache properly, you're not in that case.
Cost of running it. On every read, LRU has to move that entry to the front of its list. That's a write to shared state on the read path, so every reader takes a lock. On a machine with many cores, that lock becomes the bottleneck. FIFO writes nothing on a read, because the order was fixed when the entry went in.
So both comparisons point the same way. LRU is barely better at choosing what to keep, and clearly worse at serving reads. Use FIFO unless your cache is much smaller than your working set. If it is, buy more cache before you buy a cleverer policy.
The bigger win is admission, not eviction. Admission is the decision to let an object into the cache at all. "Should I have let this object in?" matters more than "which object should I remove?" Most objects put into a cache are never read again. They take up space from the moment they go in until they're evicted, and nobody uses them. These are called one-hit wonders. The S3-FIFO study of 6,594 traces found that removing them quickly is the main reason most advanced algorithms do better. It also found that most objects LRU evicted had sat in the cache a long time without being read again.
W-TinyLFU, the policy in the Java caching library Caffeine, is the clearest example. It keeps a sketch of what has been requested recently: a small, fixed-size summary that estimates how often each key was asked for. The sketch is built on the same ideas as a Bloom filter. That sketch is the admission test. A new object may only push out an existing one if it has been seen more often. On real workloads, its reported hit rates land within a few percent of Belady's optimum, the hit rate of an ideal policy that knows the future.
Let f = the fraction of admitted objects never read again. effective cache size = capacity x (1 − f) f = 0.2 → you are using 80% of the RAM you paid for f = 0.5 → 50% f = 0.7 → 30% This is arithmetic, not a claim about any workload: f is whatever your traffic makes it, and the only way to know is to measure how many keys are read exactly once. The point is what it implies. If f is large, no eviction policy can help, because eviction only reorders what is already inside. Only refusing entry recovers the space. And you cannot tune your way there from LRU, because LRU has no admission test at all.
How much cache to buy
The size you need is the working set, not the dataset. A 1 TB database whose readers touch only 5 percent of it in a day has a 50 GB working set. Caching 50 GB gets you most of what caching 1 TB would.
The last few points of hit rate have a second cost that the chart doesn't show. Going from 96 percent to 99.5 percent makes reads faster, and it also takes your cache-loss multiplier from 25x to 200x. Buying more cache makes the system faster and more fragile at the same time. You only see the second half if somebody calculates it. This isn't an argument against a high hit rate. It's an argument for knowing the number, and for sizing the backend for a miss rate you could survive.
The method
1. Say what you are buying. Latency, load or cost. This decides which layer the cache belongs in and what counts as a good hit rate.
2. Estimate the working set, not the dataset. This is how much distinct data is touched in a period of time. It gives you the cache size and an expected hit rate.
3. Calculate the blast radius, and check the backend against it. The blast radius is 1 / (1 - hit rate). Ask whether the backend survives that multiple. If it doesn't, say what you'll do: give the backend more capacity, add a local tier, or accept that the cache is a hard dependency and run it like one.
4. Choose read and write strategies. Cache-aside or read-through, and which of the four write strategies. Underneath, the question is what happens when the cache is unavailable, and cache-aside and read-through give different answers.
5. Choose one of the three invalidation shapes, and name the staleness. Expiry, delete-on-write or versioned keys. Then say the number: how stale a read can be, in seconds.
6. Name the stampede controls. TTL jitter, request coalescing and negative caching. All three are cheap, and teams usually add them only after the first incident.
Worked examples, start to finish
Here are four systems. In each one, the obvious approach fails in a different way.
A product page, and the race that puts stale data in the cache
A product page is read 50,000 times a second. It's cached with cache-aside and a 5 minute TTL, and the key is deleted when the product changes. That's the standard setup, and it has a bug that puts wrong data in your cache and keeps it there.
Here is the sequence. A reader misses and starts fetching from the database, which takes 20 milliseconds. While it's fetching, a writer updates the row and deletes the cache key. Then the reader finishes and writes what it fetched into the cache. That value is the old one. The cache now holds a stale value, and it will hold it for the entire TTL, because the delete already happened. This is the stale-set race: a set, the reader's write into the cache, that lands after the delete and puts the old value back.
Take a hotter entry than the product page above: one written
5 times a second. A database read still takes 20 ms. Delete
on write, so every write removes the key and the next read
puts it back.
Every one of those refills spends 20 ms fetching. If a write
lands inside that window, the reader stores the value it read
before the write, and the cache is now wrong.
chance a write lands in a refill
5/s x 0.020 s = 10%
So one refill in ten stores a stale value.
Now the part that decides how bad this is. A stale value is
not short-lived. It sits in the cache exactly as long as a
correct one would, until the next write deletes it. Nothing
distinguishes it, so nothing removes it early.
─────────────────────────────────────────────────────
the cache holds a wrong value 10% of the time
= 2.4 hours a day
On one key, from five writes a second and an ordinary 20 ms
query. Nothing errors, nothing is logged, and the value looks
completely plausible.
Notice the TTL never appears. At 5 writes a second the key is
deleted every 200 ms, so a 300 s expiry never fires and tuning
it changes nothing here.Changing the TTL doesn't help either. On a key written this often, the TTL never fires at all.
So the question is: after a writer deletes the key, how do you stop a reader that was already fetching from putting the old value back?
Delete the key after writing, and move on
This is what most code does, and it works most of the time. It only goes wrong when a read is already in progress at the moment the write lands, and that window is a few milliseconds wide. But the value written in those few milliseconds then sits in the cache for the whole TTL. Most codebases have this bug today.
Short TTL, delete after commit, and a delayed second delete
There are three cheap fixes, and you can do all three together. Delete after the database commit rather than before, so a failed write doesn't throw away a good entry. Keep the TTL short, so a bad value can't sit there for long. And schedule a second delete about a second later, to clear anything a slow reader wrote in the meantime.
This is the standard answer, and it's much better. The cost is that it works on odds, not on certainty. The second delete is a guess at how long the race window lasts, and a reader slower than your delay still wins. The bug becomes rare, but not impossible.
Make the set conditional, or make invalidation unnecessary
There are two things to do.
First, stop accepting every write a reader sends to the cache. Facebook's memcache work does this with leases. On a miss, the cache gives the client a 64-bit token tied to that key, and the client must send the token back when it sets the value. A delete on that key cancels the token, so the cache refuses the racing reader's set. The stale value never lands. The same paper uses the token for stampede control too. The cache hands out a token for a key at most once every 10 seconds and tells other readers to retry shortly. So one mechanism does both coalescing and the lease check.
Second, remove the invalidation step. Versioned keys don't have one. The writer bumps the version, and readers of the new version can't be served the old value, because they're asking for a different key. There's no delete to lose, so there's no window for a reader to write into.
What you give up:
Leases need the cache itself to understand tokens, because it hands one out on a miss and checks it on the set. You can't build this in your own code. If your code reads the token, checks it and then sets the value, that's two round trips with a gap between them, and the gap is the same race you were trying to fix. The check has to happen inside the cache, as a single operation. So you need either a cache that offers it built in, which is what memcached-style leases are, or a Lua script that Redis runs on the server for you. Either way, it's code you own and maintain, not a setting you switch on.
Versioned keys cost you on the read path instead. Every reader needs the current version number before it can even build the key, so that's one extra lookup, usually a small cache entry of its own. And bumping a version doesn't delete the old entries. It only stops anyone asking for them, so they sit in memory until eviction removes them. The faster you bump, the more of your cache holds values nobody will ever request again.
Both cost you something, and both cost less than 2.4 hours of wrong data a day.
A view counter, where the fast write path loses data
A counter goes up by one on every page view: 200,000 increments a second, and it's read rarely. Write-through to the database is out, because that's 200,000 writes a second competing for one row. So the obvious answer is write-back: increment the counter in Redis, and flush it to the database every few seconds.
This is a good design, but people rarely say out loud what it means: the cache now holds the only copy of committed data. Between flushes, those increments exist in one place, in Redis's memory.
200,000 increments/s, flushed to the database every 5 s
unflushed at any moment 200,000 x 5 = 1M increments
If Redis dies before a flush
lost increments up to 1M
and the loss is silent: nothing errored
Redis persistence, with the default appendfsync everysec
a crash can lose the last ~1 s of writes
→ still 200,000 increments
Failover to a replica: replication is asynchronous, so a
promoted replica can be further behind than that.
────────────────────────────────────────────────────────
Flush every 5 s risk 1M increments
Flush every 500 ms risk 100,000, and 10x the
database write load
Write-through risk 0, and 200,000 writes/s
on one row, which is not possible
There is no setting that gives you zero loss and this write
rate. The decision is which trade-off you are willing to accept.For a view counter, losing 1 million increments is usually fine. Say so explicitly in the design, rather than finding out later. For anything a user is told was saved, write-back is the wrong strategy, however fast its writes are.
Write-through, because losing data is unacceptable
The instinct is right, but the arithmetic rules it out. Write-through means 200,000 writes a second, all to the same row. The problem isn't throughput. It's contention: every writer needs the same lock, and a bigger database doesn't change that. The safest strategy here isn't just expensive. It's close to impossible.
Write-back, with a flush interval and a written loss tolerance
Increment in the cache and flush on a schedule. Pick the interval by deciding how many increments you're willing to lose. How many is acceptable is a product question, not an engineering one.
The cost is that the cache now holds committed data, so you have to run it as carefully as you'd run a database. The flush job can also fall behind or fail without any error. Monitor the flush lag, not just the cache.
Notice that this is not a counter
Question the data model. So far you've treated "how many views" as one number that you change. A number that 200,000 writers change at the same time is the worst possible shape for this problem. But the views are an append-only stream of events, and somebody counts them now and then.
So append. Each application instance counts views in its own memory and writes one row every second: that instance's count for that second. The write rate to durable storage is now one per instance per second, not one per view. There's no contention, because no two writers share a row. Once a row is written, it's durable. The count is a sum over a time range, and any query engine does that in milliseconds.
In numbers: 200,000 increments a second from 200 instances becomes 200 durable appends a second, a thousand times fewer writes. If an instance crashes, it loses at most the second it hadn't written yet, about 1,000 increments, instead of the 1 million that write-back puts at risk.
What you give up: the current count is no longer a single read. It's a sum, so you cache the sum and accept that it's a few seconds behind. For a view counter, nobody can tell. It's the wrong answer when the exact live value must be read atomically, as with remaining inventory. That needs a real database transaction updating one row, so every writer queues behind the same lock. If the item is popular, you then have to split the counter into several and add them up on read, which is a separate problem.
The right design depends on the requirement. The count may be allowed to lose a few seconds, it may need to be exact but can lag, or it may need to be exact and live. Ask which one it is before reaching for the cache. If the count must be exact, it isn't a cache problem at all. It's a durable-append problem, or, for a live value like inventory, a transaction.
A key that does not exist
An API takes a product ID and returns the product. It uses cache-aside, the hit rate is 99 percent, and everything is healthy. Then somebody points a scanner at it that tries sequential IDs, and most of those IDs don't exist.
Each of those requests misses the cache, queries the database, finds nothing and caches nothing, because there's nothing to cache. So these requests skip the cache entirely, and the database receives every one of them. Your 99 percent hit rate still holds, and it doesn't help, because these requests could never have been hits. This is usually called cache penetration. The same thing happens by accident whenever a client keeps retrying a resource that doesn't exist.
Both fixes are cheap.
Cache the absence. Store a negative entry, a marker meaning "this does not exist," with a short TTL. The marker is often called a tombstone. A TTL of 30 seconds is often plenty. Now the second request for a missing key is a hit. The TTL is short because the thing might be created later, and you don't want to serve "not found" for an hour after it appears.
Reject before you look. Keep a Bloom filter of the keys that do exist. A Bloom filter is a compact bit array that answers either "definitely not present" or "probably present". That suits this problem, because a "no" is always right. You can refuse the request without touching the cache or the database.
A scanner walks 10,000 IDs that do not exist, at 1,000
requests a second, and it does not stop. Behind the API
there are 1 billion product IDs that do exist.
with nothing
nothing is cached, because there is nothing to cache,
so every single request reaches the database
database queries 1,000/s, forever
with negative caching, TTL 30 s
the first miss stores a "this does not exist" marker,
so each fake ID costs one query per TTL, not one per
request. The scanner keeps hitting them, so this is a
steady rate rather than a burst that dies down.
database queries 10,000 keys / 30 s = 333/s
memory 10,000 x ~50 B = 500 KB
The TTL is the knob. At 60 s it drops to 167/s. Below
10 s it buys nothing, because the scanner takes 10 s to
come back round and the marker has already expired.
with a Bloom filter holding every ID that does exist
What a filter costs per key depends only on the error
rate you pick, never on how many keys you have. It
takes 9.6 bits per key to be wrong 1% of the time, and
14.4 bits to be wrong 0.1% of the time. Take the 1%:
memory 1B real IDs x 9.6 bits = 1.2 GB
Being wrong 1% of the time means 99 of every 100 fake
IDs are rejected before any lookup happens. Only the
other 1% carries on to the cache:
still get through 1,000/s x 1% = 10/s
Do the negative caching first. It costs 500 KB and takes
1,000/s down to 333/s. Add the filter when the volume
justifies 1.2 GB of memory, and 1,000/s becomes 10/s
before the cache is even consulted.The day the cache tier restarts
Everything above assumes the cache is there. Now assume it isn't, because someone flushed it, a deploy restarted it, or the cluster failed over.
At a 99 percent hit rate, the backend is suddenly asked for 100 times its normal load. It can't serve it, and the way it fails matters. Requests queue up and latency rises. Clients time out and retry, and the retries add more load. You now have a retry storm on top of a cold cache, one that starts empty. The cache can't refill quickly, because every refill needs a backend response and the backend is overloaded. This is how a cache restart becomes an hour-long outage.
Assume the cache is there, because it usually is
Nobody chooses this on purpose. It works for a long time, and that's the problem. The hit rate climbs, the backend is sized for the load it sees while the cache works, and you find out the first time the cache goes away. By then the hit rate is high, so the spike is big.
Warm carefully, and give the cache tier its own failover
There are three fixes, for three different failures.
The whole tier restarts. Never put an empty cache straight back under full traffic. Refill it first from a replica or a warm standby. Or bring traffic back gradually, so the cache fills while the database only takes a fraction of the misses.
One node dies. Its share of the keys now misses, and without a plan all of those misses go to the database. Facebook's memcache design keeps roughly 1 percent of its cache servers idle as a gutter pool, a set of spare servers. Clients that would have used the dead node use the gutter pool instead. Gutter entries expire quickly, so nobody has to send deletes to the gutter. A stale entry there ages out on its own.
The tier is unreachable entirely. Put a small cache inside each application process, holding its hottest few thousand keys in its own memory. Each application server can then keep answering with no network call at all, for as long as that local TTL lasts.
The cost is more infrastructure to run, warmup procedures that you must maintain and rehearse, and a local tier that adds its own staleness, up to its TTL.
Treat the hit rate as a budget you spend, not a score you maximise
A higher hit rate isn't always better. It also means a bigger spike when the cache goes away, and usually nobody has worked out how big. So turn the question around: what miss rate can the backend survive? That number belongs to the backend, not the cache. The cache's job is then to keep the miss rate comfortably below it. Any hit rate beyond that point buys latency, not capacity, so judge the money you spend on it as latency work.
Use the hit rate curve to pick the size. If the backend can survive 5 percent of peak traffic, a 95 percent hit rate is enough. Going on to 99.5 percent buys 4.5 more points of hit rate. It also takes the spike your backend faces, if the cache goes away, from 20x to 200x. Either size the backend for the miss rate you want to survive, or accept the cache as a tier-one dependency. That means on-call, replication and capacity planning, as for any critical system. Both choices are reasonable. The incident comes from drifting into the second while believing you made the first.
What you give up: money. A backend sized for 5 percent of peak rather than 1 percent has capacity that sits idle almost all the time. That's the real trade. Someone who can weigh an hour of downtime against a year of spare capacity should make it, and that's usually not the engineer choosing the TTL.
Where it goes wrong
These are ordered by how often they turn up.
1. Treating the cache as an optimisation once the hit rate is high
At a 99 percent hit rate, the backend is sized for 1 percent of the traffic, so the cache isn't an optimisation any more. The system doesn't run without it. Watch for a design that states a hit rate and never says what happens at zero.
2. The stale-set race
The product page example above covers this in detail. Cache-aside with delete-on-write has a race that lasts milliseconds and leaves a wrong value behind for a full TTL. Nothing reports an error. Raising the TTL doesn't reduce your exposure.
3. Uniform TTLs
If many entries are written at about the same time with the same TTL, they also expire at about the same time. A deploy, a warmup script or a burst of traffic fills 1 million entries, and 5 minutes later 1 million entries expire in the same second.
1M cached entries, TTL 300 s, all populated together.
Backend can serve 5,000 req/s.
No jitter: everything expires in the same second
refill demand limited only by
the request rate
→ tens of thousands per second against a 5,000 ceiling
With jitter, expiries spread over the jitter window
peak refill ≈ entries / jitter window
TTL 300 s ± 10% window 60 s 1M / 60 = 16,700/s
TTL 300 s ± 33% window 200 s 1M / 200 = 5,000/s
TTL 300 s ± 50% window 300 s 1M / 300 = 3,300/s
─────────────────────────────────────────────────────────
So the rule is not "add some jitter", it is:
jitter window >= entries / backend refill capacity
At 1M entries and 5,000/s that is a 200 second window,
which is the ± 33% row above, on a 5 minute TTL.
Most implementations use plus or minus 10 percent, which
here is three times too small.4. No negative caching
A request for something that doesn't exist skips the cache completely. So your hit rate gives no protection against the traffic a scanner produces. Cache the absence with a short TTL.
5. Flushing the cache to fix something
During an incident, "flush the cache and see" is a fair instinct. On a system with a high hit rate, it does what an attacker would do: every request misses at once, and the backend takes the full load. If flushing is ever a legitimate operation, it should happen a part at a time, and the tool should refuse to flush everything at once.
6. Tuning the eviction policy when the problem was admission
If most of what you admit is never read again, the eviction policy is choosing between entries that shouldn't be there. LRU has no admission test, so no amount of tuning gives it one. Also check the belief that LRU beats FIFO against your own traffic. Twitter's production analysis found that LRU's advantage shows up mainly in caches that are far too small.
7. Caching things that should not be cached
Large values are one case, because one large value can push out many small, useful ones. Data that changes more often than it's read is another. Per-user data in a shared CDN is worse, because it's a data leak rather than a performance problem. It happens whenever the cache key doesn't include who asked, or the response isn't marked private. The last case is expensive keys sharing a cache with cheap ones. An expensive key is one whose miss costs you something: an aggregation over millions of rows, or a call to an API you pay for per request. A cheap key's miss is one indexed row read. Eviction policies know nothing about either. So a flood of cheap keys can push out the expensive ones, and you've traded a half-millisecond miss for a two-second one.
Cheap keys also tend to change constantly, and that's why they arrive as a flood. Facebook split memcached into separate pools by how often keys change, so the fast-changing keys can't take memory from the slow-changing, expensive ones.
8. Not knowing what a miss costs
Without the cost of a miss, the hit rate means nothing. A 90 percent hit rate makes almost no difference when a miss costs 2 milliseconds. A 90 percent hit rate is the whole design when a miss costs 2 seconds and a database lock. Measure what a miss costs, not just how often you miss. How often you miss tells you nothing on its own.
If you memorise nothing else
| fact | why it matters |
|---|---|
| Losing the cache multiplies backend load by 1/(1 − hit rate) | 99 percent is 100x, 99.9 percent is 1000x |
| Every nine you add to the hit rate multiplies the blast radius by ten | the hit rate is a risk number reported as a performance number |
| Buy the working set, not the dataset | the curve has a knee, and the tail costs 20x the RAM |
| There are three invalidation shapes: expire, delete, re-key | they differ in who pays for staleness |
| Versioned keys have no invalidation step to fail | a crashed writer degrades to "stale", which is safe |
| Cache-aside plus delete-on-write has a stale-set race | a millisecond window, TTL-length consequences, no error |
| Raising the TTL makes each stale set last longer | it trades frequency for duration, not exposure |
| Leases make a set conditional on no delete since the miss | Facebook's memcache fix, and it also does coalescing |
| Write-back makes the cache a durability dependency | say how many seconds of acknowledged writes you may lose |
| Jitter window >= entries / backend refill capacity | plus or minus 10 percent is usually far too small |
| A missing key bypasses the cache entirely | cache the absence, then add a Bloom filter if volume warrants |
| Admission matters more than eviction | eviction only reorders what should not be there |
| FIFO often matches LRU in production | LRU's edge is mostly in severely undersized caches |
| An in-process tier in front of a shared one is the best structural move | it absorbs hot keys and survives the shared tier |
| A miss you have not priced makes the hit rate meaningless | 90 percent is either irrelevant or everything |
What is expected at each level
Mid-level
Know cache-aside and be able to walk through it: check the cache, read the database on a miss, then fill the cache. Know what a TTL is, and that a longer one means more staleness. Know the difference between write-through and write-back, at least in terms of what each one risks.
You aren't expected to raise the stale-set race, admission policies or blast radius without being asked. You are expected to answer sensibly when asked. If the interviewer says "what happens if the cache is empty," a good mid-level answer is "everything goes to the database, so I would want to know whether it can take that."
Don't treat cache invalidation as a detail. Every time you add a cache, say how an entry gets removed or replaced when the data changes.
Senior
You lead this part of the discussion, and three things must come up without prompting.
Which of latency, load or cost you are buying. It decides the layer, the size, and what a good hit rate means. A design that adds a cache without saying what it's for can't be evaluated.
The invalidation strategy, with a staleness number. Name the shape (expiry, delete or re-key), then say how stale a read can be, in seconds. "We invalidate on write" is half an answer. The other half is what happens when that invalidation fails.
What happens when the cache is unavailable. The question isn't whether it will be. Give the multiplier, and say whether the backend survives it. Senior candidates miss this more than anything else in the topic, because the cache is the part of the design that looks finished.
Two things are disqualifying: proposing write-back for data a user is told was saved, and having no stampede control at all on a high-traffic cache.
Staff+
The question changes from how to add a cache to what the cache is allowed to be responsible for.
Invert the hit rate into a budget. Ask what miss rate the backend can survive, and treat that as the requirement. Any hit rate beyond that buys latency, not capacity, and should be paid for as latency work. Teams drift into a hard dependency while believing they have an optimisation. Pointing out that drift is the most useful thing you can do here.
Prefer designs with no invalidation step. Versioned and content-addressed keys remove a whole kind of failure, rather than making it less likely. Use them especially where data is built from other data, because that's where the hand-written list of keys to delete goes out of date fastest.
Say what may be stale, and for how long, per read path. Don't use one global TTL. Different reads can tolerate different staleness. One number for all of them means you overpay on some reads and serve wrong data on others.
Design the cold start. Work out the refill rate, the warmup procedure, the jitter width, and what serves traffic while the cache is empty. This failure lasts longest, and it's almost never in the design.
And say what you would not build. Each of these can cost a team a whole quarter.
One is a custom eviction policy, when nobody measured the one-hit-wonder rate and the fix was admission. Another is a cache invalidation service that subscribes to every table and sends out deletes, in one region, when versioned keys would have removed the problem entirely. A third is write-back for data whose possible loss nobody would sign off on.
Another is a second shared cache tier to lift the hit rate from 97 to 99 percent. That triples the blast radius, from about 33x to 100x, for a latency gain users can't notice. Another is replicating the cache across regions, when the read could have been served stale from the local region with a timestamp. And the last is the whole cache, when the real problem was one missing index that the query plan would have shown.
Sources
Every number attributed to a paper or company below comes from that published source. The multiplier, jitter, race and sizing arithmetic is worked out in the article, with its inputs stated.
- Scaling Memcache at Facebook, Nishtala et al., NSDI 2013. Leases: a 64-bit token tied to a key, issued on a miss and checked on set, and cancelled by a delete so a racing set is refused. The same token, issued at most once every 10 seconds per key, for stampede control. A gutter pool of roughly 1 percent of servers, with short expiries so it needs no invalidation at all. And separate pools, to stop fast-changing keys evicting slow-changing expensive ones.
- A large scale analysis of hundreds of in-memory cache clusters at Twitter, Yang, Yue and Rashmi, OSDI 2020. 153 production cache clusters and over 80 TB of traces. TTL is an important and sometimes defining parameter of a cache's working set. FIFO works best for a large number of workloads, often matching LRU, and LRU's advantage shows up mainly when the cache is severely undersized.
- FIFO Queues are All You Need for Cache Eviction, Yang, Zhang et al., SOSP 2023, and the S3-FIFO write-up. A study of 6,594 traces. Quickly removing one-hit wonders is the main reason most advanced policies do better. Most objects evicted by LRU had sat in the cache a long time without being reused.
- TinyLFU: A Highly Efficient Cache Admission Policy, Einziger, Friedman and Manes, ACM Transactions on Storage 2017, and the Caffeine efficiency notes on W-TinyLFU. The mechanism is an admission test, not a choice of what to evict. The frequency sketch builds on Bloom filter theory. Reported hit rates land close to Belady's optimum on real workloads.