Case study: design a distributed cache
A senior-level walkthrough of a Memcached or Redis-style cache cluster: sizing it, a node's memory and expiry, placement that survives adding a node, and what a lost node does to the database, with tested C#.
Case studyApplied34 min readUpdated
- 1 architecture diagram
- 4 code samples
- 7 interviewer follow-ups
- 4 self-checks
On this page15 sectionsHLDLLDSenior depth
Read first: A framework for system design interviews, Caching, Replication and sharding, Cache consistency, stampedes and hot keys
- Size a cache from hit ratio, memory and operations per second, and explain why a 99% hit ratio makes losing a node dangerous.
- Choose a placement scheme (modulo, a hash ring or hash slots) by what it does to the hit ratio when the cluster changes size.
- Explain how a node stores, evicts and expires entries, and why expired entries can outlive their time to live in memory.
- Plan for failure: replicas, a gutter pool, warming a cold node and protecting the database from the cache.
4 code samples (277 lines), collapsed so the explanation stays in focus.
A cache is the cheapest capacity you can buy: a read served from memory in about a millisecond is a read the database never sees. One machine's memory is not enough for a large system, so the cache becomes a cluster, and the problems change. They stop being about caching and start being about distribution: which node owns a key, what happens to the hit ratio when a node joins or dies, and what a lost node does to the database behind it. This lesson designs a Memcached or Redis-style distributed cache the way a senior round would. It builds on caching (the patterns and eviction), replication and sharding (the hash ring) and cache consistency, stampedes and hot keys, and the placement and expiry mechanisms are simulated in tested C#.
"Design a distributed cache" is vague on purpose. Pin down what is cached and what the cache is allowed to get wrong.
| Ask | Why it matters |
|---|---|
| What goes in it: database rows, rendered fragments, sessions, computed results? | Sets the value size, the time to live and how costly a stale or lost entry is |
| A cache or a store? May any entry vanish at any time? | A cache may lose anything. If the answer is "we need it back", it is a database |
| How stale may a value be? | Seconds of staleness allow a time to live alone. No staleness at all means do not cache it, or invalidate precisely |
| What are the read to write ratio, the key skew and the latency target? | Writes invalidate, skew creates hot keys, and sub-millisecond targets decide whether a proxy hop is affordable |
| What happens when the cache is down? | The application must survive it. Decide the fallback and its limits before the outage |
| One region or several? | Invalidations and read-your-writes across regions |
Functional: get, set with a time to live, delete, a few atomic helpers (increment, compare-and-set) and batch reads. Non-functional: p99 around a millisecond inside a data center, hundreds of thousands of operations a second, bounded staleness, and elasticity: nodes can be added and removed without a miss storm. Availability belongs to the application, not the cache: a cache node can die and the database must survive it. Out of scope: durability, queries across keys and transactions. Say early that a cache is not a database.
State assumptions aloud. They are illustrative and the interviewer may change them.
reads 500,000/s, writes 50,000/s, 200M entries of about 200 B
hit ratio 95%: 25,000 reads/s reach the database; at 99%: 5,000
memory: 200M x (200 B + ~100 B of key and overhead) = 60 GB
plus 25% headroom = 75 GB; at 25 GB per node = 3 nodes
traffic: 550,000 ops/s at ~100,000 per node = 6 nodes
size for the larger (6), lose one at peak (7), round up: 8 nodes
connections: 2,000 app servers x 8 nodes x 4 = 64,000Four conclusions:
- Hit ratio is the lever, and it is not linear. At 95% the database serves 25,000 reads a second, at 99% only 5,000. The last four points are worth a factor of five, and they also make the database fragile, as the failure section shows.
- Traffic may set the node count, not memory. Memory needs three nodes and operations need six. Add a node for a failure at peak and round up. Operations per node is a rule of thumb (roughly 100,000 for a single-threaded server answering small requests): measure your own.
- Cache the working set, not the data. Popularity is skewed, so a cache holding a fifth of the keys can serve most requests: in the placement experiment below, 20% of the keys gave an 80% hit ratio. Size from a measured curve of hit ratio against memory.
- Connections add up. 64,000 connections over 8 nodes is 8,000 each, close to the default client limit of a Redis server (10,000). A routing tier that pools connections, or a multiplexing client, exists for this reason.
| Operation | Behaviour | Used for |
|---|---|---|
get(key) | The value, or a miss | Every read. A miss sends the caller to the database |
set(key, value, ttl) | Stores the value, replacing any old one | Filling after a miss. The entry can still be evicted early |
add(key, value, ttl) | Stores only if the key is absent | Simple locks, "not found" markers, leases |
delete(key) | Removes the key. Safe to repeat | Invalidation after a write |
incr(key), cas(key, value, version) | Atomic increment; store only if unchanged | Counters, rate limits, optimistic updates |
get_many(keys) | Several keys at once, one request per node | Fewer round trips. The batch is as slow as its slowest node |
Three promises define it. A miss is always allowed: any entry can disappear (eviction, restart, failover) and the caller reads the source of truth. An expired entry is never returned, so a missed invalidation can leave a value stale for at most its time to live. Nothing is durable, even where the server can persist data (Redis can write snapshots and a log): never keep the only copy of anything in a cache. Keys are short (Memcached caps them at 250 bytes) and values are small (Memcached's default item limit is 1 MB). Redis accepts far larger values, but copying one blocks a single-threaded server and hurts every other request's tail latency (see tail latency and overload).
An application asks for a key and something must work out which node holds it. There are three common topologies.
| Topology | Who knows where a key lives | Strengths | Costs |
|---|---|---|---|
| Client-side routing | Every client library holds the node list and hashes the key itself (classic Memcached clients) | No extra hop, simple servers | Every client must agree on the list; each client connects to every node; failure handling is repeated in each client |
| A proxy tier | A fleet of routers holds the map and clients talk to a router (Facebook's mcrouter, Twitter's twemproxy, Envoy's Redis proxy) | Simple clients, pooled connections, retries, failover and pools in one place | An extra network hop, and a fleet to run and scale |
| A cluster that redirects | The nodes know the slot map and answer a wrong guess with a redirect (Redis Cluster: MOVED, ASK); clients cache the map | No proxy, and resharding is built in | Clients must be cluster-aware; a stale map costs a round trip; multi-key commands must stay within one slot |
Whichever is chosen, the cluster map (which node owns which keys, and which nodes are healthy) is the shared state: small, versioned and quickly distributed. It lives in a configuration service or is gossiped between the nodes (Redis Cluster nodes gossip, and promote a replica when a primary is judged failed). A stale map is cheap when one authority enforces placement: the node redirects, and the worst case is an extra hop. With client-side routing it is not: two clients holding different node lists place the same key on different nodes, and a delete reaches only one of them, which leaves a stale copy behind. Roll out node-list changes carefully, or use a proxy or a redirecting cluster so that placement has one authority.
A node has to find entries in constant time, manage memory without wasting it, choose what to evict, and retire what has expired.
- Memory is the budget, and overhead is real. Each entry holds the key, the value, a hash-table slot, expiry and recency metadata and allocator overhead: tens of bytes that matter when values are 200 bytes. Memcached cuts memory into pages divided into fixed-size chunks per slab class, with chunk sizes growing by a factor (1.25 by default). An item takes the smallest chunk that fits and wastes the difference, about 10% on average, and memory assigned to one class cannot serve another until pages are rebalanced. Redis uses a general allocator (jemalloc by default on Linux), so the same cost shows up as fragmentation, which it reports and can defragment online.
- Threading shapes the failure modes. Redis runs commands on one thread (newer versions can use extra threads for network I/O). Every command is atomic and needs no locks, but one slow command stalls everything queued behind it: a large
KEYS, deleting a huge collection, copying a 10 MB value. Memcached is multi-threaded around a shared hash table. Either way, keep commands O(1) and values small, and scale a hot node by splitting its data, not by adding threads. - Eviction picks a victim when memory is full. Exact LRU needs a recency list updated on every read, so even reads write and contend for a lock. Real systems approximate: Redis samples a few random keys (the
maxmemory-samplessetting) and evicts the least recently used among them, and Memcached keeps segmented lists (hot, warm and cold). Choose a policy at all: Redis's default,noeviction, rejects writes at the memory limit, which is wrong for a cache (the usual choices areallkeys-lruorallkeys-lfu). Admission can matter as much as eviction: TinyLFU keeps a compact frequency sketch (see probabilistic data structures) and admits a new key only if it is likelier to be reused than the entry it would evict, so a scan of once-read keys cannot flush the hot set (Caffeine's W-TinyLFU is built on it). Replay the basic policies in the cache eviction lab. Time to live and sizing usually matter more: a study of 153 cache clusters at Twitter found that expiry limits the working set, that FIFO often matched LRU at reasonable sizes, and that more than a third of the clusters had a write ratio above 30%. - Expiry retires entries on a schedule. An expired entry must never be returned, so the node checks the time to live on every read (lazy expiry). That is exact and cheap for entries that are read, but entries nobody reads again (sessions of users who left, one-off results) keep their memory forever. So nodes also sweep. Redis's documentation describes a sampling sweep: ten times a second, test 20 random keys that have a time to live, delete the expired ones and go again if more than a quarter were expired (real versions also cap the CPU time spent and were reworked in Redis 6.0, so treat the loop below as the textbook version). The alternative groups entries by the second in which they expire, like a timing wheel, and drops a whole group when its second ends: exact and O(1) per write, for some bookkeeping memory.
C# · 100,000 entries are written at time 0 with a time to live of 30 to 90 seconds, and…
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
// 100,000 entries are written at time 0 with a time to live of 30 to 90 seconds, and nobody reads them again
// (think of the sessions of users who have left). Time moves in steps of 100 ms. How many expired entries still
// occupy memory, under three ways of removing them?
var expiryRandom = new Random(3);
const int entries = 100_000, lastStep = 1_500;
var expiresAtStep = Enumerable.Range(0, entries).Select(_ => expiryRandom.Next(300, 901)).ToArray();
var expiredBy = new int[lastStep + 1]; // expiredBy[s]: entries past their time to live at step s
foreach (int at in expiresAtStep) expiredBy[at]++;
for (int s = 1; s <= lastStep; s++) expiredBy[s] += expiredBy[s - 1];
// 1. Lazy expiry only: an entry is checked when someone asks for it. Nobody does, so nothing is ever freed.
int lazyDeadAtEnd = expiredBy[lastStep];
// 2. A sampling sweep, as Redis's documentation describes it: test 20 random entries that have a time to live, delete the
// expired ones, and go again if more than a quarter were expired. It runs ten times a second.
var inTable = Enumerable.Range(0, entries).ToList();
int sweepRemoved = 0, sweepPeakDead = 0;
for (int step = 1; step <= lastStep; step++)
{
while (inTable.Count > 0)
{
int tested = Math.Min(20, inTable.Count), expired = 0;
for (int i = 0; i < tested; i++)
{
int pick = expiryRandom.Next(inTable.Count);
if (expiresAtStep[inTable[pick]] > step) continue;
inTable[pick] = inTable[inTable.Count - 1]; inTable.RemoveAt(inTable.Count - 1);
expired++; sweepRemoved++;
}
if (expired * 4 <= tested) break;
}
sweepPeakDead = Math.Max(sweepPeakDead, expiredBy[step] - sweepRemoved);
}
// 3. Expiry buckets: entries are grouped by the second in which they expire, and a whole group is dropped when its second ends.
var perSecond = new int[lastStep / 10 + 1];
foreach (int at in expiresAtStep) perSecond[at / 10]++;
int bucketRemoved = 0, bucketPeakDead = 0;
for (int step = 1; step <= lastStep; step++)
{
if (step % 10 == 0) bucketRemoved += perSecond[step / 10 - 1];
bucketPeakDead = Math.Max(bucketPeakDead, expiredBy[step] - bucketRemoved);
}
Debug.Assert(lazyDeadAtEnd == entries);
Debug.Assert(sweepPeakDead > 10_000 && sweepPeakDead < 60_000 && sweepRemoved == entries);
Debug.Assert(bucketPeakDead < 3_000);With lazy expiry alone, all 100,000 expired entries were still in memory at the end. The sampling sweep removed every one eventually, but it fell behind while they expired at about 1,700 a second: at its worst 41,369 entries (41%) were dead but still resident, which is memory the node must have spare. Expiry buckets never held more than 1,772 (1.8%). Two rules follow. Add jitter (say plus or minus 10%) to every time to live so a batch fill does not expire as one wave. And size memory for dead entries, because they are reclaimed late.
Placement answers one question: given a key, which node? The answer must be computable by everyone who needs it, spread keys and load evenly, and, for a cache, change as little as possible when the set of nodes changes, because every key that moves is a key missing from its new home. Three schemes:
hash(key) mod N. Perfectly even, and wrong for a cache that ever changes size: going from N to N+1 nodes moves N/(N+1) of the keys.- A hash ring (consistent hashing). Each node owns many points on a ring (100 to 200 is typical, called virtual nodes) and a key belongs to the first point at or after its hash. A new node takes over only the stretches just before its own points, about 1/(N+1) of the keys, and a dead node's keys spread over its successors. The mechanism and the lab are in replication and sharding. Variants exist: rendezvous hashing, jump consistent hash (fast and exactly even, but buckets must be numbered 0 to N-1, so it suits storage better than caches that lose arbitrary nodes) and consistent hashing with bounded loads, which caps a node's load by pushing overflow to the next node.
- Hash slots. Redis Cluster fixes 16,384 slots. A key's slot is the CRC16 of the key modulo 16,384, and a table maps each slot to a node. Resharding moves slots one at a time, explicitly, which gives exact balance and operator control. Keys containing
{tag}hash only the tag, so related keys land in one slot and multi-key commands work. The table is small enough to gossip and to cache in every client.
C# · Which node holds a key? Three answers, so that the cost of changing the number of nodes…
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// Which node holds a key? Three answers, so that the cost of changing the number of nodes can be compared.
public interface IRouter { int NodeFor(string key); }
public static class Hash
{
// FNV-1a, then a bit-mixing step so that keys that differ in one character end up far apart.
public static uint Of(string text)
{
uint h = 2166136261;
foreach (char c in text) { h ^= c; h *= 16777619; }
h ^= h >> 16; h *= 0x85ebca6b; h ^= h >> 13; h *= 0xc2b2ae35; h ^= h >> 16;
return h;
}
}
// hash(key) mod N. Fine until the number of nodes changes.
public sealed class ModuloRouter : IRouter
{
private readonly int nodes;
public ModuloRouter(int nodes) { this.nodes = nodes; }
public int NodeFor(string key) => (int)(Hash.Of(key) % (uint)nodes);
}
// A hash ring: each node owns many points on it, and a key belongs to the first point at or after its own hash.
public sealed class RingRouter : IRouter
{
private readonly uint[] points;
private readonly int[] owners;
public RingRouter(int nodes, int pointsPerNode = 150)
{
var all = new List<(uint Point, int Node)>();
for (int n = 0; n < nodes; n++)
for (int p = 0; p < pointsPerNode; p++) all.Add((Hash.Of("node-" + n + "#" + p), n));
all.Sort((a, b) => a.Point.CompareTo(b.Point));
points = all.Select(a => a.Point).ToArray();
owners = all.Select(a => a.Node).ToArray();
}
public int NodeFor(string key)
{
int i = Array.BinarySearch(points, Hash.Of(key));
if (i < 0) i = ~i;
return owners[i == points.Length ? 0 : i];
}
}
// Redis Cluster's scheme: 16,384 fixed slots, a table from slot to node, and keys hashed to slots with CRC16.
public sealed class SlotRouter : IRouter
{
public const int Slots = 16384;
public readonly int[] Owner = new int[Slots];
public int Nodes { get; private set; }
public SlotRouter(int nodes)
{
Nodes = nodes;
for (int s = 0; s < Slots; s++) Owner[s] = (int)((long)s * nodes / Slots); // a fresh cluster: contiguous ranges
}
public int NodeFor(string key) => Owner[SlotOf(key)];
// If the key contains {tag}, only the tag is hashed, so related keys can be placed on one node.
public static int SlotOf(string key)
{
int open = key.IndexOf('{');
if (open >= 0)
{
int close = key.IndexOf('}', open + 1);
if (close > open + 1) key = key.Substring(open + 1, close - open - 1);
}
return Crc16(Encoding.UTF8.GetBytes(key)) % Slots;
}
public static int Crc16(byte[] data) // the XMODEM variant: polynomial 0x1021, start at 0
{
int crc = 0;
foreach (byte b in data)
{
crc ^= b << 8;
for (int bit = 0; bit < 8; bit++) crc = (crc & 0x8000) != 0 ? ((crc << 1) ^ 0x1021) & 0xFFFF : (crc << 1) & 0xFFFF;
}
return crc;
}
// A new node takes slots from the nodes that hold more than their new fair share, until it has a fair share itself.
public int AddNode()
{
int added = Nodes++;
var counts = new int[Nodes];
foreach (int owner in Owner) counts[owner]++;
int fairShare = Slots / Nodes, moved = 0;
for (int slot = 0; slot < Slots && moved < fairShare; slot++)
{
int donor = Owner[slot];
if (counts[donor] > fairShare) { Owner[slot] = added; counts[donor]--; counts[added]++; moved++; }
}
return moved;
}
}The experiment uses these three routers. A node is an LRU set of keys, and the workload is a Zipf stream: a few keys requested very often and a long tail requested rarely.
C# · A node, as far as the experiment cares: a fixed-size set of keys with…
using System;
using System.Collections.Generic;
// A node, as far as the experiment cares: a fixed-size set of keys with least-recently-used eviction.
public sealed class LruSet
{
private readonly int capacity;
private readonly Dictionary<int, LinkedListNode<int>> map = new Dictionary<int, LinkedListNode<int>>();
private readonly LinkedList<int> recent = new LinkedList<int>(); // most recent first
public LruSet(int capacity) { this.capacity = capacity; }
// True on a hit. A miss fills the key (the application read the database), evicting the least recent key if full.
public bool Access(int key)
{
if (map.TryGetValue(key, out var node)) { recent.Remove(node); recent.AddFirst(node); return true; }
if (map.Count >= capacity) { map.Remove(recent.Last.Value); recent.RemoveLast(); }
map[key] = recent.AddFirst(key);
return false;
}
}
// The cluster: one cache per node, and a table that says which node owns each key.
public sealed class CacheCluster
{
private readonly List<LruSet> nodes = new List<LruSet>();
private readonly int capacityPerNode;
private int[] nodeOf;
public CacheCluster(int nodeCount, int capacityPerNode, int[] nodeOf)
{
this.capacityPerNode = capacityPerNode;
this.nodeOf = nodeOf;
for (int i = 0; i < nodeCount; i++) nodes.Add(new LruSet(capacityPerNode));
}
// The cluster grows by one empty node, and keys are now routed by the new table.
public void AddNode(int[] newNodeOf) { nodes.Add(new LruSet(capacityPerNode)); nodeOf = newNodeOf; }
public bool Get(int key) => nodes[nodeOf[key]].Access(key);
}
// Key popularity follows a Zipf law: key number r (from 0) is requested in proportion to 1 / (r + 1)^exponent.
public sealed class Zipf
{
private readonly double[] cumulative;
private readonly Random random;
public Zipf(int keys, double exponent, int seed)
{
random = new Random(seed);
cumulative = Probabilities(keys, exponent);
for (int r = 1; r < keys; r++) cumulative[r] += cumulative[r - 1];
}
public int Next() { int i = Array.BinarySearch(cumulative, random.NextDouble()); return i < 0 ? ~i : i; }
public static double[] Probabilities(int keys, double exponent)
{
var p = new double[keys];
double sum = 0;
for (int r = 0; r < keys; r++) sum += p[r] = 1.0 / Math.Pow(r + 1, exponent);
for (int r = 0; r < keys; r++) p[r] /= sum;
return p;
}
}C# · The slot function against values reported for Redis Cluster, and hash tags putting…
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
// The slot function against values reported for Redis Cluster, and hash tags putting related keys together.
Debug.Assert(SlotRouter.Crc16(Encoding.ASCII.GetBytes("123456789")) == 0x31C3); // the standard check value for CRC16/XMODEM
Debug.Assert(SlotRouter.SlotOf("foo") == 12182 && SlotRouter.SlotOf("hello") == 866);
Debug.Assert(SlotRouter.SlotOf("{user1000}.following") == SlotRouter.SlotOf("{user1000}.followers"));
// A cluster of 10 nodes holds 20% of 100,000 keys, and then an 11th node is added.
const int keyCount = 100_000, capacityPerNode = 2_000, startNodes = 10;
string[] names = Enumerable.Range(0, keyCount).Select(k => "key:" + k).ToArray();
int[] Table(IRouter router) => names.Select(router.NodeFor).ToArray();
var modulo = (Before: Table(new ModuloRouter(startNodes)), After: Table(new ModuloRouter(startNodes + 1)));
var ring = (Before: Table(new RingRouter(startNodes)), After: Table(new RingRouter(startNodes + 1)));
var slotRouter = new SlotRouter(startNodes);
var slotsBefore = Table(slotRouter);
int slotsMoved = slotRouter.AddNode();
var slotted = (Before: slotsBefore, After: Table(slotRouter));
// How many keys change node?
double Moved((int[] Before, int[] After) table) => Enumerable.Range(0, keyCount).Count(k => table.Before[k] != table.After[k]) / (double)keyCount;
Debug.Assert(Moved(modulo) > 0.85 && Moved(ring) < 0.15 && Math.Abs(Moved(slotted) - 1.0 / 11) < 0.01);
Debug.Assert(slotsMoved == 1_489);
// The same request stream (Zipf, exponent 0.99) goes to each cluster: warm up, then add a node and watch the hit ratio.
(double Steady, double[] After) HitRatios((int[] Before, int[] After) table)
{
var cluster = new CacheCluster(startNodes, capacityPerNode, table.Before);
var requests = new Zipf(keyCount, 0.99, 7);
for (int i = 0; i < 300_000; i++) cluster.Get(requests.Next()); // fill the caches
int steadyHits = 0;
for (int i = 0; i < 100_000; i++) if (cluster.Get(requests.Next())) steadyHits++;
cluster.AddNode(table.After);
var windows = new double[30]; // the next 30,000 requests, 1,000 at a time
for (int w = 0; w < windows.Length; w++)
{
int hits = 0;
for (int i = 0; i < 1_000; i++) if (cluster.Get(requests.Next())) hits++;
windows[w] = hits / 1_000.0;
}
return (steadyHits / 100_000.0, windows);
}
var moduloRun = HitRatios(modulo);
var ringRun = HitRatios(ring);
var slotRun = HitRatios(slotted);
double Reads(double[] windows) => windows.Take(10).Sum(h => 1_000 * (1 - h)); // database reads in the first 10,000 requests after the change
Debug.Assert(moduloRun.After[0] < 0.5 && ringRun.After[0] > moduloRun.Steady - 0.1);
Debug.Assert(moduloRun.After[0] < ringRun.After[0] - 0.25);
Debug.Assert(Reads(moduloRun.After) > 1.8 * 10_000 * (1 - moduloRun.Steady) && Reads(ringRun.After) < 1.2 * 10_000 * (1 - ringRun.Steady));
Debug.Assert(ringRun.After[29] > ringRun.Steady - 0.03 && slotRun.After[29] > slotRun.Steady - 0.03 && moduloRun.After[29] > moduloRun.Steady - 0.05);The first assertions check the slot function against values Redis reports: the CRC16 of "123456789" is 0x31C3, and the key foo lands in slot 12182 (hello in 866). Then a tenth node becomes an eleventh. The cluster holds 20% of 100,000 keys, 2,000 entries on each node, with an 80% hit ratio before the change.
| Measure | Modulo | Ring | Slots |
|---|---|---|---|
| Keys that change node | 91.0% | 8.9% | 9.1% (1,489 of 16,384 slots) |
| Hit ratio before | 80.3% | 80.3% | 80.3% |
| Requests 1 to 1,000 after | 40.8% | 75.6% | 75.7% |
| Requests 1,001 to 2,000 | 53.2% | 77.4% | 76.7% |
| Requests 4,001 to 5,000 | 59.9% | 77.9% | 79.1% |
| Requests 9,001 to 10,000 | 66.4% | 80.1% | 80.5% |
| Requests 29,001 to 30,000 | 75.5% | 82.3% | 82.4% |
| Database reads in the first 10,000 requests | 4,176 | 2,179 | 2,177 |
In steady state 10,000 requests cause 1,969 database reads. Under modulo hashing the first thousand requests after the change missed 59% of the time instead of 20%, and the database saw twice its normal load. Thirty thousand requests later the cache had still not recovered, because 91% of the keys had to be fetched again and the old copies (now on the wrong node and never asked for) held memory until they were evicted. With the ring or slots the cluster lost only the 9% that moved, and ended higher than before because the extra node added memory. How long "30,000 requests" lasts depends on the request rate and the working set: seconds at a million requests a second, far longer for a cache with terabytes of hot data.
Three practical points follow. Add capacity gradually and warm it: move slots in small steps, let the new node read from the old owner for a while, or replay hot keys into it. Facebook's paper describes warming a new, empty cluster by reading from a warm one instead of from the database. Old copies are a hazard, not only waste. A key's old copy stays on its former node until it is evicted or expires. If the key moves back (a node flaps out and in), the old copy is served again, possibly after the value changed or was deleted. Cap the time to live, or flush a node that rejoins. Choose by operations, not elegance. A ring needs no coordination but balances statistically; slots balance exactly and give explicit control at the price of a table to distribute. Both move about 1/N of the keys. Modulo is acceptable only for a fleet that never changes size.
A cache node will die, restart or be replaced during a deploy. The data loss is acceptable. The consequence is the problem: that node's keys now miss, and every miss lands on the database.
8 nodes, 500,000 reads/s, hit ratio 99%: the database sees 5,000/s
one node dies: its 12.5% of the reads, 62,500/s, miss until refilled
database load: 5,000 x 7/8 + 62,500 = about 67,000/s, 13x normal
at a 95% hit ratio the same loss is 3.4xThe higher the hit ratio, the worse this gets: the database is sized for the misses, and a cache that works too well makes the database depend on it. Defences, roughly in order of use:
- Spread the dead node's keys. With many points per node on a ring (or slots reassigned across all survivors) its keys go to every remaining node in small amounts. If they all landed on one neighbour, that node would take double load and might fall over in turn.
- Replicas. A primary with an asynchronous replica loses almost nothing when the primary dies, except its most recent writes. The price is double the memory, so many fleets replicate only the tiers that cannot survive a cold start.
- A gutter pool. Facebook's paper describes a small pool (about 1% of the servers in a cluster) that takes over for failed servers, with short expirations, so the database sees refills at a bounded rate and stale entries age out quickly instead of needing invalidations.
- Protect the database. Cap concurrent reads per key and in total, and shed load or serve stale data when the cap is reached. A cache failure should degrade the product, not take down the source of truth.
- Warm the replacement. Preload hot keys from a replica or the old owner, or shift traffic to the new node gradually.
Replication has a hazard specific to caches. Redis replicates asynchronously, so a primary can acknowledge a write and fail before the replica receives it. For a cache a lost set is harmless, but a lost delete is not: if an invalidation reached only the old primary, the promoted replica still holds the old value and serves it until the time to live ends. Invalidation must therefore be repeatable (idempotent deletes from a durable stream), and the time to live is the safety net, not an afterthought.
With several regions, each runs its own cache fleet beside its own database replica. A write in one region must delete the key in every region. Facebook's design reads the database's commit log and broadcasts the deletes, and marks a key for a short time after a write so the writer does not read a stale copy from a lagging replica and cache it.
Three problems appear at scale whatever the topology. The cache consistency, stampedes and hot keys lesson takes each apart with a simulation. In an answer, name the problem and its defence:
| Problem | What goes wrong | The defence |
|---|---|---|
| A stale value outlives the data | A slow reader fills the old row after the writer's delete: 1 in 10 interleavings of plain cache-aside | Delete after the write, a lease or version check on the fill, invalidation from the change log, a time to live as the guarantee |
| A popular key expires | About 200 identical database reads inside 100 ms | A lease or per-server coalescing, serving stale while one request refreshes, early refresh, jittered times to live |
| One key is hotter than a node | The busiest node carries several times its fair share, and more nodes do not help | A near cache in each application server, copies of the hottest keys under several names, heavy-hitter detection |
- Measure per namespace. Hit ratio (an average hides a cold keyspace), evictions (high evictions with a low hit ratio mean too little memory or a scan), expirations, memory and fragmentation, p50, p99 and p99.9 latency per node, connections and bandwidth, replication lag, and the busiest keys.
- Clients decide how a cache problem feels. Use tight timeouts (a cache that takes 50 ms is worse than a miss), retry only with a budget and jitter, and trip a circuit breaker when a node is slow so requests skip it. Fail open to the database, but through a limit on concurrent reads, so a cache outage cannot become a database outage.
- Design keys and values. Namespaced, versioned keys (
user:v3:42) turn a schema change into a new keyspace, ideally rolled out gradually, since it starts cold. Keep keys short and free of secrets and personal data. Store compact encodings, cap value sizes, never cache errors, and cache "not found" briefly so lookups of missing keys do not reach the database every time. - Isolate tenants and workloads. One shared eviction policy is unfair by default: whoever writes fastest owns the memory. Use per-tenant quotas or separate pools by access pattern, as Facebook does, and separate clusters for the loud or critical.
- Secure it and roll it out slowly. Keep caches off public networks and require authentication and TLS where the product supports it (open Redis and Memcached servers have been exploited for data theft, code execution and, with UDP enabled, denial-of-service amplification). Restart one node at a time, with replicas promoted or traffic shifted gradually, and watch the hit ratio and the database load while it happens.
| Case | What goes wrong | Response |
|---|---|---|
| A node dies | Its share of reads misses; at a 99% hit ratio the database sees about 13x its load | Spread its keys over all survivors, replicas or a gutter pool, a cap on database reads, a warmed replacement |
| A node is added or removed under modulo hashing | About 91% of keys move and the hit ratio collapses | A ring or slots, one node at a time, warming |
| An old copy returns when a node rejoins | A deleted or changed value is served again | Flush a rejoining node, a capped time to live |
| Two clients have different node lists | One key on two nodes, and a delete reaches only one | One authority for the map: a proxy or a redirecting cluster |
| Expired entries pile up | A sweep that samples falls behind and memory fills with dead entries | Jitter, expiry buckets, memory headroom for dead entries |
| A big value or a slow command | Everything queued behind it on a single-threaded node waits | Value limits, O(1) commands, SCAN rather than KEYS, split big values |
| The wrong eviction policy | Writes rejected at the limit, or hot data pushed out by a scan | A cache policy, admission such as TinyLFU, pools per workload |
| A slow cache, not a dead one | Client threads pile up behind timeouts | Short timeouts, a circuit breaker, bulkheads, fail open through a limit |
| A restart or a key-format change | Every key misses at once | Rolling restarts, replicas, versioned keys rolled out gradually |
Interviewer follow-upL5Why not hash(key) mod N, and what do you use instead?How to answer
Because changing N moves almost every key: from 10 to 11 nodes 91% of the keys changed node in the simulation, the hit ratio fell from 80% to 41% and the database read twice its normal load for the first 10,000 requests. Use a hash ring with many points per node, or fixed hash slots with a slot-to-node table. Both move about 1/(N+1) of the keys when a node is added.
Interviewer follow-upL6A cache node dies and the database falls over. Walk me through it.How to answer
At a 99% hit ratio the database is sized for 1% of reads. Losing one of eight nodes sends 12.5% of reads to it, about 13 times the load. Queries slow down, request threads wait, retries add load, and the database cannot recover because it is also refilling the cache. Prevent it by spreading the dead node's keys over all survivors, running replicas or a gutter pool, capping concurrent database reads and shedding load, coalescing refills, using timeouts and retry budgets, and planning database capacity as if the cache could be cold.
Interviewer follow-upL6How do you add a node to a live cluster without hurting the hit ratio?How to answer
Use a ring or slots so only about 1/(N+1) of the keys move, add one node at a time off peak, and warm it: move slots in small steps, let it read from the old owner, or replay hot keys into it. Keep every client's map in step, because two maps place one key on two nodes. Watch the hit ratio and database load during the move, and flush a node that rejoins so old copies cannot come back.
Interviewer follow-upL6How does Redis Cluster route a key and reshard?How to answer
A key's slot is CRC16(key) modulo 16,384 (only the {tag} if there is one) and each primary owns a set of slots. A client sends a command to any node, a node that does not own the slot answers MOVED with the owner, and the client updates its slot map. Resharding moves one slot at a time with its keys, and for a key already moved the old owner answers ASK, so the client asks the new owner once without updating its map. Multi-key commands must stay within one slot, which hash tags arrange.
Interviewer follow-upL6Redis or Memcached?How to answer
Memcached is a multi-threaded cache of opaque values with a slab allocator and a small set of operations, which is hard to misuse as anything else. Redis offers data structures (hashes, sorted sets, counters), replication, optional persistence and scripting, but executes commands on one thread, so you design for O(1) commands and small values. Choose Memcached for simple, high-throughput caching of blobs and Redis when you need atomic structures or replication. Both scale out with the placement schemes above, and both change between versions, so check the current documentation.
Interviewer follow-upL7When is a cache the wrong answer?How to answer
When reuse is low (a scan-heavy or uniform access pattern gives a low hit ratio, and the cache only adds latency and cost), when reads must see the writer's changes at once, when writes dominate (every write invalidates, so entries churn), and when the database cannot survive without it. In that last case the cache is part of the database's capacity, and its failure is an outage: either grow the database or limit what the cache is allowed to shield.
Interviewer follow-upL7How do you run one shared cache for many teams?How to answer
Namespace every key, give each tenant a memory quota or a separate pool by access pattern (so a churn-heavy workload cannot evict a stable one), track hit ratio and evictions per tenant, rate-limit at the proxy, and give loud or critical tenants their own clusters. A single shared eviction policy rewards whoever writes fastest.
- Clarify: what is cached, how stale it may be, cache or store, and what happens when it is down.
- Estimate: hit ratio into database load, memory and operations into a node count, and connections.
- Contract:
get,setwith a time to live,delete; a miss is always allowed, and nothing is durable. - Draw it: clients or a proxy, nodes with replicas, a cluster map, and the invalidation stream from the database.
- Placement: a ring or hash slots, and what happens to the hit ratio when a node joins or dies.
- One node: memory, eviction with an admission policy, and expiry beyond the lazy check.
- Failure: replicas, a gutter pool, protecting the database, warming a cold node.
- Consistency and hot spots: delete after the write with a lease or versions, a time to live as the guarantee, stampede defences and a near cache.
A distributed cache is a sharded in-memory hash table in front of a database. Size it from the hit ratio, memory and operations, and remember that the database must survive a cold node: at a 99% hit ratio, losing one of eight nodes is 13 times the load. Place keys with a ring or hash slots, so a new node moves about a ninth of the keys instead of 91%, and the database does not read twice its normal load for the first 10,000 requests. A node must evict with an admission policy and retire expired entries with more than the lazy check, and its memory plan must include the dead entries a sweep reclaims late. Plan for failure with spread keys, replicas or a gutter pool, a cap on database reads and a warmed replacement. Keep the cache consistent with deletes after writes and a time to live as the guarantee, and defend against stampedes and hot keys with leases, coalescing and a near cache. Measure per namespace, and roll out one node at a time.
Try answering out loud before you reveal each answer.
QuestionYou add an 11th node to a 10-node cache that uses hash(key) mod N and the database load doubles. Why, and what do you change?Reveal answer
Going from 10 to 11 changes the node for 10/11, about 91%, of the keys, so most requests miss until the hot keys are refilled, and the old copies sit unused on the wrong nodes. Use consistent hashing with many points per node, or hash slots, so only about 1/11 of the keys move, and add the node gradually or warm it.
QuestionEight cache nodes serve 500,000 reads a second at a 99% hit ratio, and one node dies. What does the database see, and what do you do about it?Reveal answer
The dead node owned 12.5% of the reads, 62,500 a second, and they all miss until refilled, so the database goes from 5,000 to about 67,000 reads a second, 13 times its load. Spread the node's keys over all survivors, run replicas or a gutter pool, cap concurrent database reads and shed load, coalesce refills, and warm the replacement.
QuestionAn expired entry is never returned, yet a node's memory fills with expired entries. How?Reveal answer
Lazy expiry checks the time to live only when an entry is read, so entries nobody reads again keep their memory. A background sweep that samples keys reclaims them only as fast as it samples, and can fall behind when many expire together (41% of the table in the simulation). Spread expiry with jitter, group entries by expiry time so a whole group is dropped, and keep memory headroom for dead entries.
QuestionTwo application servers have different node lists during a rollout. What goes wrong for invalidation?Reveal answer
The same key is cached on two different nodes, one for each server's view. A delete issued through one server removes only one copy, and the other server keeps reading the stale copy until it expires. Give placement one authority, a proxy or a cluster that redirects, or roll out node-list changes so all clients agree before keys move.
- Rajesh Nishtala and others, Scaling Memcache at Facebook (opens in a new tab), NSDI 2013: leases, gutter pools, regional pools, invalidation through the commit log and cold cluster warmup.
- Redis documentation, Redis Cluster specification (opens in a new tab): hash slots, CRC16, hash tags, redirections and failover. Also the page on key eviction (opens in a new tab) and the page on the EXPIRE command (how expiry works).
- Gil Einziger, Roy Friedman and Ben Manes, TinyLFU: A Highly Efficient Cache Admission Policy (opens in a new tab), ACM Transactions on Storage, 2017: frequency-based admission and W-TinyLFU.
- Juncheng Yang, Yao Yue and K. V. Rashmi, A large scale analysis of hundreds of in-memory cache clusters at Twitter (opens in a new tab), OSDI 2020: write ratios, time to live, popularity skew and eviction in production caches.
- Twitter Engineering, Improving key expiration in Redis (opens in a new tab), 2019: why expired keys can stay in memory and how the sweep was improved.
- Vahab Mirrokni, Mikkel Thorup and Morteza Zadimoghaddam, Consistent Hashing with Bounded Loads (opens in a new tab), SODA 2018, and John Lamping and Eric Veach, A Fast, Minimal Memory, Consistent Hash Algorithm (opens in a new tab), 2014 (jump consistent hash).
- The Memcached manual page (opens in a new tab): slab growth factor, item size limit and threading options.