To design a distributed cache is to decide which data to keep in fast memory across several machines, which entry to throw out when memory is full, how to keep cached copies from going stale, and what happens to the database when the cache is cold, overloaded or has lost a machine. A good answer treats the cache as a protection for the database and shows with numbers when that protection fails.

This lesson designs the cache behind ResultsHub, a portal where millions of candidates look up exam results by roll number on results day. Six runnable programs in Java, with Python and C++ versions, test the decisions interviewers probe most: which entry to evict, how to invalidate on a correction, absent keys and synchronized expiry, a viral key, losing a node, and when to write to the database. All capacities and timings are assumptions chosen to make comparisons clear, not benchmarks of a product.

Key takeaways

  • No eviction policy won everywhere. LFU had the best hit rate (35.3%) and resisted a batch scan (21.3%), but after a new exam made different numbers popular it fell to 1.0%, while LRU stayed at 24.5%.

  • Writing the database first and then deleting the cache entry left the old score in the cache in 0.44% of cases. Deleting first left it in 9.24%. A second delete 500 ms later brought it to 0.00%.

  • Remembering "not found" did nothing against random typos (24.53 database calls per 100 lookups, against 24.68 with no protection) but cut a bot that repeated 100 numbers to 4.89. A Bloom filter of the real numbers handled both for 6,250 bytes.

  • 5,000 entries cached together with one lifetime produced 837 database calls in a single second. Adding up to 60 seconds of random lifetime brought the busiest second to 96.

  • When half of all lookups asked for one roll number, its owner node was over its limit for all 100 seconds (1,180 calls in the worst second). Keeping the value in each server's memory for 1 second brought the busiest node to 201.

  • When 1 of 6 cache nodes failed, hash-modulo placement moved 83.0% of the keys and the hit rate fell to 25.2%. Rendezvous hashing moved 16.5% and fell to 81.4%. With a second copy there was no dip.

  • Write-behind cut database writes from 50,296 to 5,269 with a 30 second flush, and a crash then sent 1,748 of 2,000 answer sheets back to an older mark.

1. Clarifying Requirements

Functional requirements

  • get(key), put(key, value, ttl) and delete(key) for results keyed by roll number.

  • Values expire after a time to live (TTL), and the cache evicts entries when it is full.

  • The cluster survives the loss of a node and can grow without a long period of misses.

  • A corrected result must reach readers quickly.

Non-functional requirements

  • 40,000 lookups per second at the peak, with a 1 to 2 ms response from the cache.

  • The database must never see more than about 2,000 reads per second, so the cache must absorb at least 95% of lookups.

  • A wrong score must not stay visible for long, because candidates make decisions from it.

Say what you leave out: the cache is not the source of truth, so losing it must never lose data that matters (section 10 shows when that can go wrong), and it is not a search engine.

2. Back-of-the-Envelope Estimation

  • Traffic: 40,000 lookups per second. If the database can answer 2,000 reads per second, at most 5% of lookups can miss. A hit rate of 90% would send 4,000 reads per second to the database, double what it can take.

  • Memory: 3 million results at about 500 bytes is 1.5 GB, or 3 GB with two copies. A node with 16 GB of memory holds all of it, so memory does not decide the node count.

  • Nodes: we assume a cache node answers 25,000 lookups per second. 6 nodes share 40,000 lookups at 6,667 each (27%), rising to 8,000 each (32%) after one node fails. More nodes are for availability and hot keys, not for capacity.

3. Core APIs

  • GET /v1/cache/{key} returns the value or 404 for a miss.

  • PUT /v1/cache/{key}?ttl=300 stores a value. The service adds a random extra of up to 20% to the TTL (section 7).

  • DELETE /v1/cache/{key} removes an entry.

  • POST /v1/cluster/nodes and POST /v1/cluster/nodes/{id}:drain change membership; GET /v1/cluster/status lists each node's hit rate, memory and load.

Most applications use the cache cache-aside: read the cache, on a miss read the database and put the answer in the cache. The service above is only the cache; the application owns that logic.

4. High-Level Design

Application servers hold a list of the cache nodes and decide which node owns a key by hashing. The nodes do not need to talk to each other for a normal lookup, so there is no coordinator to overload.

