Caching
Read first: Latency numbers that matter, Choosing a database
A cache is a copy you can serve faster than the source of truth, and it is wrong unless you invalidate it. A TTL only bounds how long a missed invalidation can last. When a hot key expires, single-flight or a lease is the difference between one database read and a herd.
A product page that is cheap at a dozen requests a second becomes a database incident at the moment a timer reaches zero. The cache was hiding the database. Expiry, a restart, or a lost invalidation puts the database back on the path for one key, for everyone at once.
The gap that makes a cache worth it is in Latency numbers that matter. A main-memory reference is 100 ns. A round trip inside one datacenter is 0.5 ms, about 5,000 of those references. A hit in another process still pays a network round trip and skips the query. A hit in the process that already has the bytes can stay in memory. The database remains the source of truth. Choosing a database is still where the row lives, and a cache in front of it does not change the invariant on that row.
Core concepts
Three write policies
Cache-aside. The application reads the cache. On a hit, it returns that value. On a miss, it reads the database and fills the cache. The cache is demand-filled: a key nobody reads costs you nothing. The miss pays an extra lookup, and the first reader after a restart pays the database for every key they touch.
Write-through. The write updates the cache and the database together, and the acknowledgement waits for both. The next read can hit. The writer pays both systems on the slow path. “Together” is still two systems. If you update the cache and the database write then fails, readers see a value that never committed. If you commit the database first and the cache update then fails, treat the cache key as gone and let the next read refill. Leaving the old cache value in place is how a failed write-through becomes a stale read. When the database is the truth, order the database first, then the cache, and delete the key if the second step fails.
Write-back. The write acknowledges once the cache has the value, and a later flush reaches the database. It is faster, and it is easier to lose. A crash between the acknowledgement and the flush drops the write. That is acceptable for a view counter you can stand to under-count for a few seconds. It is the wrong policy for a balance or for seats remaining. If losing the write means selling a seat you do not have, the speed came from lying about durability.
TTL versus invalidation
Invalidation is how you get correctness. On a write, delete the key, or replace it with the value you just committed. Deleting is the safer of the two when the writer might be holding an older copy: the next read misses and refills from the database, instead of pinning whatever the writer thought was current. The 2013 memcache paper treats invalidation on write as the correctness path, in front of a fleet of databases. That design is Facebook’s memcache. A router added in front of the cache years later is a different story. Do not merge them.
A TTL is a lifetime. When it expires, the next read misses. The TTL does not know that a write happened. It bounds how long a stale value can survive a lost invalidation: a dropped delete, a writer that forgot, a replica of the cache that missed the message. Invalidation is the plan. The TTL is what remains when the plan fails. Set it to the staleness you can explain. A day on a price is a day of the old price after a lost delete. Thirty seconds is thirty seconds of the same bug. Neither number makes the delete optional.
If you skip invalidation and rely on the TTL alone, you have chosen to be wrong until the timer. That can be the right product choice for a ranking that tolerates a minute of lag. It is a bad choice for a price the warehouse just changed, unless you say the bound out loud.
Stampede, single-flight, and leases
A stampede is many misses at once, all hitting the database. It happens when a hot key expires, when a cache process restarts, and when a deploy sets every TTL on the same second so they fall due together. The database sees a spike for data that was cheap a moment ago. The spike slows the fill, which lets more requests join. That loop is the outage, and it shows up as a periodic cliff rather than as steady load.
Single-flight means one filler per key. The first miss computes the value. The other misses wait for that computation and share the result. You turn N database reads into one. The waiters still pay the filler’s latency. You saved the database. You did not make a slow query fast. If the filler fails, the waiters need a bounded retry, or they all become a second herd. A lock around the fill is the same idea: only the holder reads the database. If the holder dies and the lock has no timeout, every waiter sits until a person notices. When the lock expires, allow one new filler, not every waiter at once.
A lease, in that memcache design, is a token handed out on the miss. The filler’s set must present the token. A stale token is rejected. The token does two jobs. One filler populates the key while others wait, which is the stampede control. And a slow filler cannot write an old value over a newer one. Filler A reads a price of 20 and stalls. A writer commits 18, the key is invalidated, and filler B stores 18 under a newer token. A wakes up and sets 20 with the old token. The cache rejects it. Without the lease, the page reverts to a price you already replaced. The symptom is a value moving backward in time, which is a worse bug than a miss.
Probabilistic early expiration spreads the cliff. A reader, with a probability that rises as expiry gets closer, refreshes the key while everyone else still hits the current value. Misses land across the window instead of on one instant. That is the XFetch idea. The idea is the spreading. You can use it in a design without a formula you have not derived: near expiry, a growing fraction of readers recompute, and the rest keep hitting.
The same storm exists one tier out. An origin shield is an extra cache in front of the origin so a miss storm does not all land on one database. DNS and CDNs is that tier for bytes you were going to cache at the edge anyway. If the only shield in your design is one application cache, the database meets the herd the moment that cache misses together.
Hot keys
A hot key is one key a large fraction of traffic wants. More cache machines do not split it. The key has one owner. Partitioning and sharding says the same thing about a database: a hot key is not fixed by more partitions. Shards that do not hold this key do not change the requests pinned to the machine that does.
You have three moves that actually move load.
Coalesce. Single-flight on that key, so the owner does one fill and many waits. This cuts misses. It does not cut a flood of hits against one process, if the hits themselves are the problem.
Replicate that key to a few copies and let clients pick one. One machine is no longer the only hit path. You now invalidate every copy. A missed invalidation leaves that copy stale until its TTL.
Put a small local cache on each application process for the one hot key. Hits can be memory references instead of datacenter round trips. Invalidation has to reach every process, or each local TTL is the staleness you just accepted. If every process expires the local copy on the same second, you built a smaller stampede in front of the shared cache.
A cache does not absorb writes to a counter everyone updates. The last-seat row in Transactions and isolation stays hot on the write path no matter how fast the product description is served. Cache the description. Do not decrement seats inside the cache and call it a sale. The transaction has to land on the database row, or two buyers will each see “available” in a copy.
What does not belong in the cache
Cache a value when many reads hit it between writes, and when you can invalidate it or you can name the staleness. Otherwise you added a hop and a way to be wrong.
The seat counter, the balance, and the uniqueness check do not belong. The bug looks like a successful purchase. The database transaction was the protection, and the cache served a copy of “still available.”
A key read once per write does not belong. Cache-aside then does a get, a database read, and a set, which is more work than the database read. Nobody arrives to hit the value you stored. Count reads between writes before you add the cache. If the count is about one, skip it.
Personalized HTML does not belong in a shared cache whose key is only the URL. A CDN cache key is usually the URL plus selected headers. Dynamic HTML is a poor cache citizen. Bytes of media are a good one. If the response depends on who is logged in and the user is not part of the key, you serve one person’s page to another. The symptom is crossed accounts.
Anything you cannot lose does not belong in a write-back cache. The symptom is a crash after the acknowledgement and before the flush, which deletes a write the caller thinks happened.
An authorization decision you just revoked does not belong behind a long TTL with no delete. The user still looks allowed. If you cannot delete the key at revoke time, the TTL is the whole policy. Keep it short, or do not cache the decision.
Caching absence is the case that looks like caching nothing. A client scanning random product ids should not all reach the database. Store a short-lived “no such product.” If you never invalidate that entry, a product created a second later stays invisible until the TTL. Absence is a value. It needs the same delete-on-write rule, and a shorter lifetime, because being wrong about absence hides a row that exists.
A worked example
One product page. Cache-aside. Writes delete the key. A 60-second TTL is the backstop if a delete is lost.
Assumptions, because none of these is a measured company:
- The site serves 1,000,000 product-page views a day when nothing is launching.
- During a launch, one product key takes 500 requests per second. That is about 43 times the site-wide quiet rate, a spike you must declare, not a 2x to 5x factor on a normal day.
- A healthy database fill takes 25 ms. A same-datacenter round trip on the 2012 teaching list is 0.5 ms, so 25 ms is 50 of those round trips: a query, not a ping.
- If the herd piles up, the fill stretches to 500 ms. That figure is the failure, not the steady state.
- A remote cache hit costs a datacenter round trip, 0.5 ms. A hit from memory already in the process is the 100 ns reference.
quiet site
1,000,000 / 86,400 = 11.6 requests/s
shortcut: 1,000,000 / 100,000 = 10 requests/s
launch assumption against that quiet rate
500 / 11.6 = about 43 times
healthy fill in round trips
25 ms / 0.5 ms = 50
herd with no single-flight, healthy fill
Little's law: concurrency = rate * time
500 * 0.025 = 12.5 database reads of one row
same herd if the pile-up stretches the fill to 500 ms
500 * 0.5 = 250 database reads of one row
remote hit versus memory
0.5 ms = 500,000 ns
500,000 ns / 100 ns = 5,000 memory references
At the expiry instant, with no coalescing, about 13 requests arrive during a healthy 25 ms fill and all read the database for the same row. If that load stretches the fill to half a second, 250 requests are in flight on that one row. The connection pool fills with identical work. Latency becomes the database queue. The TTL did what it was set to do.
Single-flight makes that window one database read. Everyone else waits on the filler. A healthy fill costs the waiters about 25 ms. A fill that has already blown out to 500 ms costs them 500 ms, once, instead of 250 copies. Single-flight caps load. It does not hide a slow database from the request that is waiting. Put a timeout on the wait, or one stuck fill holds every thread that asked for the key. An error the client can retry is cheaper than a pool with nothing left.
The lease version of the same launch is about correctness, not about the count of 250. Filler A misses, takes token 1, reads a price of 20, and stalls. A writer commits 18 and deletes the key. Filler B stores 18 with token 2. A wakes and sets 20 with token 1. The cache rejects the stale token. The page stays at 18. Without the lease the page flips back to 20 until some later write. Shoppers see a price you ended.
Write-back would acknowledge the change to 18 when the cache stores it, and flush later. If the process dies first, the database still says 20, and the next fill brings 20 back. You told a shopper the price moved. Write-through does not acknowledge until the database has committed 18 and the cache was updated or deleted. The shopper waits on the write path. That wait is the right one for a price.
Cache the description, the image locations, and a price you can stand to show for at most the TTL when a delete is lost. Do not cache the inventory count the transaction decrements. The launch can make that count hot on writes. A fast description does not reduce those writes. Say so, or the design sounds like the cache solved the sale.
A restart is a larger herd. A dead cache server misses every key it owned, not one product. Single-flight still collapses each key to one fill, and the database still sees one fill per key at the same moment. Tens of thousands of live keys become tens of thousands of fills. The spare that absorbs a dead server is the advanced note.
flowchart TD
readers[Concurrent readers]
miss[Miss on one expired key]
flight[One filler runs]
waiters[Other readers wait]
db[One database read]
readers --> miss
miss --> flight
miss --> waiters
flight --> db
db --> waiters
The diagram is single-flight. Delete the middle split and every reader has their own arrow into the database. That picture is the expiry incident.
Tradeoffs
| Choice | What you gain | What you spend |
|---|---|---|
| Cache-aside, delete the key on write | Reads hit, and a crashed cache refills from the database | A miss storm on expiry or restart, and the first read pays the database |
| Write-through, database first | The next read can see a write that actually committed | The writer waits for both systems, and a failed cache write must delete the key |
| Write-back | A fast acknowledgement from the cache | Any write not flushed yet dies with the process |
| TTL only, no invalidation | Staleness has a bound you can say out loud | You are wrong until the timer, and expiry is a scheduled herd |
| Invalidation plus a TTL | Correct on the write, bounded when a delete is lost | You have to send the delete, and you still need a plan for the miss |
| Single-flight or a lease | One fill per key, and a late fill cannot restore an old value | Waiters share the filler’s latency, and a dead holder needs a timeout |
| A local copy of one hot key | Hits at memory speed on each process | You invalidate every process, or each copy is stale for its own TTL |
Pitfalls
- Treating the TTL as the consistency mechanism. The symptom is a price that changes in the database and stays wrong on the page until the timer, because nothing deleted the key.
- Letting every miss call the database. The symptom is a cache that looks healthy and a database spike on a period, once per TTL, under a launch.
- A lock or a lease with no timeout. The symptom is every request for that key waiting on a filler that has already died.
- A slow filler writing the value it read before a newer commit. The symptom is the page moving back to the old price. The token exists so that set is rejected.
- Putting the inventory counter in a write-back cache. The symptom is a decrement you acknowledged and then lost, followed by a second sale.
- A cache key that is only the URL when the body depends on the viewer. The symptom is one account rendered for a different account.
- Caching “not found” with no expiry and no delete. The symptom is a new product that exists in the database and stays missing at the cache.
- Adding shards to cool one hot key. The symptom is a larger cluster and the same owner on fire. The key did not split.
In the interview
In the first five minutes, say cache-aside, delete the key when the row changes, and keep a TTL only as a bound on a lost delete. Name the latency you removed: a database read on the hit path, replaced by a cache hit that is a round trip or a memory reference. Name the bottleneck: one hot key, or a stampede when that key expires. The honest tradeoff is staleness bounded by the TTL, against reading the database on every request.
Skip write-back unless the data can disappear. Skip a lecture on eviction. A full cache needs a policy, and least-recently-used is enough to say until someone asks what you measured. The question that usually follows is what happens when the key expires, or when the cache process restarts. Answer with single-flight or a lease, and with the arithmetic. Arrival rate times fill time is how many database reads you just stopped from stacking. If they ask what you will not cache, say the counter the transaction protects, and any response that depends on the user when the user is not in the key.
Check yourself
You delete the cache key on every write and you also set a 60-second TTL. Which one is the correctness plan, and what is the other for?
The delete is the correctness plan. The next read misses and loads the value you committed. The TTL is the bound for the case where that delete never arrives. Until it fires, readers can see the old value. A TTL alone, with no delete, means every write is invisible for up to 60 seconds on purpose.
A key takes 400 requests per second and the fill takes 50 ms. About how many database reads happen if every request misses and nothing coalesces?
Little’s law: 400 times 0.05 seconds is 20. About 20 requests are in flight during one fill, and without single-flight each of them reads the database for the same row. One filler cuts that to one read. The other 19 still wait about 50 ms. You capped load, and you did not make the fill cheaper than 50 ms.
A filler read the database, stalled, and sets the cache after a newer write has already updated the key. What does a lease change about that set?
The miss handed the filler a token. A newer fill or a newer write carries a later token. The late set presents the old token and the cache rejects it, so the key does not move backward to the stalled filler’s value. Without the lease, the late set wins and the page shows the price from before the write.
Name a value you would refuse to put in this cache, and the symptom if you cached it anyway.
The seats-left counter for a sale, kept in a write-back cache or served as the thing you decrement. Buyers would each see a copy that still says available, or you would acknowledge a decrement that never reached the database. The symptom is two confirmations for one seat. Cache the product description. Let the transaction on the database row decide the sale.
Based on: Facebook memcache, NSDI 2013, Nishtala and others; Designing Data-Intensive Applications, Kleppmann and Riccomini; Jeff Dean, Numbers Everyone Should Know.