Lesson 24 of 38Case studies
Design a Distributed Cache
Build Redis or Memcached from the inside: an O(1) LRU, slab memory, hash slots and redirects, failover, hot keys, and keeping the cache honest with the database.
In the Caching lesson you put a cache in front of a database and treated it as a box that answers in a millisecond. This lesson opens the box. The prompt "design a distributed cache" (or "design Redis") asks you to build the thing itself: a key-value store that answers a million requests a second, spreads data across dozens of nodes, survives a node dying, and does not quietly serve wrong data. It is a favourite senior interview because every choice has a sharp trade-off, and the same knowledge pays off at work whenever your Redis cluster pages someone at 2 a.m.
Requirements
Functional
get(key),put(key, value, ttl),delete(key).- Keys expire after their TTL.
- When memory is full, evict something (LRU by default).
Non-functional
- 1 million operations a second, about 90% reads.
- p99 under 1 ms inside one datacenter.
- Hundreds of GB of data, more than one machine holds.
- Survive the loss of any single node without a stampede onto the database.
Out of scope: being the source of truth. A cache may lose data, and the system must be correct (if slower) when it does. Durable key-value stores are a different design.
Back-of-the-envelope numbers
| Quantity | Math | Result |
|---|---|---|
| Data | 300M keys × about 1 KB | about 300 GB |
| Per-key overhead | hash entry, object header, pointers, expiry | roughly 50 to 100 bytes |
| Throughput per node | plan about 100k ops/s for headroom | 10 nodes minimum for 1M ops/s |
| Memory per node | 64 GB machine, keep about half for data | about 32 GB usable |
| Primaries | 300 GB / 32 GB, rounded up for growth | 16 primaries, plus 1 replica each |
Two lessons hide in this table. Per-key overhead matters: with tiny values (a 10-byte counter), metadata can be bigger than the data, so millions of small keys cost far more memory than their values suggest. And you only use about half the RAM because a Redis snapshot uses fork(), and copy-on-write can nearly double memory during heavy writes. Many cache clusters turn persistence off on primaries for exactly this reason.
Single node first: an O(1) LRU
Get one node right before you distribute anything. The Caching lesson used Python's OrderedDict for LRU. Underneath, that is a hash map plus a doubly linked list. The map finds a key's node in O(1). The list keeps nodes in recency order, and because each node knows its neighbours, moving it to the front or removing the oldest from the back is also O(1). No scanning, no sorting.
Press Run (⌘ Enter) to see what happens.The sentinel head and tail nodes remove every "is the list empty?" special case, a trick worth using in an interview whiteboard.
What real servers do differently. Two pointers per key is 16 bytes, which across 300 million keys is almost 5 GB of pure bookkeeping. Redis does not keep a true LRU list. It stores a small access clock in each object and, when it must evict, samples a few random keys (maxmemory-samples, default 5) and evicts the oldest of them, keeping a small pool of good candidates between rounds. The result is close to true LRU at a fraction of the memory. Expiry is similarly lazy: an expired key is deleted when someone touches it, and a background cycle samples keys with TTLs to catch the rest.
Memcached uses a slab allocator. Calling malloc and free for every item fragments memory over days. Instead, Memcached carves memory into 1 MB pages and assigns each page to a slab class with a fixed chunk size. Chunk sizes grow by a factor (1.25 by default), so there is a class for 96-byte items, one for 120-byte items, and so on. An item goes into the smallest chunk that fits. No fragmentation, at the cost of some wasted bytes per chunk. The classic failure is slab calcification: your values grow from 200 bytes to 2 KB after a release, but all pages are stuck in the small class, so the hit rate collapses. Modern Memcached moves pages between classes automatically, and it keeps a segmented LRU per class.
Partitioning: who owns which key?
With 16 primaries, every request must reach the node that owns its key. There are two common designs.
Client-side consistent hashing (the Memcached way). Memcached servers know nothing about each other. The client library hashes each key onto a ring of virtual nodes and talks to the owner directly, exactly as in the Replication and Sharding lesson. It is simple and fast, with no extra hop. The downside is that every client must agree on the server list, and changing it is a deploy, not a command.
Hash slots (Redis Cluster). Redis Cluster splits the key space into exactly 16,384 slots. A key's slot is CRC16(key) mod 16384, and each primary owns ranges of slots. Clients fetch the slot map once (CLUSTER SHARDS), cache it, and send each command straight to the right node. Moving data means moving slots, which is a fine-grained, online operation.
When the client's map is wrong, the server tells it:
MOVED 3999 10.0.0.7:6379: slot 3999 now lives elsewhere, permanently. The client retries there and refreshes its slot map.ASK 3999 10.0.0.7:6379: slot 3999 is being migrated right now, and this key has already moved. The client sendsASKINGand then the command to the new node, for this one request only, without updating its map, because the rest of the slot is still on the old node.
Multi-key commands (MGET, transactions, Lua scripts) only work when all keys are in the same slot. Hash tags make that possible: if a key contains {...}, only the part inside the braces is hashed. So {user:1}:profile and {user:1}:cart always share a slot. This code computes slots the same way Redis does, and the first two results match the examples in the Redis docs.
Press Run (⌘ Enter) to see what happens.Hash tags have a cost. Put {tenant} on every key and your biggest tenant becomes one hot slot on one node. Use them for small groups of keys that truly need atomic multi-key operations.
Replication and failover
Each primary has at least one replica that receives its write stream. Replication is asynchronous: the primary replies OK to the client, then forwards the write. That keeps writes sub-millisecond, but if the primary dies, writes from its last few milliseconds that never reached the replica are gone. The WAIT command lets a client block until N replicas have a write, which shrinks the window but does not make Redis strongly consistent. For a cache this trade is usually right: a lost write means a missing or stale entry, which the TTL and the database will repair.
Redis Cluster detects failure with gossip. Every node pings others over a cluster bus. If a primary does not answer within cluster-node-timeout, a node marks it PFAIL (possibly failed). When a majority of primaries agree, it becomes FAIL, and its replicas hold an election. The replica that wins votes from a majority of primaries promotes itself, takes over the slots, and bumps its config epoch so everyone accepts the new map.
Order the events when a Redis Cluster primary's machine dies.
- Tap the steps below in the right order.
What about a network split? A primary on the minority side stops accepting writes once it notices it cannot reach a majority for the node timeout. Until then it can still accept a few writes that will be thrown away when the partition heals. The Consistency and CAP lesson explains why no design avoids this trade without paying in latency.
Hot keys
Hashing spreads keys evenly, but it cannot spread one key. A celebrity's profile or a flash-sale item can take 300,000 reads a second, three times what its node can serve. Fixes, from cheapest:
- L1 in-process cache. Each app server keeps the hottest keys in local memory for 1 to 5 seconds. A thousand servers each asking once a second is 1,000 requests instead of 300,000. Redis 6 added server-assisted client-side caching (
CLIENT TRACKING), where the server tells clients when a locally cached key changes. - Read from replicas. Spread reads for a hot slot across its replicas, accepting slightly stale reads.
- Key replication. Write the value under N keys (
item:42#0throughitem:42#7), which land on different nodes, and have readers pick one at random. Writes get N times more expensive, so only do it for known hot keys. - Request coalescing. When a hot key misses, let one request rebuild it while the rest wait, as the Caching lesson showed for stampedes.
Finding hot keys is half the job. Sample keys in the client library, or use redis-cli --hotkeys (it needs an LFU eviction policy), and push the hot list to app servers so the L1 cache knows what to hold.
Keeping the cache consistent with the database
Cache-aside with delete-on-write (the pattern from the Caching lesson) has a race that bites real systems. It needs a slow reader and a writer at the same moment:
The key is not cached, so the reader will load it.
What does this print?
db = {"price": 10}
cache = {}
seen = db["price"] # reader misses and reads the DB
db["price"] = 12 # writer updates the DB
cache.pop("price", None) # writer deletes the cache key
cache["price"] = seen # reader finally fills the cache
print(cache["price"], db["price"])Fixes, in rising order of strength:
- Short TTLs. Bounds the damage. Always do this.
- Delayed double delete. The writer deletes, waits a few hundred milliseconds, and deletes again. It is cheap and catches most slow readers, but the delay is a guess.
- Versioned values. Store a version (an
updated_ator row version) with the value, and only set if the new version is higher, using a small Lua script so the compare-and-set is atomic. - Leases. Facebook's 2013 paper on scaling Memcache describes this. On a miss, the cache hands the reader a lease token. A delete cancels outstanding leases, so a set with a cancelled token is rejected. Leases also tame stampedes, because only one reader at a time gets a token for a key and the rest are told to wait.
- Invalidate from the database log. Facebook also tails the MySQL commit log and sends deletes to the cache, so invalidation does not depend on every code path remembering to delete.
Press Run (⌘ Enter) to see what happens.A production version also gives leases a short expiry, so a reader that crashes while holding one does not block the key forever.
Which software, and the licence question
You will rarely build this from scratch. You will run Redis, Valkey, or Memcached, often as a managed service, and you should know the licence history because legal teams ask. In 2024 Redis moved from the BSD licence to source-available licences (RSALv2 and SSPLv1). The Linux Foundation then started Valkey, a fork of the last BSD-licensed Redis. In 2025 Redis 8 added the open-source AGPLv3 as another licensing option. AWS ElastiCache and Google Cloud Memorystore both offer Valkey. For most application code the commands are the same, but check the current licence terms and your provider's docs before you choose.
Match each problem to the mechanism that solves it.
Bottlenecks, failures, and 10x scale
- Cold cache after a failure. A promoted replica is warm, but a node replaced from scratch is empty. Warm it before routing traffic, and size the database to survive a single shard's misses.
- Big keys and slow commands. A 50 MB hash or a
KEYS *blocks a single-threaded node, and every client on it sees the stall in their p99. BanKEYS(useSCAN), cap value sizes, and alert on slow-log entries. - Connection storms. Thousands of app servers × connection pools can exhaust a node. Use pooling with sane limits, or a proxy layer.
- 10x (10M ops/s): add primaries and rebalance slots online. Per-node throughput rises with I/O threading in recent Redis and Valkey versions, so measure before adding hardware. Lean harder on L1 caches, because the cheapest request is the one that never leaves the app server.
- hash slot
- One of Redis Cluster's 16,384 key buckets; a key's slot is CRC16(key) mod 16384, and each primary owns slot ranges.
- MOVED vs ASK
- MOVED means a slot has permanently moved, so update the map; ASK means it is mid-migration, so redirect this one request.
- hash tag
- The
{...}part of a key; only it is hashed, so related keys share a slot and can be used together. - slab allocator
- Memcached's memory scheme: fixed-size chunks in size classes, avoiding fragmentation at the cost of some wasted bytes.
- approximated LRU
- Evicting the oldest of a few randomly sampled keys instead of keeping an exact recency list.
- lease
- A token given to a reader on a cache miss; a delete invalidates it, so a stale set is rejected.
- hot key
- A single key whose traffic exceeds what its one owning node can serve, no matter how many nodes you add.