Placement. Spreading keys with hash modulo number of nodes is simple but reshuffles almost every key when a node leaves (section 9). A hash ring, as in Consistent Hashing, or rendezvous hashing (each key goes to the node with the highest hash of the key and the node name) moves only the keys of the node that left. The programs below use rendezvous hashing because it needs no ring and behaves the same way.

5. Eviction: What to Throw Out

When the cache is full, an entry must go. FIFO evicts the oldest entry. LRU evicts the one used least recently. LFU evicts the one used least often. Clock approximates LRU cheaply: entries sit on a circle with a "used" bit, and a hand clears bits until it finds an entry that was not used since its last pass.

The first program has 4,000 roll numbers, room for 200 entries and 60,000 lookups, with a few roll numbers much more popular. From lookup 20,000 to 30,000 a batch export reads every roll number in order (half of all lookups). At lookup 40,000 a new exam's results are released and a different set becomes popular.

Output

ResultsHub cache: 4000 roll numbers, room for 200 entries, 60000 lookups.
Lookups 20000-30000: a batch export reads every roll number in order (half of all lookups). At 40000 a new exam's results are released.

policy  normal            batch export      after export      after new exam    whole run
        (0-20000)         (20000-30000)     (30000-40000)     (40000-60000)
FIFO    22.5%             9.2%              22.2%             22.7%             20.3%
LRU     24.4%             9.8%              24.5%             24.5%             22.0%
LFU     35.3%             21.3%             36.4%             1.0%              21.7%
Clock   25.6%             10.3%             25.6%             25.7%             23.1%
  • In normal traffic LFU led with 35.3%, then Clock 25.6%, LRU 24.4% and FIFO 22.5%.

  • During the batch export every policy but LFU lost more than half its hits: FIFO 9.2%, LRU 9.8%, Clock 10.3% and LFU 21.3%. The export reads each entry once, and these policies let those one-time entries push out the useful ones. LFU does not, because an entry read once has the lowest count.

  • After the new exam LFU fell to 1.0%, because entries that were popular earlier kept their high counts and stayed. FIFO, LRU and Clock recovered within the phase to 22.7%, 24.5% and 25.7%.

  • Over the whole run Clock had the best total (23.1%), with LFU at 21.7%.

Choose by how popularity behaves. Where it is stable, frequency helps. Where it shifts, recency is safer, or use LFU with counts that decay. Where one-time scans are common, keep them out of the cache (read them without filling it), which helps every policy.

6. Keeping Entries from Going Stale

When a score is corrected, the cached copy must stop being served. The usual rule is: update the database, then delete the cache entry (not update it), and let the next read refill it. Two orders are possible, and the order matters because a reader may be in the middle of a miss.

The second program corrects one score while a reader looks it up. The cache holds the old score in 70% of trials and is empty (expired) in 30%. The reader starts within the 20 ms around the write. On a miss it reads the database and fills the cache a few milliseconds later. We count how often the cache ends up holding the old score.

Output

A score is corrected while a reader looks it up. 200000 trials; the cache holds the old score in 70% of them.

Part 1: one writer, one reader
order of the two steps                                      cache left with the old score
A  delete the cache entry, then write the database          9.24%
B  write the database, then delete the cache entry          0.44%
C  as B, and delete the entry again 500 ms later            0.00%

Part 2: two writers correct the same score at almost the same time
what each writer does to the cache after its database write  cache differs from the database
set the cache to its own value                              10.33%
delete the cache entry                                      0.00%

Part 3: a stale entry stays until its TTL ends. A hot score is read 10 times per second.
wrong answers served per 100000 corrections       TTL 5 s       TTL 60 s      TTL 3600 s
A  delete, then write                           462300        5547600       332856000
B  write, then delete                           22450         269400        16164000
  • A, delete the entry and then write the database: 9.24% of trials ended with the old score. A reader that missed in between read the old value from the database and put it back after the delete.

  • B, write the database and then delete the entry: 0.44%. The same race exists but needs the entry to be empty at the wrong moment.

  • C, as B with a second delete 500 ms later: 0.00%, because in this model any refill with the old value finishes within about 30 ms and the second delete clears it. This depends on that being true; a very slow reader could still refill after the second delete.

  • With two writers at once, each setting the cache after its database write, the cache differed from the database in 10.33% of trials, because the two updates can arrive in a different order at the database and the cache. Deleting instead of setting avoided it.

