Skip to content

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.

23 min read0/5 questions

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

QuantityMathResult
Data300M keys × about 1 KBabout 300 GB
Per-key overheadhash entry, object header, pointers, expiryroughly 50 to 100 bytes
Throughput per nodeplan about 100k ops/s for headroom10 nodes minimum for 1M ops/s
Memory per node64 GB machine, keep about half for dataabout 32 GB usable
Primaries300 GB / 32 GB, rounded up for growth16 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.

Pythonlru_cache.py
class Node: __slots__ = ("key", "value", "prev", "next") def __init__(self, key=None, value=None): self.key, self.value = key, value self.prev = self.next = None class LRUCache: def __init__(self, capacity): self.capacity = capacity self.map = {} # key -> Node, O(1) lookup self.head, self.tail = Node(), Node() # sentinels: head.next is newest self.head.next, self.tail.prev = self.tail, self.head def _unlink(self, node): node.prev.next, node.next.prev = node.next, node.prev def _push_front(self, node): node.prev, node.next = self.head, self.head.next self.head.next.prev = node self.head.next = node def get(self, key): node = self.map.get(key) if node is None: return None self._unlink(node) # O(1): we hold the node itself self._push_front(node) return node.value def put(self, key, value): if key in self.map: node = self.map[key] node.value = value self._unlink(node) else: if len(self.map) == self.capacity: oldest = self.tail.prev # least recently used self._unlink(oldest) del self.map[oldest.key] print(f" evict {oldest.key}") node = Node(key, value) self.map[key] = node self._push_front(node) def order(self): out, n = [], self.head.next while n is not self.tail: out.append(n.key) n = n.next return out cache = LRUCache(3)for op in ["put a", "put b", "put c", "get a", "put d", "get b", "put e"]: verb, key = op.split() if verb == "put": cache.put(key, key.upper()) print(f"{op:6s} -> {cache.order()}") else: print(f"{op:6s} = {cache.get(key)!s:4s} -> {cache.order()}")
Output
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.

Quick check
Why does Redis approximate LRU by sampling instead of keeping an exact LRU linked list?
Need a nudge? A hint rules out a wrong answer.

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 sends ASKING and 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.

Pythonkey_slot.py
def crc16(data: bytes) -> int: # CRC16-CCITT (XMODEM): polynomial 0x1021, initial value 0 crc = 0 for byte in data: crc ^= byte << 8 for _ in range(8): crc = ((crc << 1) ^ 0x1021) if crc & 0x8000 else crc << 1 crc &= 0xFFFF return crc def key_slot(key: str) -> int: # Hash tag: if the key has {...} with something inside, hash only that part start = key.find("{") if start != -1: end = key.find("}", start + 1) if end > start + 1: key = key[start + 1:end] return crc16(key.encode()) % 16384 for key in ["somekey", "foo{hash_tag}", "user:1:profile", "user:1:cart", "{user:1}:profile", "{user:1}:cart"]: print(f"{key:18s} slot {key_slot(key):5d}")
Output
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.

Put it in order5 steps

Order the events when a Redis Cluster primary's machine dies.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

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#0 through item: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.

Quick check
One key gets 300,000 reads a second, and its node tops out at about 100,000. You add 8 more primaries. What happens?
Need a nudge? A hint rules out a wrong answer.

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 stale-set race in cache-aside
ReaderCacheDatabaseWriterget pricemissSELECT price10UPDATE price = 12delete priceset price = 10

The key is not cached, so the reader will load it.

1/7
Predict the outputPython

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"])
Need a nudge? Hints walk you through it.

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_at or 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.
Pythonleases.py
import itertools class LeaseCache: """Leases in the style of Facebook's memcache paper, simplified.""" def __init__(self): self.data = {} self.leases = {} # key -> token handed out on a miss self.tokens = itertools.count(1) def get(self, key): if key in self.data: return self.data[key], None if key in self.leases: return None, "wait" # someone else is filling it: retry soon token = next(self.tokens) self.leases[key] = token return None, token # you may fill it, with this token def set(self, key, value, token): if self.leases.get(key) != token: return False # lease was invalidated: drop the stale value del self.leases[key] self.data[key] = value return True def delete(self, key): self.data.pop(key, None) self.leases.pop(key, None) # a delete also cancels outstanding leases db = {"price": 10}cache = LeaseCache() _, token_a = cache.get("price") # reader A misses and gets a leaseseen = db["price"] # A reads 10 from the DB, then stallsprint("reader B:", cache.get("price")) # B misses too, but is told to wait db["price"] = 12 # writer updates the DBcache.delete("price") # and deletes the key, killing A's lease print("A's late set accepted?", cache.set("price", seen, token_a))_, token_c = cache.get("price") # the next reader gets a fresh leasecache.set("price", db["price"], token_c)print("cache now:", cache.get("price")[0])
Output
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 the pairs0/5 matched

Match each problem to the mechanism that solves it.

Choose an item, then its match on the other side.

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. Ban KEYS (use SCAN), 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.
Key terms
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.