When the cache fails: fail-open, fail-closed and the cascade
A cache is optional for correctness, not for capacity
Section titled “A cache is optional for correctness, not for capacity”Everything in this module has one idea underneath: the database only sees the misses. With a hit ratio of 95%, the database serves 5% of the reads. If the cache disappears, it is asked for 100% of them, which is twenty times more. At 90% it is ten times more. At 99% it is a hundred times more.
The cache made the system fast, but it also let you buy a smaller database. The day it fails, the database must carry the load it was never sized for.
This is the same arithmetic as in the first lesson, and it is the reason a cache failure is a different kind of failure from most. Nothing is wrong with the database. Nothing is wrong with the application. A component that was only supposed to make things faster has made the whole system depend on it.
What the dashboard shows
Section titled “What the dashboard shows”Below is a service at 12,000 requests per second with three API servers, a cache and a database. It shows the key figures an operator watches and the chain that links them. Drag Cache hit rate down to imitate a cache that is losing its entries.
Requests pass a load balancer to three API instances. The API reads through a cache and falls back to a database whose connection pool is sized for far less traffic than the API can take. Change the traffic, the number of instances, the cache hit rate, and the database connections, and watch the cause and effect play out.
Each dot stands for many requests. The numbers show the real rate.
No bottleneck: every component has headroom.
Key figures
- Traffic
- 12,000 req/s
- CPU
- 25%HealthyAPI utilisation
- Memory
- 20%Healthy404 MB of 2,048 MB per API instance
- Latency
- p50 4.5 msp95 19 msp99 28 msHealthyWhole request, all requests
- Error rate
- 0%HealthyRequests that fail
- Database load
- 46%HealthyDatabase utilisation
- Cache load
- 14%HealthyCache utilisation
Cause and effect
Each step leads to the next. A step that is changing right now is marked.
- Traffic12K req/sNormal steady
- Database utilisation46%Normal steady
- Database queuenone waitingNormal steady
- Latency (p99)28 msNormal steady
- Timeouts and rejections0%Normal steady
- Errors0%Normal steady
| Component | State | Utilisation | Offered (req/s) | Served (req/s) | Rejected (req/s) | p50 | p95 | p99 |
|---|---|---|---|---|---|---|---|---|
| Clients | Healthy | <1% | 12K | 12K | 0 | 0 ms | 0 ms | 0 ms |
| Load balancer | Healthy | <1% | 12K | 12K | 0 | 0.03 ms | 0.15 ms | 0.23 ms |
| API | Healthy | 25% | 12K | 12K | 0 | 2.8 ms | 12 ms | 18 ms |
| Cache | Healthy | 14% | 11K | 11K | 0 | 0.14 ms | 0.6 ms | 0.92 ms |
| Database | Healthy | 46% | 2.3K | 2.3K | 0 | 5.5 ms | 24 ms | 37 ms |
- Traffic
- 12,000 req/s
- Successful
- 12,000 req/s
- Error rate
- 0%
- Mean latency
- 6.3 ms
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- Requests arrive at random, as a Poisson process, at a constant average rate.
- Each node is one queue, served first-come first-served by several identical slots (instances × concurrency).
- Service times are random with the stated mean; by default they are exponentially distributed.
- Each node is analysed separately, with the traffic it receives treated as Poisson.
- Nine in ten requests are reads. The cache answers the share set by the hit rate; the rest, and every write, go to the database.
Simplifications
- Above capacity there is no steady state. The model switches to a fluid approximation: the node serves at capacity, its queue grows until it reaches its limit, and further requests are rejected.
- Percentiles assume an exponential tail. A service-time variability other than exponential changes the mean wait but not the shape of the tail.
- A node frees its slot as soon as it has done its own work, before waiting on the services it calls. Real thread-per-request servers hold the slot, so a slow dependency exhausts them faster than this model shows.
- A request calls its dependencies one after another. Parallel fan-out is not modelled.
- When a caller times out and gives up, the callee still finishes the work, so abandoned requests keep consuming capacity.
- Retries add load. Their backoff and jitter decide when that load arrives, which only the per-request simulation shows.
- Retry feedback is solved from the healthy starting point, so it finds one stable outcome. Systems that stay stuck in overload after the cause is gone are not shown.
- A throughput limit (for example maximum writes per second) is modelled as slower service, not as a separate rate limiter.
- A caller’s timeout counts the mean time its dependencies take, not their full distribution.
- Latency percentiles for a whole request are estimated, over every request, including those that are rejected and fail quickly. The mean is exact, and the percentiles come from a gamma distribution that has that mean and the variance of the time spent in each component.
- Memory is modelled simply: a fixed base for each instance, plus a fixed amount for every request the instance holds, whether it is being served or waiting.
- Each database connection serves one operation at a time, about 8 ms each, so 40 connections can serve about 5,000 operations per second. Reads and writes cost the same here; real databases treat them differently, and writes are usually the scarcer resource.
Parameter values are illustrative. They are not benchmarks of any real product.
With the starting hit rate of 90%, the database is at 46% utilisation and everything is healthy. Now move the hit rate down:
| Cache hit rate | Database utilisation | State |
|---|---|---|
| 90% | 46% | Healthy |
| 80% | 67% | Busy |
| 70% | 89% | Saturated |
| 50% | 132% | Overloaded, about 13% of requests fail |
| 0% | 240% | Overloaded, about 55% of requests fail |
Notice that at 70% nothing has failed yet and the p99 latency has barely moved, 35 milliseconds against 28, while the database is already saturated. By the time the errors appear, the cascade is already running: the Cause and effect chain lights up from the database utilisation down to the errors. A rise in database utilisation is the earliest warning, and it comes before the error rate does.
When the hit rate slides instead of falling
Section titled “When the hit rate slides instead of falling”The table above is a set of still pictures. A real hit rate rarely jumps from one row to the next. It slides, a little each hour, and the system looks fine at every moment you check. The lab below opens on a healthy cache and then lets the share of requests that write climb on its own, from 2% to 30% over two and a half minutes. Every write deletes the cached copy, so more writes leave fewer entries to hit. Nobody touches a control, and nothing breaks.
The lab opens on a healthy cache. From this moment the share of requests that write climbs on its own, from 2% to 30% over two and a half minutes, and every write deletes the cached copy. Nothing breaks. Watch the hit ratio slide, the database take the misses, and the errors stay at zero until the database runs out of room.
- Cache hit
- Cache miss, goes on to the database
- Waits for another request’s read
- Request fails
Each dot stands for many requests. The numbers show the real rate.
Hit ratio 87%: 15% of requests reach the database (59.2 reads/s, capacity 200/s).
History
Hit ratio
88%Use the left and right arrow keys to read values at each moment.
Database reads per second
44/sUse the left and right arrow keys to read values at each moment.
Requests that fail
0%Use the left and right arrow keys to read values at each moment.
Data table
| Simulated time | Hit ratio | Database reads per second | Requests that fail |
|---|---|---|---|
| 5 s | 99% | 2/s | 0% |
| 10 s | 98% | 8/s | 0% |
| 15 s | 96% | 14/s | 0% |
| 20 s | 97% | 12/s | 0% |
| 25 s | 91% | 38/s | 0% |
| 30 s | 83% | 70/s | 0% |
| 35 s | 83% | 66/s | 0% |
| 40 s | 82% | 78/s | 0% |
| 45 s | 88% | 44/s | 0% |
| Component | State | Utilisation | Queue |
|---|---|---|---|
| Cache, Shard 1 | Healthy | <1% | 0 |
| Cache, Shard 2 | Healthy | 1% | 0 |
| Cache, Shard 3 | Healthy | 1% | 0 |
| Cache, Shard 4 | Healthy | 1% | 0 |
| Database | Healthy | 30% | 0 |
- Traffic
- 401/s
- Successful
- 401.2/s
- Error rate
- 0%
- Hit ratio
- 87%
- Database reads
- 59.2/s
- p50
- 0.17 ms
- p95
- 11 ms
- p99
- 32 ms
- Entries cached
- 986 / 1,500
- Requests that write
- 2%
- Stale hits
- 0%
- Coalesced requests
- 0/s
- Skipped the cache
- 0/s
Figures describe the last 5 simulated seconds.
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- Each request asks for a key drawn independently from a fixed popularity distribution. Real traffic has bursts and trends that this does not capture.
- Every operation on a cache shard (lookups, stores, deletions) joins one queue served by a few slots, so a busy shard slows everything on it.
- The share of requests that write rises in a straight line, from 2% to 30%, starting when the lab opens. The lab runs it for you: it is not a control.
Simplifications
- Real traffic drifts for many reasons at once: more writes, a longer tail of keys, shorter TTLs, a cache that is too small. The lab moves one so the effect of that one is visible.
- The latency in the table is that of the requests that succeeded. Once most requests fail, it describes only the few that got through.
- An entry’s lifetime starts when it is stored. Reading it does not extend it.
- Only a version number is tracked for each key, not the data. A cached copy is stale when its version is behind the database’s.
- The cache never runs out of memory, so no entry is evicted early. Real caches evict the least recently used entries when they are full.
- A write updates the database and then deletes the cached copy (cache-aside). Write-through and write-behind are compared in the trade-off explorer, not simulated here.
- Refresh before expiry reloads an entry in the background when a request reads it in the last part of its life. Production systems often use a probabilistic variant.
- A cache that goes down loses everything it held and comes back empty. A cache with persistence would not.
- The application learns that the cache is down at once, on the request that fails. Health checks and circuit breakers are not modelled.
- When a caller times out and gives up, the callee still finishes the work, so abandoned requests keep consuming capacity.
Parameter values are illustrative. They are not benchmarks of any real product.
Let it run to the end, or raise the speed. These are the figures the lab shows, and a run of yours will be close to them.
| Time | Requests that write | Hit ratio | Database | Requests that fail | p99 latency |
|---|---|---|---|---|---|
| 45 s | 2% | about 87% | 30% | 0% | 32 ms |
| 105 s | 13% | 81% | 57% | 0% | 39 ms |
| 150 s | 22% | 69% | 95% | 0% | 183 ms |
| 170 s | 25% | 57% | 117% | 57% | not meaningful |
| 195 s | 30% | 51% | 125% | 63% | not meaningful |
From 45 s to 150 s the hit ratio falls from about 87% to 69%, the database goes from 30% to 95% busy, and not one request fails. The p99 latency, 32 ms to 183 ms, is a second warning, and a late one. The first failed requests arrive at about 160 s, when the database is already past its capacity, and ten seconds later more than half fail. An alert on the error rate stays silent through most of the slide. An alert on the hit ratio or on the database’s utilisation can fire while every request still succeeds. The p99 of the last two rows comes only from the few requests that succeeded, so it says nothing about the others.
Try two changes. For each, change one control, press Restart so that the lab starts from the new setting, let it run to the end, and put the control back before you try the other.
- Raise Database reads in parallel to 4. The hit ratio slides just the same, to 66% at the end, but the database stops at 52% and nothing fails. More capacity removes the cliff in this lab. It does not stop the slide.
- Switch off Delete the cached copy on write. The hit ratio now stays near 90% to the end, and the database is at 73%, still rising because the writes themselves go to it. But by 195 s about 82% of the hits are stale. The slide was caused by the invalidation, and removing it bought the hit ratio at the price of correctness, the trade-off of TTL and invalidation.
Two policies, one choice
Section titled “Two policies, one choice”When the application cannot reach the cache, it has to do something. The two common answers have two names.
- Fail-open. The application goes around the cache and reads the database. Users keep being served, if the database can take the load. Each request first waits for the connect timeout to find out that the cache is not answering.
- Fail-closed. The application returns an error at once. The database is never asked to do the cache’s job, and every read that needed the cache fails.
Neither is the right answer in general. Fail-open protects availability and risks the database. Fail-closed protects the database and gives up availability. The choice depends on what the database can take, and on how much it matters that the user gets an answer.
Break it, then repair it
Section titled “Break it, then repair it”The lab below is a service in steady state: Redis answers almost every read, and the database was sized for the few that remain. You choose the policy, kill Redis, read the cascade, decide what to change, and run the same failure again to compare.
Before you press Kill Redis, write down what you expect to happen to the database, and to the share of requests that fail. Predicting first is what makes the result worth reading.
Kill Redis
Redis answers almost every read of this application, and the database was sized for the few that remain. You choose how the application behaves when Redis cannot be reached. Then you kill Redis and watch where the work goes. Finally you decide what to change, and run the same failure again to compare.
The failure lab needs JavaScript. The healthy system is shown below.
1. Choose how the application reacts
2. Kill Redis
The healthy system runs for a moment, then Redis dies. The run measures the 30 seconds that follow.
- Cache hit
- Cache miss, goes on to the database
- Waits for another request’s read
- Request fails
Each dot stands for many requests. The numbers show the real rate.
Hit ratio 96%: 7.9% of requests reach the database (31.8 reads/s, capacity 200/s).
Sources
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- Each request asks for a key drawn independently from a fixed popularity distribution. Real traffic has bursts and trends that this does not capture.
- Every operation on a cache shard (lookups, stores, deletions) joins one queue served by a few slots, so a busy shard slows everything on it.
- The cache restarts empty: everything it held is lost.
Simplifications
- A request waits for the full connect timeout each time the cache is unreachable. Real clients may stop trying for a while after repeated failures, which is what a circuit breaker does.
- An entry’s lifetime starts when it is stored. Reading it does not extend it.
- Only a version number is tracked for each key, not the data. A cached copy is stale when its version is behind the database’s.
- The cache never runs out of memory, so no entry is evicted early. Real caches evict the least recently used entries when they are full.
- A write updates the database and then deletes the cached copy (cache-aside). Write-through and write-behind are compared in the trade-off explorer, not simulated here.
- Refresh before expiry reloads an entry in the background when a request reads it in the last part of its life. Production systems often use a probabilistic variant.
- A cache that goes down loses everything it held and comes back empty. A cache with persistence would not.
- The application learns that the cache is down at once, on the request that fails. Health checks and circuit breakers are not modelled.
- When a caller times out and gives up, the callee still finishes the work, so abandoned requests keep consuming capacity.
Parameter values are illustrative. They are not benchmarks of any real product.
Do it in this order:
- Fail-open first. Kill Redis and read the cascade. Redis stops answering, each request waits for the connect timeout and then reads the database, the database takes about 380 reads a second instead of about 20, the waiting room fills, latency rises to the timeout, and almost every request fails.
- Pick one fix and run it again. Add database read capacity and almost nothing fails. Try shortening the waiting room instead: about half the requests fail, but quickly. Try the shorter connect timeout alone, and see that almost nothing changes.
- Start over, choose fail-closed. The database is protected, and nearly every read fails. Now choose the fix that falls back to the database. Falling back alone brings the overload back. Falling back and adding capacity together gives you the first fix again.
Here is what the lab measures over the 30 seconds after Redis dies. Your numbers will be close.
| What you changed | Requests that fail | p99 latency |
|---|---|---|
| Nothing (fail-open) | 99% | about 490 ms |
| Fail closed | 95% | about 46 ms |
| A shorter connect timeout | 98% | about 490 ms |
| A shorter waiting room (load shedding) | 50% | about 260 ms |
| More database read capacity | 0% | about 150 ms |
| More capacity and a shorter connect timeout | 0% | about 60 ms |
Look at what each change did. Fail-closed trades an overloaded database for failing nearly every read. Load shedding keeps latency down by deciding which half of the traffic fails. A shorter connect timeout does almost nothing while the database is the bottleneck, and helps once it is not. Only more capacity removes the cause. The others change who suffers.
That is the lesson of the failure lab: there is no setting that makes a cache failure free. Each fix has a price, and the lab shows it next to the fix.
What real systems do
Section titled “What real systems do”The labs cover four fixes. Real systems add others, and some of them are worth knowing because they are the ones that were invented after outages like this one.
- A standby for the cache. Facebook’s memcache paper describes Gutter, a small set of machines, about 1% of the cluster, that take over for a few failed cache servers. A client that gets no answer asks Gutter instead, and Gutter’s entries expire quickly. Failed requests turn into hits there, so the database is shielded at the cost of slightly stale data. They report that it reduced client-visible failures by 99% in practice.
- Don’t spread a failed server’s keys over the others. The paper points out that this can cascade: a server that inherits a hot key can be overloaded in turn. Shunting the load to idle spare servers limits that risk.
- Degrade gracefully and shed load. Google’s SRE book describes load shedding, which drops traffic to avoid overload, and graceful degradation, which reduces the work done for each request. Both help a server avoid being overwhelmed. It also advises keeping queues short, so that requests that cannot be served are rejected early rather than made to wait.
- Serve stale data. A copy that is a little old is often better than none. Facebook’s memcache keeps recently deleted items for a short time and can hand them out marked as stale, to applications that can carry on with an old value.
- A circuit breaker. After repeated failures, the client stops trying the cache for a while instead of waiting for the connect timeout on every request. The lab does not model this, and the connect timeout is its closest stand-in.
Microsoft’s description of cache-aside makes the same point from the other side: the workload can fall back to the data store when the cache malfunctions. The question is whether the data store can carry it.
What happens if Redis comes back?
Section titled “What happens if Redis comes back?”Restoring the cache is not the end of the story. A cache that has been replaced or restarted usually comes back empty. Everything it held is gone, so the hit ratio starts at zero and the database faces the full load again until the cache refills.
In the lab below, press Kill the cache, wait a few seconds, then press Restart the cache, and watch Requests that fail and the database queue.
Kill the cache and see what the application does. Fail-open sends every read to the database, which was sized for the misses of a working cache. Fail-closed returns errors and protects the database. Change the policy or the database, restart the cache, and try again.
- Cache hit
- Cache miss, goes on to the database
- Waits for another request’s read
- Request fails
Each dot stands for many requests. The numbers show the real rate.
Hit ratio 100%: 0% of requests reach the database (0 reads/s, capacity 200/s).
History
Requests that fail
0%Use the left and right arrow keys to read values at each moment.
Database queue (most waiting)
0Use the left and right arrow keys to read values at each moment.
p99 latency
0.84 msUse the left and right arrow keys to read values at each moment.
Data table
| Simulated time | Requests that fail | Database queue (most waiting) | p99 latency |
|---|---|---|---|
| 5 s | 0% | 0 | 0.89 ms |
| 10 s | 0% | 0 | 1 ms |
| 15 s | 0% | 0 | 0.91 ms |
| 20 s | 0% | 0 | 0.84 ms |
| Component | State | Utilisation | Queue |
|---|---|---|---|
| Cache, Shard 1 | Healthy | <1% | 0 |
| Cache, Shard 2 | Healthy | 1% | 0 |
| Cache, Shard 3 | Healthy | 1% | 0 |
| Cache, Shard 4 | Healthy | <1% | 0 |
| Database | Idle | 0% | 0 |
- Traffic
- 404.2/s
- Successful
- 404/s
- Error rate
- 0%
- Hit ratio
- 100%
- Database reads
- 0/s
- p50
- 0.14 ms
- p95
- 0.61 ms
- p99
- 1 ms
- Entries cached
- 300 / 300
- Requests that write
- 0%
- Stale hits
- 0%
- Coalesced requests
- 0/s
- Skipped the cache
- 0/s
Figures describe the last 5 simulated seconds.
Illustrative values, not benchmarks of any real product.
Model notes
Assumptions
- Each request asks for a key drawn independently from a fixed popularity distribution. Real traffic has bursts and trends that this does not capture.
- Every operation on a cache shard (lookups, stores, deletions) joins one queue served by a few slots, so a busy shard slows everything on it.
- The cache restarts empty: everything it held is lost.
Simplifications
- A request waits for the full connect timeout each time the cache is unreachable. Real clients may stop trying for a while after repeated failures, which is what a circuit breaker does.
- An entry’s lifetime starts when it is stored. Reading it does not extend it.
- Only a version number is tracked for each key, not the data. A cached copy is stale when its version is behind the database’s.
- The cache never runs out of memory, so no entry is evicted early. Real caches evict the least recently used entries when they are full.
- A write updates the database and then deletes the cached copy (cache-aside). Write-through and write-behind are compared in the trade-off explorer, not simulated here.
- Refresh before expiry reloads an entry in the background when a request reads it in the last part of its life. Production systems often use a probabilistic variant.
- A cache that goes down loses everything it held and comes back empty. A cache with persistence would not.
- The application learns that the cache is down at once, on the request that fails. Health checks and circuit breakers are not modelled.
- When a caller times out and gives up, the callee still finishes the work, so abandoned requests keep consuming capacity.
Parameter values are illustrative. They are not benchmarks of any real product.
With fail-open, in a run where the cache is down for 15 seconds, the first five seconds after it comes back have a hit ratio of about 56% and about 46% of requests failing. By the next ten seconds it has refilled, with a hit ratio of about 93% and no failures. The lab has only 300 keys, so it refills in seconds. A real cache with millions of keys takes much longer, and so does the danger.
Trade-offs
Section titled “Trade-offs”| Decision | What it protects | What it costs | How it fails |
|---|---|---|---|
| Fail-open | Availability: users are still served | Puts the full read load on the database | A database that was sized for the misses overloads, and its slowness fails the requests anyway |
| Fail-closed | The database | Every read that needed the cache fails | The outage is as long as the cache’s |
| More database capacity | Availability and latency | Money, and capacity that sits idle in normal times | Replicas take time to add and can lag behind the primary |
| Load shedding | The latency of accepted requests, and the database | The rejected requests fail at once | Shedding the wrong requests: you choose who to give up on |
| Shorter connect timeout | Latency | A slow but healthy cache is treated as dead | Does nothing for an overloaded database |
| A standby for the cache | The database, and availability | More machines, and slightly stale data | A standby that is too small, or that fails with the cache |
Defend your decision
Section titled “Defend your decision”An interviewer asks what happens when your cache goes down. A good answer names the arithmetic (the database sees the misses, so a cache failure multiplies its load by 1 / (1 − h)), names the choice (fail-open or fail-closed, and why), and names the price of each fix. Write your answer before you look at the strong one.
Interview question
Writing and reviewing an answer needs JavaScript.
The interviewer asks
Your service reads user profiles through Redis, which sits in front of a PostgreSQL database. Redis goes down. What happens, and what would you have designed in advance?
Assume 5,000 reads per second. The cache normally answers about 95% of them, and the database was sized for the other 5%.
Write your answer first. The strong answer unlocks once you have written a real attempt.
0 of 60 characters written to unlock the strong answer
- A cache lets you size the database for the misses. If the cache goes away, the database sees all the reads:
1 / (1 − h)times more. - The cascade runs in order: the cache stops answering, the application reacts, the database takes the reads, the queue fills, latency rises, requests time out and fail.
- Fail-open protects availability and risks the database. Fail-closed protects the database and gives up availability.
- Only more capacity removes the cause. Shedding load, failing fast and failing closed change who suffers, and each has a price.
- A cache that comes back is empty, so the database faces the full load again until it refills.
- A cache can also fail slowly. A falling hit ratio loads the database long before any request fails, so watch the hit ratio and the database’s utilisation, not only the error rate.
- Check a fix by running the same failure again and comparing, not by arguing that it should work.
That is the end of the module’s lessons. The next page gathers them: a recap of the whole module, and a quiz that covers all five.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.