A TTL is the safety net: a stale entry lives at most one TTL. The table in the output shows what that costs. For a hot score read 10 times per second, order A produced 5,547,600 wrong answers per 100,000 corrections with a 60 second TTL, against 269,400 for order B. A short TTL limits the damage but raises the miss rate, so use it as a backstop and not as the main method.

7. Absent Keys and Synchronized Expiry

Two failure patterns send a burst of misses to the database. Cache penetration is a flood of lookups for keys that do not exist, which can never be cached as hits. Cache avalanche is many entries expiring at the same moment.

Part 1 of the third program has 5,000 real roll numbers and 100,000 lookups, 20% of them for numbers that do not exist. In one workload the absent numbers are typos spread over a million values. In the other a bot keeps asking for the same 100 numbers. We compare no protection, remembering "not found" for 30 seconds, and a Bloom filter of the real numbers (10 bits per number, as in Design Key-Value Store) checked before the database. Part 2 caches all 5,000 entries together after a restart, runs 1,000 lookups per second for 650 seconds against a database that can take 200 calls a second, and compares one fixed lifetime with a random extra.

Output

Part 1: 100000 lookups at 2000 a second. 20% ask for a roll number that does not exist. Database calls per 100 lookups:
                                   typos over a million values    a bot repeating 100 numbers
protection                         calls/100      memory          calls/100      memory
no protection                      24.68          -               24.68          -
remember "not found" for 30 s      24.53          19812 entries   4.89           100 entries
Bloom filter of real roll numbers  4.84           6250 bytes      5.08           6250 bytes

Part 2: 5000 entries cached together at second 0, 1000 lookups a second for 650 s. The database can take 200 calls a second.
entry lifetime                           busiest second  seconds over 200  database calls in total
all entries expire together (300 s)      837            12                9086
300 s plus up to 60 s random             96             0                 5798
300 s plus up to 150 s random            47             0                 5036
  • With no protection 24.68 database calls per 100 lookups went through. Remembering "not found" gave 24.53 for typos (almost every typo is new, so there is nothing to remember, and it stored 19,812 entries) and 4.89 for the bot (100 entries).

  • The Bloom filter gave 4.84 and 5.08 in the two workloads and used 6,250 bytes. The remaining calls are the first load of each real number plus the filter's rare false alarms.

  • With one lifetime for all entries, the busiest second sent 837 calls to the database and 12 seconds went over its limit. With up to 60 seconds of random extra, the busiest second was 96 and none went over. With up to 150 seconds it was 47.

  • The random extra also makes entries live longer on average, which is part of why total database calls fell from 9,086 to 5,798 in this window.

