Design: distributed cache
Partition keys across memory-only nodes by hash slot or consistent hashing, evict by LRU or LFU at a memory limit, replicate asynchronously for failover, and protect the database from hot keys and cold nodes.
Fundamentals you'll use
How it works
- Each node is a hash table with a memory limit; when full, it evicts by LRU or LFU.
- Redis Cluster maps keys to 16,384 slots owned by nodes; Memcached clients hash keys onto a ring.
- A smart client reaches the owner in one hop; a proxy keeps clients thin but adds a hop.
- Replication is asynchronous: a failover can lose acknowledged writes, which a cache tolerates.
- Losing 1 of 10 nodes at a 95% hit rate nearly triples the database load.
Check yourself
Answer to mark it learned; your answers aren't scored.
One node of your 20-node cache cluster sits at 100% CPU while the others idle at 15%. Sampling shows a single key receives 30% of all reads. What is the best first move?
Go deeper
Full explanation
Requirements
Functional: get, set with a TTL, and delete on string keys, with values up to ~1 MB. Non-functional: sub-millisecond server time, capacity that grows by adding nodes, and no durability promise: it is a cache, so a lost entry is just a miss. What it must never do is fail in a way that sends all traffic to the database at once.
Scale (assumed): 240 GB of hot data and 500k operations/s at peak.
Questions I'd ask:
- Can every entry be rebuilt from a source of truth, or is this a store in disguise?
- What does a miss cost the backend?
- Do clients need multi-key operations?
Node design
Each node is a hash table in RAM with a memory limit. When it is full, a write evicts another entry: usually LRU, or LFU when a few keys dominate and a scan would flush them. TTLs expire lazily on read, plus a background sweep. How applications use a cache is in Caching strategies.
Architecture
Partitioning maps a key to a node. Memcached servers know nothing about each other: the client hashes keys onto a ring (Consistent hashing). Redis Cluster hashes every key into one of 16,384 slots and assigns slots to nodes. Routing is done by a smart client that holds the map, or by a proxy that hides it. Replication is asynchronous, primary to replica, and a replica is promoted when its primary dies.
The hard parts
- Hot keys. Hashing spreads keys, not load: one celebrity key still lands on one node.
- A node dies or restarts cold. Its share of the keys now misses, and the database receives that traffic in one burst.
Code Redis Cluster routing: hash slot, MOVED and ASK
from binascii import crc_hqx
def key_slot(key: bytes) -> int:
# Hash tag: if the key contains {...}, only that part is hashed, so
# user:{42}:cart and user:{42}:profile share a slot and multi-key ops work.
start = key.find(b"{")
if start != -1:
end = key.find(b"}", start + 1)
if end > start + 1:
key = key[start + 1:end]
return crc_hqx(key, 0) % 16384 # CRC16-XMODEM; key_slot(b"foo") == 12182
class SmartClient:
def __init__(self, seed_node):
self.slots = fetch_slot_map(seed_node) # CLUSTER SHARDS: slot -> primary
def call(self, cmd: str, key: bytes, *args, max_redirects: int = 5):
node = self.slots[key_slot(key)] # one hop, no proxy
for _ in range(max_redirects):
reply = node.send(cmd, key, *args)
if reply.is_error("MOVED"): # slot has a new owner: my map is stale
self.slots = fetch_slot_map(node)
node = self.slots[key_slot(key)]
elif reply.is_error("ASK"): # slot is mid-migration: one-off hop,
node = connect(reply.address) # and the map stays as it is
node.send("ASKING")
else:
return reply
raise RuntimeError("too many redirects: the cluster is reconfiguring")Real example
A cluster of 10 primaries serves reads at a 95% hit rate, so the database sees 5% of them. One node dies with no replica. Its 10% of the keys now always miss: database load becomes 10% + 90% × 5% = 14.5% of reads, 2.9× normal, within seconds.
With a replica, promotion takes the node timeout plus a second or two, and only writes not yet replicated are lost. With a spare gutter pool, as Facebook runs, clients send the dead node's keys there instead: each key misses once, then hits.
Trade-offs +3 · −3
+ You gain
- Scales by adding nodes: memory and throughput grow with the number of shards.
- A smart client reaches the owner in one hop, with no proxy or coordinator on the request path.
- Replicas turn a node failure into a brief failover instead of a miss storm.
− You pay
- Asynchronous replication can lose acknowledged writes on failover: fine for a cache, wrong for a store.
- Hot keys and large values overload one node however many nodes you add.
- Multi-key operations work only inside one slot; there are no cross-node transactions.
Use it when
A read-heavy service whose hot data no longer fits one cache node, or whose database could not survive that node failing.
Avoid it when
Data you can't rebuild: use a database or Design: distributed key-value store. Or data that fits one node with a replica: clustering adds moving parts for nothing.
Numbers to know 5
- Redis Cluster: 16,384 slots, slot = CRC16(key) mod 16384; suggested maximum of ~1,000 nodes.
- Memcached defaults: 64 MB of memory, 1 MB max item, 4 threads, port 11211; keys are limited to 250 bytes.
- Redis defaults: no memory limit,
noeviction, and 5 keys sampled per eviction. - Sizing (assumed): 240 GB ÷ 24 GB usable per 32 GB node = 10 primaries, 20 nodes with replicas; 500k ops/s ÷ 10 = 50k each.
- Lose 1 of 10 nodes at a 95% hit rate: database load goes from 5% to 14.5% of reads, 2.9×.
Common pitfalls 4
- Redis as a cache on defaults: no memory limit and
noeviction, so it grows until the OS kills it. - Rehashing a dead node's keys onto its neighbors: the hot key moves too and takes down the next node.
- Treating failover as lossless: replication is asynchronous, so acknowledged writes can vanish.
- Multi-key commands across slots: Redis Cluster rejects them unless the keys share a hash tag.
Interview questions 3
Answer out loud first, then reveal.
Consistent hashing or hash slots?Show answer
Both limit how many keys move when nodes change; they differ in who knows the mapping. Every client computes a ring from the member list: no coordination, ideal for Memcached, whose servers don't talk to each other. Slots add an explicit table, 16,384 entries in Redis Cluster, so I can move one slot, see who owns what and migrate online. I'd pick slots when the cluster manages itself, and a ring when clients or a proxy own routing.
One key receives 30% of all reads. What do you do?Show answer
Adding nodes won't help: one key lives on one node. First I put a small in-process cache with a TTL of a few seconds in each app server, which absorbs most reads before the network. If staleness matters, Redis client-side caching invalidates it on change. Next come replica reads, or splitting the key into k copies on different nodes and reading a random one. I'd also sample requests to detect hot keys, so the next one is found early.
A cache node dies. Walk me through what happens.Show answer
With a replica: a majority of primaries marks it failed after the node timeout, a replica is elected in a second or two, and clients refresh their slot maps. Unreplicated writes are gone, which a cache accepts. Without a replica its keys miss and the database takes the burst: at a 95% hit rate, losing 1 of 10 nodes nearly triples its load. So I size the database for that or run a gutter pool, and coalesce refills.
Deep dive 4
Partitioning and routing
Consistent hashing (Memcached clients): nodes sit on a ring with virtual nodes; adding one moves ~1/N of the keys, and the servers coordinate nothing. Hash slots (Redis Cluster): CRC16(key) mod 16384 picks a slot and a table maps slots to nodes. Resharding moves whole slots, one at a time, while the cluster keeps serving; ownership is explicit and inspectable. Routing: a smart client caches the slot map and reaches the owner in one hop; on MOVED it refreshes the map, on ASK it follows a one-off redirect during a migration. A proxy such as Facebook's mcrouter speaks the cache protocol to simple clients and pools connections, at the price of an extra hop and another tier to run. Multi-key commands work only when the keys share a slot: force that with hash tags like user:{42}:cart.
Eviction and memory
A cache without a memory cap is a memory leak. Memcached starts with 64 MB and evicts by LRU. Redis ships with no limit and noeviction, so a Redis cache must set maxmemory and a policy, usually allkeys-lru. Redis keeps no true LRU list: it samples 5 keys (maxmemory-samples) and evicts the best candidate, close to real LRU for a fraction of the memory. LFU (allkeys-lfu, Redis 4.0+) keeps an approximate, decaying access counter per key, so a nightly scan can't push out the truly hot keys as it does under LRU. Leave headroom: replication buffers are not counted in maxmemory. Watch evictions and hit rate together: a falling hit rate with rising evictions means the cache is too small, not that the TTLs are wrong.
Failover and the cold-cache problem
With asynchronous replication the primary answers before the replica has the write; the Redis Cluster spec says plainly that acknowledged writes can be lost in a failover. For a cache that is fine. The load shift is not. When a node dies you can promote a replica (warm, but 2× the memory); rehash onto the survivors (cheap, but the node that inherits a hot key can overload and fail too, a cascade Facebook explicitly avoids); or keep a gutter pool, idle machines (~1% of the servers in a Facebook cluster) that temporarily take the dead node's keys with short TTLs. For restarts and scale-ups, warm a node before it takes full traffic. And coalesce every miss: Facebook's leases let one client refill a key while the others wait, cutting a peak of 17K database queries/s to 1.3K.
Hot keys
One key can dominate: Facebook reports that a single key can account for 20% of a server's requests. Partitioning can't help, because a key lives on one node by definition. In order of cost: an in-process cache in each app server with a TTL of seconds removes most reads before they touch the network; Redis 6+ can keep it fresh with client-side caching, where the server sends an invalidation when a tracked key changes. Read from replicas for keys that tolerate lag. Split the key into key#1…key#k copies on different nodes and read a random one; writes must update all k. Find hot keys by sampling requests at the client or proxy, not by guessing. Large values are the sibling problem: a 1 MB value read 1,000 times/s is 1 GB/s of network from a single node.