Design a distributed cache like Redis Cluster or Memcached at scale.
Hash every key onto a ring of memory, and keep a hot spare for every shard.
Consistent hashing (or fixed hash slots) so adding a node moves only about 1/N of the keys.
- Partition with consistent hashing
- Replicate each shard and fail over automatically
- Protect the DB: TTL jitter, request coalescing, hot-key copies
1. Requirements
get,setwith TTL,delete; sub-millisecond latency; millions of operations per second; terabytes of data in memory.- Horizontal scaling by adding nodes with minimal data movement; tolerate node failures.
- Consistency: cache semantics (stale reads acceptable within TTL), but replicas should converge.
2. Build it step by step
Stage 1: a single cache node
Flow:
- Applications send
GET key; on a miss they load from the database andSET key value EX ttl. Memory is bounded with LRU eviction.
Problem: one node limits memory (say 64 GB) and throughput (about 100K ops/s), and if it dies every request falls through to the database at once.
Stage 2: partition keys across many nodes
Flow:
- The client hashes the key onto a ring with virtual nodes and sends the request to the owning node. Adding node D moves only about a quarter of the keys instead of nearly all of them (which
hash mod Nwould do).
Problem: losing a node still loses its share of data and sends a spike to the database; clients must agree on the ring.
Stage 3: replicas, failover and a cluster map
Flow:
- Clients map key → slot → primary (Redis Cluster style) and are redirected with
MOVEDif their map is stale. - Each primary replicates to a replica.
- If a primary fails, the cluster promotes its replica and clients refresh the map.
Problem: a single extremely hot key still lands on one shard, and mass expiry of a popular key causes a thundering herd on the database.
Final architecture: near cache and stampede protection
End-to-end read:
- The app checks a small local cache for the hottest keys.
- Then the owning shard (replicas can serve reads for hot keys).
- On a miss, only one caller loads from the database (request coalescing or a short lock) while others wait; TTLs have jitter so popular keys do not expire together.
End-to-end write: the database is updated first, then the cache key is deleted (or invalidated via a change stream).
3. Deep dives
- Partitioning: simple
hash(key) mod Nremaps almost every key when N changes. Use consistent hashing with virtual nodes (each physical node owns many points on a ring), so adding a node moves only about 1/N of keys and load stays even. Redis Cluster uses a variant: 16,384 hash slots assigned to nodes; resharding moves slots. - Routing: smart clients cache the slot map and talk directly to the right node (Redis Cluster returns
MOVEDwhen the map is stale), or a proxy layer (Twemproxy, Envoy) routes for dumb clients. - Replication and failover: each primary has replicas with asynchronous replication; the cluster detects failure by gossip and promotes a replica. Asynchronous replication means acknowledged writes can be lost on failover, which is acceptable for a cache.
- Eviction: when memory is full, evict by LRU or LFU approximations (Redis samples keys rather than keeping an exact LRU list); TTL expiry is done lazily on access plus by an active sampling sweep.
- Memory efficiency: compact encodings for small hashes and lists, avoid huge keys and values, monitor fragmentation.
- Hot keys: a single key that receives a flood of reads is bounded by one shard. Mitigate with a local in-process cache in front (near cache), replicating the key under several names (
key#1..#n) and reading a random copy, or reading from replicas. - Cache patterns: cache-aside (application loads on miss), read-through and write-through (cache library loads and writes), write-behind (asynchronous writes to the DB, risky).
- Thundering herd: on a popular key's expiry, many requests miss together. Use request coalescing (single flight), a short lock key, or early probabilistic refresh, and add TTL jitter.
4. Trade-offs
Asynchronous replication gives speed but possible lost writes; synchronous replication (WAIT) costs latency. Smart clients avoid a proxy hop but complicate clients.
Follow-up questions interviewers ask
Try answering each one before you open it.
How does consistent hashing reduce data movement?
Nodes and keys are mapped onto the same hash ring; a key belongs to the first node clockwise from its position. Adding a node only takes over keys between it and its predecessor, about 1/N of the total, and removing a node hands its keys to the next node. Virtual nodes (many ring positions per node) spread each node's share across the ring, which evens out load and lets more powerful nodes take more virtual nodes.
How do you keep the cache consistent with the database?
Use cache-aside: read from cache, on miss read the DB and populate; on write, update the DB and then delete (not update) the cache key, ideally after commit. To close the race where a reader repopulates a stale value between the DB write and the delete, use short TTLs, a delayed second delete, versioned values (only write if newer), or invalidate from the database's change stream (CDC) so invalidation follows commit order.