Use a Bloom filter (or a check against the database's key list) when absent keys are common, remember "not found" briefly for repeats, and add random jitter to every TTL. Also protect the refill itself: when a hot entry expires, let one request refill it and make the others wait (the stampede protection shown in Design API Gateway).

8. One Key Gets Half the Traffic

Hashing spreads keys evenly, but it cannot spread the requests for a single key: all of them go to its owner. When the topper of an exam is announced, one roll number can receive a large share of the traffic.

The fourth program has 8 cache nodes, 50 application servers and 2,000 lookups per second for 100 seconds. Half of all lookups ask for one roll number. A node can answer 1,000 lookups per second (an assumption). It compares: one owner node; copies of the key on all 8 nodes with a random pick; and each application server keeping the value in its own memory for 100 ms or 1,000 ms.

Output

8 cache nodes, 50 application servers, 2000 lookups a second for 100 s. 50% of lookups ask for one roll number.
A cache node can answer 1000 lookups a second (an assumption).

setup                    busiest node   seconds over 1000   lookups reaching cache   cache writes per correction   extra staleness
                         (worst second)
one owner node           1180           100                 200000                   1                             0
copy to all 8 nodes      305            0                   200000                   8                             0
server memory, 100 ms    483            0                   133107                   1                             100 ms
server memory, 1000 ms   201            0                   104405                   1                             1000 ms
  • With one owner node the busiest second sent it 1,180 lookups, and the node was over its limit in all 100 seconds.

  • Copies on all 8 nodes brought the busiest node to 305. The cost is that each correction must be written 8 times.

  • Server memory for 100 ms gave 483 and reduced lookups reaching the cache from 200,000 to 133,107. For 1,000 ms it gave 201 and 104,405. The price is that a corrected score can be shown up to 100 ms or 1,000 ms late.

Detect hot keys (count lookups per key in a short window), then copy or near-cache just those keys. The correction delay of the near copy is a product decision: for a score that rarely changes, a second is fine.

9. Losing a Cache Node

When a node dies, its entries are gone and the keys it owned must go somewhere. Misses for those keys land on the database. How many keys move, and how much memory the cache holds in reserve, decide how large that spike is.

The fifth program has 6 nodes, 2,000 lookups per second for 80 seconds over 20,000 roll numbers. At second 40 node 3 fails and loses its contents. It compares hash modulo the number of alive nodes, rendezvous hashing, and rendezvous hashing with two copies of every entry (a lookup uses the first copy it finds). It measures the hit rate before the failure (seconds 30 to 39), the worst hit rate afterwards, the time to return to 95% of the earlier hit rate, and the database calls in the 10 seconds afterwards.

Output

6 cache nodes, 2000 lookups a second for 80 s over 20000 roll numbers. At second 40 node 3 fails and loses its contents.
Hit rate before the failure is measured over seconds 30-39; database calls are counted over the 10 s before and after the failure.

placement                  keys moved  hit rate     worst hit   back to 95%  database calls (10 s before)  busiest second
                           by failure  before       rate after  of before    in 10 s after                 database calls
hash modulo node count     83.0%       95.1%        25.2%       19 s         8444           965 before     1495
rendezvous hashing         16.5%       95.1%        81.4%       5 s          2201           965 before     371
rendezvous + 2 copies      16.5%       95.1%        95.4%       0 s          675            965 before     91
  • The hit rate before the failure was 95.1% for all three.

  • Hash modulo moved 83.0% of the keys. The hit rate fell to 25.2%, took 19 seconds to recover, and the database took 8,444 calls in 10 seconds (965 in the 10 seconds before), with 1,495 in the worst second.

  • Rendezvous hashing moved 16.5% (about the share of the dead node, 1 of 6). The hit rate fell to 81.4%, recovered in 5 seconds, and the database took 2,201 calls with 371 in the worst second.

  • With two copies the worst hit rate was 95.4% (no dip), and the database took 675 calls with 91 in the worst second. Two copies need twice the memory and writes.

In this run the database took 8.7 times its normal load (8,444 calls against 965) for 10 seconds. The program is scaled down, so compare the ratio, not the totals: if the database normally runs close to its limit, as in the estimate, a spike of that size would take it down. This is the main reason to avoid hash modulo in a cluster that changes size. A cache that is rebuilt after a restart (cold start) has the same problem, so warm it before sending it full traffic.

10. Writes: When Does the Database Hear?

Three ways to handle a write decide the balance between speed and safety. Cache-aside with delete writes the database and deletes the entry. Write-through writes the database and the cache before replying. Write-behind (write-back) writes only the cache, replies at once, and writes the database later in batches.

The sixth program has examiners correcting marks for 2,000 answer sheets while others read them: 2,000 operations per second for 100 seconds, 25% of them writes. A database write takes 12 ms, a database read 8 ms and a cache operation 1 ms. The cache starts empty and the cache node crashes at 57.3 seconds. Write-behind flushes every 1, 5 or 30 seconds.

Output

2000 answer sheets, 200000 operations (25% writes) over 100 s. The cache node crashes at 57.3 s.

policy                       write takes    database    database   reads from     writes lost in a  sheets back to
                                            writes      reads      the cache      crash             an older mark
cache-aside (delete)         13.0 ms        50296       38907      74.0%          0                 0
write-through                13.0 ms        50296       1509       98.9%          0                 0
write-behind, flush 1 s      1.0 ms         39772       1509       98.9%          150               143
write-behind, flush 5 s      1.0 ms         21118       1509       98.9%          1202              737
write-behind, flush 30 s     1.0 ms         5269        1509       98.9%          13759             1748
  • Cache-aside and write-through both took 13.0 ms per write and made 50,296 database writes. Cache-aside deleted the entry on each write, so reads served from the cache were 74.0% and the database saw 38,907 reads. Write-through kept the cache fresh: 98.9% and 1,509 reads.

  • Write-behind took 1.0 ms per write. It made 39,772 database writes with a 1 second flush, 21,118 with 5 seconds and 5,269 with 30 seconds, because repeated writes to the same sheet were combined.

  • The crash exposed the cost. Nothing was lost with cache-aside or write-through. With write-behind, 150 acknowledged writes were lost with a 1 second flush (143 sheets back to an older mark), 1,202 with 5 seconds (737 sheets) and 13,759 with 30 seconds (1,748 of 2,000 sheets).

Use write-behind only for data you can afford to lose for a few seconds (counters, view counts, session activity). For marks, payments and anything a person was told was saved, write to the database before replying.

11. Choosing the Design

SituationChoiceWatch for
Values change rarely, wrong answers are costlyCache-aside, delete after the database write, TTL as a backstopThe delete race; use a second delete or short TTL
Reads are hot, writes frequentWrite-through, and copy or near-cache hot keysWrites cost the database and the cache
Cluster changes sizeRendezvous or ring hashing, not moduloWarm new nodes before full traffic
Many absent keysBloom filter, brief negative cachingFilter must be rebuilt as keys are added
Loss of a few seconds of writes is fineWrite-behind with a short flushNever for marks or money

12. Trade-offs to Mention

  • Hit rate against freshness: a longer TTL absorbs more reads and serves older data.

  • Eviction policy depends on whether popularity shifts and whether scans are common.

  • A second copy removes the dip after a node failure and doubles memory and write work.

  • Near-caching a hot key removes load and adds a bounded delay.

  • Write-behind lowers latency and database load and risks recent writes.

  • A cache that is down must not be able to bring the database down; plan for it.

13. Common Mistakes

  • Updating the cache entry instead of deleting it, so two writers can leave the cache different from the database.

  • Giving every entry the same TTL.

  • Using hash modulo in a cluster that grows or loses nodes.

  • Letting a batch job read through the cache and push out hot entries.

  • Ignoring keys that do not exist.

  • Letting one hot key sit on one node.

  • Using write-behind for data that must not be lost.

  • Never testing what the database does when the cache is empty.

14. Interview Questions

  • Why delete the cache entry on a write instead of updating it? Two writers can update the database and the cache in different orders. A delete cannot leave a wrong value, and the next read refills it.

  • How do you stop a flood of lookups for missing keys? A Bloom filter of existing keys, with brief negative caching for repeats. Random keys defeat negative caching alone.

  • What is a cache avalanche and how do you prevent it? Many entries expiring together. Add random jitter to TTLs and limit refill concurrency.

  • One key is far hotter than the rest. What do you do? Detect it, then copy it to several nodes or keep it in application memory for a short time.

  • A cache node dies. What happens to the database? Misses for its keys land there. Use consistent placement, optionally a second copy, and warm new nodes.

  • When is write-behind acceptable? When losing a few seconds of writes does not matter.

Summary

  • The cache exists to protect the database; size it by the hit rate the database needs.

  • Pick the eviction policy from how popularity behaves; no policy wins everywhere.

  • Write the database, delete the entry, delete again shortly after, and keep a TTL.

  • Guard against absent keys with a Bloom filter and against synchronized expiry with jitter.

  • Spread or near-cache hot keys.

  • Use rendezvous or ring placement, and consider a second copy for node failures.

  • Use write-behind only where recent writes may be lost.

Conclusion

A cache makes a system fast on a good day and decides whether the database survives a bad one. The design above handles each bad day with a mechanism and a measured result: stale entries, absent keys, synchronized expiry, a hot key, a lost node and a lost write. In an interview, say what the cache protects, which failure you are guarding against, and what that guard costs.

Previous topic: Design Key-Value Store. Next topic: Design a CDN.

References and further reading

  • Karger et al., Consistent Hashing and Random Trees (STOC 1997), and Thaler and Ravishankar, Using Name-Based Mappings to Increase Hit Rates (1998), for rendezvous hashing.

  • Corbato, A Paging Experiment with the Multics System (1968), for the clock algorithm.

  • B. H. Bloom, Space/Time Trade-offs in Hash Coding with Allowable Errors (1970).

  • Consistent Hashing, Consistency Models, Design API Gateway (stampede protection) and Design Key-Value Store (Bloom filters) on this site.