What it is
A distributed cache is a set of in-memory nodes that together act as one large key-value cache. Each key belongs to one node (its owner), chosen by hashing the key; clients or a proxy compute the owner and talk to it directly. Optionally each node has replicas. Memcached clusters with client-side hashing, Redis Cluster (16,384 hash slots spread over primaries with replicas) and managed equivalents all follow this shape.
This lesson designs the cache tier itself: how big, how keys are spread, what happens when a node dies or comes back, and what to do about hot keys. The ring mechanics are in the Consistent Hashing lesson; the read pattern is cache aside or read-through.
Why it exists
One cache node hits two ceilings. Memory decides how many keys fit and therefore the hit ratio. Throughput (CPU, network, connections) decides how many requests per second it answers, regardless of hit ratio. A bigger machine raises both a little; spreading keys over many nodes raises both linearly. A distributed cache also limits the blast radius of a failure to one node's share of the keys.
How it works
Sizing. Start from the hot set and the request rate, both from your requirements:
| Quantity | Example (illustrative) | Result |
|---|---|---|
| Hot set | 200M keys × ~1 KB (key, value, overhead) | ≈ 200 GB |
| Usable memory per node | 64 GB × 75% (leave room for fragmentation, replication buffers, forks) | 48 GB |
| Primaries for memory | 200 ÷ 48 | 5 |
| Primaries for throughput | 500k ops/s ÷ a conservative per-node budget | depends on value size and commands; measure |
| With one replica per shard | 5 × 2 | 10 nodes |
Take the larger of the memory and throughput counts, then add headroom so the database survives one node's share of misses.
Routing. The cache client (a library in each application instance, or a proxy such as mcrouter or twemproxy) hashes the key and picks the owner. Consistent hashing with virtual nodes, or a fixed number of hash slots assigned to nodes (Redis Cluster), means adding or removing a node moves only about 1/N of the keys. Client-side routing saves a hop; a proxy centralises topology changes and connection pooling.
Partitioning adds memory. Because a key lives only on its owner, three nodes hold three times as many distinct keys as one. In the simulation the hit ratio goes from about 55% (one node, 200 of 2,000 keys) to about 70% (three nodes, 600 keys) while traffic grows. Round-robin spreading would not do that: every node would cache the same popular keys.
Node failure. When a node dies, reads to it fail until the client or health checks notice. Then its keys map to other nodes, which do not have them: misses. Popular keys are re-cached within milliseconds; the long tail keeps missing because less total memory now holds the same key space. In the simulation the database read rate jumps by more than half right after the ejection and settles clearly higher.
Cold rejoin. A restarted in-memory node is empty. If it rejoins at full weight, its keys move back and miss a second time. Warm it first (replay recent keys, or copy from a replica), rejoin it gradually, or promote a replica instead.
Hot keys. A key always maps to one node, so a key that gets 40% of the traffic puts 40% of the load on one node however evenly the ring spreads keys. In the simulation the flash sale saturates node 2 while the others have spare capacity. Fixes: replicas of the hot shard serving reads, a small near cache (in-process, short TTL) for the hottest keys, or splitting a key into key#1…key#n copies and picking one at random on read (writes must update all copies).
Replicas. Each shard gets one or more copies. Redis replicates asynchronously from primary to replicas; reads can be served by replicas if slightly stale data is acceptable. When a primary dies, a replica that already holds the data takes over, so no key moves on the ring and the database barely notices. That is what the failover step shows.
When to use it
When the working set or request rate outgrows one cache node, when a cache node's failure must not send all reads to the database, or when many application instances must share cached state (sessions, rendered fragments, computed results, rate-limit counters).
When not to
- A single node with a replica covers a surprising amount: if the hot set fits in one machine's memory and its throughput is enough, sharding adds operational cost for nothing.
- Per-instance in-process caches are faster and simpler for small, mostly static data (configuration, feature flags) where each instance can afford its own copy.
- A cache is not a database: if losing the data is unacceptable, keep the source of truth elsewhere.
Trade-offs
| Choice | You gain | You pay |
|---|---|---|
| More, smaller nodes | Smaller blast radius per failure; more aggregate throughput | More connections and topology to manage |
| Client-side routing | No extra hop | Every client needs the topology and the same hash function |
| Proxy routing | Central topology, pooled connections | An extra hop and a tier to run |
| Replicas | Cheap failover; read capacity for hot shards | ~2× memory; asynchronous replicas can serve stale data |
| Reads from replicas | Spreads hot shards | Read-your-writes is no longer guaranteed |
| Near cache for hot keys | Hot keys never leave the instance | Staleness per instance; invalidation is harder |
Alternatives
- Single primary with replicas (no sharding) when one node's memory suffices.
- In-process caches only, accepting duplicated memory and per-instance staleness.
- A CDN or edge cache for public, cacheable HTTP responses: it is a distributed cache someone else runs.
- A database with a large buffer pool or read replicas, if the access pattern is already served well enough by the database's own cache.
Failure modes
- Miss burst on node loss (simulated): the database takes one node's share of misses at once. Keep headroom, or use replicas.
- Cold rejoin: a second burst when an empty node takes its keys back (simulated).
- Hot key saturating one node (simulated) while the cluster average looks fine. Monitor per-node load, not just totals.
- Stampede on a hot key's expiry: many concurrent misses rebuild the same value. Use request coalescing, early refresh or TTL jitter (Cache Stampede).
- Split topology: clients with different views of the ring send the same key to different nodes, producing inconsistent values. Distribute topology from one source and version it.
- Eviction pressure: memory fills, the eviction policy throws out useful keys and the hit ratio drops silently. Alert on evictions and memory headroom.
In production
Watch per-node hit ratio, evictions, memory, CPU, network and connection counts, and the database read rate together: a falling hit ratio is an early warning for the database. Keep TTLs on every key so mistakes age out. Spread primaries and replicas across availability zones. Test node loss in staging and measure the database burst. Use pipelining or multi-get for fan-out reads, and keep values small; one huge value on a node can block it.
Common misconceptions
- "Adding nodes fixes hot keys." It moves other keys around; the hot key stays on one node.
- "A restarted cache node comes back with its data." An in-memory cache without persistence comes back empty.
- "Consistent hashing means no misses when a node fails." It limits which keys move; those keys still miss.
- "Replicas make the cache strongly consistent." Asynchronous replicas can lag; after failover some recent writes may be missing.
Interview angle
Size the tier from memory and throughput with numbers, explain client-side vs proxy routing, and why consistent hashing (or hash slots) beats hash mod N. Then expect: what happens when a node dies (miss burst, database headroom), how a node rejoins, how you handle a hot key, and what replicas cost. Naming the failure-time load on the database is what separates a strong answer. The URL Shortener case study shows a cache tier like this one in use.
Model assumptions
The simulation is a simplified model, not a benchmark. Reads arrive as a Poisson process over 2,000 keys with a Zipf(1) popularity (Zipf 1.6 during the flash sale). Each cache node is a read-through process with 4 workers and about 5 ms of work per request (lognormal, cv 0.3), and its memory is a separate LRU of 200 keys; a worker is held while the node waits for its memory and, on a miss, the database. The database has 3 connections and a 20 ms mean read (about 150 reads/s); a query waiting more than 200 ms for a connection fails. The ring uses 64 virtual nodes per cache node; node ids were chosen so node 2 owns the most popular keys. A crashed node comes back with empty memory. Health checks run every 500 ms (2 failures eject, 3 successes restore). Replication is approximated: the two copies of shard 2 each fill their own memory from the reads they serve (reads alternate between them), which stands in for a replica kept up to date by the primary; replication lag and promotion are not modelled. Numbers show behaviour and orders of magnitude only.