The Problem#
A distributed cache keeps key-value pairs in the memory of many machines, so that applications can read hot data in about a millisecond instead of querying a database in 5-50 ms. Clients call get, set and delete, and can give each entry a time to live (TTL). When memory fills up, the cache throws out the entries least likely to be needed again, by default the least recently used ones. Memcached and Redis are the best-known examples. Many large companies run their own layers on top of them, such as Facebook's memcache tier and Netflix's EVCache.
In this case study we design the cache itself, not just its use. We cover:
- What one node keeps in memory and how it answers in microseconds.
- How keys are spread over dozens of nodes so that adding a node does not reshuffle everything.
- How nodes find each other and agree on who owns what.
- How the cluster survives a node crash.
- What to do when one key gets a million reads per second.
The interview tests infrastructure thinking. The single-node data structure is a coding question, the partitioning is a distributed-systems question, and the failure handling is a staff-level question. It is one of the few designs where you are expected to go from a doubly linked list all the way up to a gossip protocol.
The concepts are introduced in Distributed Caching with Redis and Memcached and Consistent Hashing. This page turns them into one complete design and explains every decision.
Clarifying Questions#
| Question | Assumed answer | Why it matters |
|---|---|---|
| Is this a pure cache, or must data survive restarts? | A pure cache. The source of truth is a database, and losing cached data costs only extra database load. | Durability would need disk persistence and synchronous replication. Without it we can use asynchronous replication and simple failover. |
| What operations are needed? | get, set with an optional TTL, delete, plus batch mget and compare-and-set. No queries or transactions. | A small key-value API keeps every operation to a single key, so it can be served by one node in O(1). |
| How much data and traffic? | 1 TB of cached data, 100k operations per second at launch, and growth to 1M per second planned. About 90% reads. | Memory, not CPU, will decide the node count at launch. Throughput becomes the constraint later. |
| What latency? | p99 under 1 ms on the server and under 2-3 ms from the client in the same zone. A hard ceiling of 10 ms. | This rules out disk on the read path and puts the emphasis on avoiding queueing and slow commands. |
| Value sizes? | Typically 100 B to 10 KB, with an average around 1 KB and a 1 MB maximum per value. | Overhead per entry matters at a billion entries, and very large values cause hot spots in network traffic. |
| Which eviction policy? | LRU by default, with LFU available per pool. TTL expiry is independent of eviction. | This decides the node's data structure: a hash map plus a recency list or a frequency structure. |
| Consistency expectations? | Eventual. A read may be briefly stale after a write or a failover, and stale data is bounded by TTL. | It allows asynchronous replication and reading from replicas, and keeps failover simple. |
| Availability target? | 99.99% for reads. A node failure must not make its keys unavailable for more than a few seconds. | We need replicas and automatic failover, not just "re-fetch from the database". |
| Is there a hot-key problem? | Yes. Viral items and celebrity profiles can get 100 times the normal traffic. | Even distribution of keys does not give even distribution of traffic, so we need explicit hot-key handling. |
| Multi-tenant? | Several teams share the platform, using separate pools with quotas. | This brings in isolation, per-tenant memory limits and noisy-neighbour protection. |
| Single region or multi-region? | Single region with three availability zones. Cross-region is an extension. | It decides whether replicas are spread across zones and how invalidations cross regions. |
Requirements#
Functional#
- Set, get and delete key-value pairs, including batch reads and conditional writes (set-if-absent, compare-and-set by version).
- Expire entries after a TTL given per key, and let clients read and change the remaining TTL.
- Evict entries when memory is full, by an LRU policy (LFU optional), without blocking requests.
- Grow and shrink the cluster by adding or removing nodes while serving traffic, without remapping most keys.
Out of scope: persistence across restarts, strong consistency, transactions across keys, rich data types such as sorted sets and streams, and per-tenant cache sizing UIs. We mention where each would plug in.
Non-Functional#
- Low latency. p99 under 1 ms on the server, about 1-2 ms end to end in the same zone. The whole point of a cache is to be much faster than the database behind it. A cache that is slow at the tail makes every caller slow too.
- High availability. 99.99% for reads (about 4.4 minutes a month). A single node failure is invisible to clients apart from a short blip, typically under 10 seconds.
- Scalability. 1 TB growing to 10 TB, and 100k growing to 1M operations per second, by adding nodes. Adding a node moves only about 1/N of the keys.
- Eventual consistency. Replicas and readers may lag by milliseconds. After a failover a few recent writes may be lost. Every stale entry is bounded by its TTL.
- Even load. No node should carry far more keys or traffic than its peers. That covers both structural balance (how keys spread) and workload balance (how requests spread).
- Operability. Rolling upgrades, live resharding, per-pool metrics such as hit ratio, evictions, memory and latency, and graceful behaviour while a cache is warming up.
Which matter most? Latency and availability, with consistency relaxed on purpose. A cache that is perfectly consistent but adds a replication round trip to every write, or that refuses reads during failover, gives up the reason it exists. The database is the source of truth. The cache only has to be fast and usually right, with TTLs limiting how wrong it can be. In CAP Theorem and PACELC terms this is an AP/EL system.
Capacity Estimation#
We only work out the numbers that change the design (see Back-of-the-Envelope Estimation).
Entries. 1 TB of values at an average of 1 KB is about 1 billion entries. Keys average around 50 bytes.
Overhead per entry. Each entry needs more than its key and value:
- A hash-table slot: a pointer, 8 bytes.
- An entry header: key length, value length, flags, TTL, a version for compare-and-set, and the hash-chain pointer, about 32-48 bytes.
- Two LRU list pointers: 16 bytes.
- Allocator rounding: anything from 0 to 25% of the item size, depending on the allocator.
A realistic total is 60-100 bytes of overhead per entry on top of the key and value. Redis keys stored as plain strings cost roughly this much, and Memcached items are of a similar order. For 1 billion entries that is 60-100 GB of overhead, close to 10% of the data, so the cluster needs about 1.1-1.2 TB of RAM for data plus metadata. For small values the picture changes. With 100-byte values, overhead can be as large as the data itself, which is why compact encodings matter for workloads with many small items.
Memory per node. Assume hosts with 128 GB of RAM. We do not give all of it to cached data. The rest goes to:
- the OS and page cache,
- connection buffers (each client connection has input and output buffers),
- the replication backlog,
- fragmentation, which typically adds 10-20% on long-running nodes with mixed value sizes,
- the copy-on-write overhead of a background snapshot, if one is ever taken.
A safe setting is maxmemory ≈ 70-80 GB per node. 1.2 TB / 75 GB ≈ 16 primaries, and with one replica each, 32 nodes. At launch, memory decides the node count.
Throughput. One node of a Redis-style, single-threaded event loop handles about 100k-200k simple operations per second. Multi-threaded Memcached-style nodes handle several hundred thousand to over a million on many cores. 16 primaries at a conservative 100k each give 1.6M operations per second, which already covers the 1M growth target. If we read from replicas too, read capacity roughly doubles. So throughput is not the constraint at launch, memory is. That reverses at 10 times the traffic or with smaller values, which is why the design must scale both ways.
Network. 100k operations per second × about 1.1 KB is about 110 MB/s for the cluster. At 1M operations per second it is about 1.1 GB/s, or roughly 70 MB/s per primary. That is comfortable on 10-25 Gbit NICs. One hot key with a 100 KB value read 50k times a second is 5 GB/s on a single node, which is more than its NIC can send. Large hot values are a bandwidth problem before they are a CPU problem.
Replication. Writes are about 10% of operations: 10k-100k per second × 1.1 KB, which is 11-110 MB/s of replication stream in total, or a few MB/s per primary. A full resync of a 75 GB replica takes about a minute at 10 Gbit/s plus the snapshot time. That is why we prefer partial resync from a backlog, and why the backlog is sized for the length of outage we want to survive without a full copy.
Rebuild cost. If a node is lost with no replica, its 75 GB of entries, about 70M keys, must be re-fetched from the database as misses arrive. Suppose the node served 6% of 100k operations per second and the database handles 20k reads per second. The extra miss traffic is then manageable. If the node held the hot set for a busy service, it might not be. That is the case for replicas even in a "pure cache".
What the numbers imply:
- About 16 primaries plus replicas at launch, sized by memory, so partitioning is required from day one.
- About 60-100 B of overhead per entry, so node data structures must be compact.
- Hot large values exceed a NIC, so hot keys need replication or client-side caching, not just even sharding.
- The cost of resync and rebuild justifies replicas and partial resync, even for data that can be lost.
Core Entities#
- Entry: a key (up to 250 bytes), a value (up to 1 MB), an expiry timestamp, a version number for compare-and-set, and flags. It lives in exactly one partition, on that partition's primary and replicas.
- Node: a cache server process with a memory budget, a set of owned partitions, and a role (primary or replica) for each.
- Partition (slot or token range): a fixed slice of the key space that moves between nodes as a unit. Redis Cluster uses 16,384 hash slots, and consistent-hash rings use ranges of tokens.
- Cluster map: the authoritative mapping from partitions to the primary and replica nodes, stamped with a monotonically increasing epoch. Clients and nodes cache it and use the epoch to tell old maps from new ones.
- Client library: the smart client in each application. It hashes keys, picks nodes from the cluster map, pools connections, batches and pipelines requests, and handles redirects and retries.
- Pool or namespace: an isolated cache for a tenant or use case, with its own memory quota, eviction policy and TTL defaults.
API Design#
The data plane is a binary or text protocol over long-lived TCP connections, not REST, because per-request HTTP overhead would cost more than the operation itself. Here it is in shorthand:
GET key -> value, version | MISS
MGET key1 key2 ... keyN -> [value | MISS, ...] (client fans out by node)
SET key value [TTL sec] [NX | XX] -> OK | NOT_STORED (NX = only if absent, XX = only if present)
CAS key value expected_version [TTL] -> OK | CONFLICT | MISS (compare-and-set)
DELETE key -> DELETED | MISS
TTL key -> remaining seconds | NO_TTL | MISS
EXPIRE key seconds -> OK | MISS (set or change TTL)
TOUCH key -> OK | MISS (refresh recency without reading)
INCR key delta -> new integer value (atomic counter)
Redirect replies (server-side routing hints):
MOVED slot host:port the slot has a new owner; update the cluster map
ASK slot host:port the slot is migrating; try that node for this one request
Control plane (operators and automation):
CLUSTER MAP -> { epoch, slots: [ {range, primary, replicas} ] }
NODE JOIN host:port -> { assignedSlots }
NODE LEAVE host:port -> drain then remove
STATS -> { hitRatio, evictions, memory, opsPerSec, p99 }Some details matter. SET is idempotent and safe to retry. INCR and CAS are not, so a client must not retry them blindly after a timeout. NX gives a cheap "lock" or "first writer wins" primitive. CAS gives optimistic concurrency, so two writers cannot silently overwrite each other's updates. Memcached's gets/cas work the same way. Authentication uses TLS and per-pool credentials (ACLs). Pools are named, so the same key in two pools never collides.
High-Level Design#
We build up one requirement at a time. We start with a single in-memory node and add a component only when a requirement needs it.
1) Clients can set, get and delete key-value pairs#
Start with one node. A cache node is, at heart, a hash map in RAM: key to entry. get hashes the key, finds the bucket, compares keys and returns the value, in O(1) average time. set inserts or replaces. delete unlinks the entry and frees its memory. A single-threaded event loop, the Redis model, can serve 100k or more of these operations per second. Each one takes about a microsecond of CPU, and the network round trip of about 0.5 ms dominates what the client sees. A single node is a good start, but it fails our requirements three ways: 1 TB does not fit in one machine's RAM, one machine is a single point of failure, and its throughput ceiling is fixed.
Partition the key space across nodes. Each key must have exactly one home, which every client can compute on its own:
- Modulo hashing,
node = hash(key) mod N, is simple and spreads keys evenly. But when N changes, almost every key moves. Going from 10 to 11 nodes remaps about 10/11, roughly 91%, of keys. For a cache, a "move" means a miss, so every node's hit ratio drops at once and the database gets the whole read load. This is the classic way a resize turns into an outage. - Consistent hashing places nodes, and many virtual nodes per physical node, on a hash ring. A key belongs to the first node clockwise from the key's hash. Adding a node takes over only the ranges just before its virtual nodes, about 1/N of the keys, taken in small pieces from many existing nodes. Removing a node hands its ranges to its ring neighbours, again spread across many nodes because of the virtual nodes.
- Fixed hash slots (Redis Cluster): hash every key into one of 16,384 slots with
CRC16(key) mod 16384, then assign slots to nodes in a separate table. Resizing moves whole slots. Only the slots chosen for the new node move, and nothing else changes. It is consistent hashing with the ring replaced by an explicit table, which makes ownership easy to inspect and to move deliberately.
We use fixed slots with an explicit slot-to-node table: 16,384 slots, each owned by one primary with one or more replicas. Deep Dive 3 compares the options with their maths.
Routing. Something must turn a key into a node address. We use a smart client library:
- The client hashes the key to a slot.
- It looks up the slot's primary in its cached cluster map.
- It sends the command over a pooled connection.
This saves a network hop compared with a proxy tier. If the map is stale because a slot has moved, the node answers MOVED. The client updates its map and retries, so stale maps fix themselves. A proxy tier, in the style of mcrouter or twemproxy, is the alternative for languages without a good smart client, or where you want connection fan-in. Deep Dive 5 covers the choice.
2) Entries expire after their TTL#
Each entry stores an absolute expiry time in milliseconds, or "none". Expiry has to happen in two ways, because neither one is enough by itself:
- Lazy expiry on access. On every
get, ifnow ≥ expires_at, the node deletes the entry and returns a miss. This costs nothing extra and ensures a client never sees an expired value. But an expired key that is never read again would stay in memory forever. - Active expiry in the background. A periodic task frees those forgotten keys. Redis uses a sampling algorithm. In its classic form (newer versions tune the thresholds adaptively), several times a second, it takes a random sample of about 20 keys from those that have TTLs and deletes the expired ones. If more than about a quarter of the sample was expired, it repeats straight away, because there are probably many more. Each cycle has a CPU time budget, so expiry can never stall the event loop. This keeps memory used by expired keys low on average, without scanning a billion keys and without keeping a perfectly sorted expiry index.
The alternatives are a min-heap or a timing wheel keyed by expiry time (Deep Dive 2). They make expiry exact at the cost of memory and pointer upkeep per entry. Sampling is the practical default, because a cache only needs "expired keys are never served" to be exact. "Expired keys are freed quickly" can be approximate.
Replicas should not expire keys on their own clock. The primary performs expiry and replicates it as an explicit delete, so primary and replicas agree on what exists. A replica read still checks the TTL logically, so it never returns an expired value while the delete is in transit. This is the approach Redis takes.
3) Entries are evicted by LRU when memory is full#
When used memory reaches maxmemory, a set must first free space. Least recently used is the policy we were asked for. The classic structure that makes it O(1) is a hash map plus a doubly linked list:
- The hash map gives O(1) lookup from key to list node.
- The list keeps entries in recency order. The most recently used is at the head and the least recently used at the tail.
- On
get, move the entry to the head. Unlinking and relinking take O(1) with prev and next pointers. - On
setof a new key, insert at the head. While memory is over the limit, evict the tail and remove it from the map.
class LRUCache<V> {
private map = new Map<string, Node<V>>();
private head: Node<V> = { key: "", value: null as any, prev: null, next: null };
private tail: Node<V> = { key: "", value: null as any, prev: null, next: null };
constructor(private capacity: number) { this.head.next = this.tail; this.tail.prev = this.head; }
get(key: string): V | undefined {
const n = this.map.get(key);
if (!n) return undefined;
if (n.expiresAt && Date.now() >= n.expiresAt) { this.remove(n); return undefined; } // lazy expiry
this.unlink(n); this.pushFront(n); // mark most recent
return n.value;
}
set(key: string, value: V, ttlMs?: number): void {
const old = this.map.get(key);
if (old) this.remove(old);
const n: Node<V> = { key, value, prev: null, next: null, expiresAt: ttlMs ? Date.now() + ttlMs : undefined };
this.map.set(key, n); this.pushFront(n);
while (this.map.size > this.capacity) this.remove(this.tail.prev!); // evict LRU tail
}
delete(key: string): boolean { const n = this.map.get(key); if (n) this.remove(n); return !!n; }
private remove(n: Node<V>) { this.unlink(n); this.map.delete(n.key); }
private unlink(n: Node<V>) { n.prev!.next = n.next; n.next!.prev = n.prev; }
private pushFront(n: Node<V>) { n.next = this.head.next; n.prev = this.head; this.head.next!.prev = n; this.head.next = n; }
}
type Node<V> = { key: string; value: V; prev: Node<V> | null; next: Node<V> | null; expiresAt?: number };This sketch limits by entry count for clarity. A real node limits by bytes. It tracks each entry's allocated size and evicts until used memory falls below the limit. The sentinel head and tail nodes remove all the null-check edge cases from unlink and insert.
Two production refinements change this picture, and Deep Dive 1 explains them. First, exact LRU needs a list update on every read. With multiple threads that means a lock, and on very hot nodes that lock becomes the bottleneck. Redis avoids the list completely with approximate LRU: it stores a 24-bit access clock in each entry, and when it must evict, it samples a few keys and evicts the oldest of the sample. Memcached keeps lists, but splits them into segments (hot, warm, cold) and bumps items asynchronously. Second, plain LRU is not scan-resistant. One batch job that reads a million cold keys once each pushes the entire hot set out of the cache. Segmented LRU and LFU-based admission fix that (Deep Dive 7).
4) The cluster grows and shrinks while serving#
A node joins by announcing itself. An operator or an autoscaler then assigns it slots, which are taken a few at a time from the most loaded nodes. To move a slot:
- Mark the slot migrating on the source node and importing on the target node.
- Copy the slot's keys in batches, using
MIGRATEor an equivalent. - Meanwhile, a request for a key that has already moved gets
ASK, which means "try the target for this one request". Keys not yet moved are served by the source. - When the slot is empty on the source, flip ownership in the cluster map, bump the epoch, and let
MOVEDreplies update every client.
For a pure cache there is a simpler alternative: do not migrate. Flip ownership straight away and let the new owner fill from misses. That costs a miss burst on about 1/N of the keys, which is fine if the database can absorb it, and it avoids migration traffic entirely. Removing a node is the reverse: drain its slots to other nodes, then take it out of the map.
Who keeps the cluster map? We need agreement on "slot 4120 belongs to node 7, epoch 913". The two families are:
- A coordination service such as etcd or ZooKeeper that holds the map, with nodes and clients watching it. See ZooKeeper and etcd.
- Gossip among the cache nodes, with epochs to settle conflicts, as Redis Cluster does.
Deep Dive 6 compares them.
The full high-level design#
The request path, as seen from an application:
The control plane that keeps everyone agreeing on the slot map:
Each component in one line:
- Smart client. It hashes keys to slots, routes to primaries (or to replicas when that is allowed), pipelines and batches requests, applies timeouts and retry rules, and updates its map on
MOVED. - Optional L1 cache. A tiny in-process cache in each application for a few very hot keys, with TTLs of 1-5 seconds. It is the strongest defence against hot keys.
- Cache nodes. Each runs a hash map plus eviction metadata under a memory budget, with lazy and active expiry, serving its slots over an event loop.
- Replicas. Asynchronous copies of each primary in another zone. They take over on failover and can serve reads for stale-tolerant keys.
- Cluster manager. It plans resharding and node replacement, drives slot migration, and promotes replicas when a primary fails.
- Coordination or gossip. This is the source of truth for the slot map and its epoch. It notifies nodes and clients of changes and settles conflicts.
- Failure detector. It uses heartbeats, gossip or leases to decide when a node is dead rather than just slow. See Heartbeats, Failure Detection and Gossip.
- Database. The source of truth. Callers fill the cache on a miss (cache-aside). See Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind.
- Monitoring. It tracks hit ratio, evictions, memory, fragmentation, replication lag, p99 per node, and the top keys.
Key Flows#
Reading a key, with a miss and a refill#
- Routing is local and costs microseconds: one CRC16, one array lookup into the slot map, and one pooled connection. There is no proxy hop and no lookup service on the request path.
- The node's work is a hash lookup, a TTL check and a recency update, about a microsecond. Almost all of the ~0.5-1 ms the client sees is network time.
- On a miss the application reads the database and writes the value back with a TTL. This is cache-aside. The cache never calls the database itself, which keeps it simple and generic.
- A
setthat needs room evicts first, inline and in O(1) per evicted entry. Eviction is incremental, so onesetnever triggers a long pause. - If many clients miss on the same hot key at once, they all hit the database. That is a stampede, and Deep Dive 11 prevents it with leases or request coalescing.
A primary fails and its replica takes over#
- Detection must tell dead from slow. A single missed heartbeat proves nothing. Nodes mark a peer as suspect after a timeout, and as failed only when a majority of primaries agree. This stops one partitioned observer from triggering a failover.
- The replica asks for promotion with a new, higher epoch, and a majority must vote for it. The epoch is the fencing mechanism. If the old primary comes back, it sees a higher epoch for its slots, demotes itself to a replica and drops any writes it accepted while isolated.
- Clients find out through
MOVEDreplies or a watch on the map. Until then, their requests to the old primary time out, so the client's timeout and retry budget decide how visible the failover is. A typical figure is 5-15 seconds of errors on one shard's keys. - Replication was asynchronous, so writes acknowledged by the old primary but not yet replicated are lost. For a cache that only means a few extra misses, and it is why async replication is acceptable here.
Data Model#
There are two very different datasets. One is the cached entries, a billion of them, all in RAM and never in a database. The other is the small cluster metadata that says who owns what. The erDiagram describes the metadata, because that is the part with relationships and transactions. The entries are described as a memory layout below it.
Where the metadata lives. The metadata is tiny: tens of nodes and a few hundred slot ranges. It needs agreement more than throughput. Store it in a coordination service with linearizable writes and watches, such as etcd or ZooKeeper. Alternatively, it can be held by every node and kept consistent with epochs and gossip, as Redis Cluster does. It is not a job for a general relational or NoSQL database, because the access pattern is "everyone watches one small document" (see Choosing a Database: A Decision Guide). The entries are the cache's own in-memory store. Their "database choice" is the data structure in Deep Dive 1.
Entry layout on a node (approximate, in the style of Memcached and Redis):
- Hash table bucket. A pointer to the first entry in the chain. The table is an array of 2^k buckets, resized by incremental rehashing.
- Entry header. Hash-chain next pointer, LRU prev and next pointers (or a 24-bit access clock under approximate LRU), expiry time, CAS version, flags, key length and value length.
- Key bytes, then value bytes. These are stored inline to save a pointer and a cache-line miss. Small integers and short strings use compact encodings.
Keys and sharding. The partition key is the cache key itself, hashed to a slot. Applications can force related keys into one slot with hash tags, where only the part of the key inside braces is hashed. That allows multi-key operations, such as MGET of one user's fields, on a single node. Use them sparingly, because a popular tag creates a hot slot. There are no secondary indexes: every access is by exact key. That is a deliberate constraint, and it keeps every operation O(1) on one node.
Retention. Entries live until their TTL, eviction or deletion. Nothing is archived. The metadata keeps a short history of maps, for example the last 100 epochs, for debugging and rollback.
Deep Dives#
1) What does a single node look like inside, and how does it stay fast?#
The node is where the microseconds are spent. An interviewer who asks "what data structure?" wants hash map plus LRU list. One who keeps going wants to hear about resizing, threads and memory.
Basic: a language hash map plus a linked list behind one big lock. The LRUCache class above, wrapped in a mutex, is correct. It is fine for an in-process cache with modest traffic. It breaks down in three places at server scale:
- The lock serialises everything. Every
getwrites, because it moves the entry to the head of the list. So a read-write lock does not help, and all cores queue on one mutex. - Resizing the hash map stops the world. Growing from 2^27 to 2^28 buckets means rehashing 100 million entries, which pauses the node for seconds.
- The general-purpose allocator fragments. After hours of mixed-size sets and evictions, resident memory can be 30-50% above the live data. The node then hits
maxmemory, or the out-of-memory killer, with far less data than expected.
Better: pick a concurrency model on purpose, and resize incrementally.
- Single-threaded event loop (Redis). One thread runs every command, so there are no locks, every command is atomic for free, and latency is predictable. To use more cores, you run more nodes per machine, one per core or so. Redis 6 added I/O threads to read and write sockets in parallel, while command execution stays on one thread. The weakness is that any slow command blocks everyone: a
KEYS *, a hugeDEL, a big Lua script. Big frees are handed to a background thread withUNLINKand lazy-free options. - Multi-threaded with partitioned locks (Memcached). Worker threads handle connections. The hash table is protected by many striped locks, chosen by bucket hash, so threads touching different buckets do not contend. LRU maintenance uses per-class locks, and a background thread moves items between the LRU segments. One process scales across cores. The cost is more complex code, and contention on genuinely hot keys.
- Incremental rehashing. Redis keeps two tables during a resize. Each operation moves a few buckets from the old table to the new one, and lookups check both until the move finishes. The resize cost is spread over millions of operations instead of one pause. Memcached does something similar with a background thread that expands the table.
Best: also design the memory layout and allocator for a billion small objects.
- Slab allocation (Memcached). Memory is carved into 1 MB pages, and each page is assigned to a slab class of fixed-size chunks: 96 B, 120 B, 152 B and so on, growing by a factor of about 1.25. An item goes into the smallest chunk that fits. Freed chunks are reused within their class, so external fragmentation cannot build up. The cost is internal waste, up to about 20% per item, and slab calcification: if the workload's size mix shifts, memory stuck in the wrong classes must be rebalanced. Memcached has a slab-rebalancer thread for exactly this.
- jemalloc with size classes and active defragmentation (Redis). Redis relies on jemalloc's size classes and can move live allocations to compact memory in the background (
activedefrag). It reportsmem_fragmentation_ratio(resident memory over used memory), so operators can see the problem. - Compact encodings. Small values, small integers and short strings are stored inline or in packed forms. For workloads with many small items this can halve memory, because per-entry overhead is comparable to the data.
- Avoid per-request allocation. Use pre-allocated buffers for parsing, and send replies straight from item memory where possible, using reference counts so an item being sent cannot be freed mid-write.
- Big values are special. A 1 MB value takes about 1 ms just to send at 10 Gbit/s, and blocks a single-threaded node while it is copied. Cap value size, compress values over a few KB with a fast codec such as LZ4 or Zstd, and split very large objects into chunks.
The interview answer that lands: "Each node is a hash table with chained entries plus approximate-LRU metadata. Execution is single-threaded per shard, with several shards per host to use the cores. Resizing is incremental, and memory uses a size-class allocator with defragmentation, so used memory tracks live data." Then expect follow-ups on each part.
2) How exactly do TTLs and expiry work at a billion keys?#
Basic: a sweeper that scans every key. It is correct, but it scans a billion keys to find a few million that have expired, and it uses CPU and memory bandwidth on the same thread that serves requests. It is also slow to free memory, because each key is only visited once per full sweep, which might take minutes.
Better: lazy expiry plus a sampled active expiry. This is the approach in the high-level design. Lazy deletion on access ensures correctness, since nothing expired is ever returned. Probabilistic sampling, with a fixed CPU budget per cycle, frees forgotten keys: sample keys that have TTLs, delete the expired ones, and repeat while the share of expired keys in the sample stays high. The steady state is that a small, bounded fraction of memory holds expired-but-not-yet-freed keys. The cost is per cycle, not per key. Memcached is lazier still. Its LRU crawler thread walks the item lists in the background and reclaims expired items, and a set can reuse an expired item it finds at the tail of the LRU.
Best: exact timers only where they matter, and expiry that is safe across replicas and time.
- Timing wheels for exact, cheap timers. If an application needs expiry callbacks (keyspace notifications) close to the deadline, a hashed timing wheel gives O(1) insertion and O(1) work per tick. It is an array of slots, one per tick, with each timer hashed into its slot. Hierarchical wheels add wheels with coarser ticks, so long timeouts do not need huge arrays. The idea comes from George Varghese and Tony Lauck's "Hashed and Hierarchical Timing Wheels" (SOSP 1987), and it is used in operating system kernels and in network libraries such as Netty. A min-heap is simpler, but costs O(log n) per insertion.
- Primary-driven expiry. As the high-level design described, only primaries expire keys. They replicate an explicit
DEL, so replicas never disagree about existence. Replicas still hide logically expired keys on reads. - Absolute timestamps, and the clock question. Store
expires_atas absolute time on the primary. If a client sends a TTL in seconds, the primary turns it into an absolute time on its own clock. A failover to a replica with a skewed clock could expire keys early or late by the skew. Keep clocks disciplined with NTP. Never let clients send absolute expiry times from their own clocks for correctness-sensitive data. See Time, Clocks and Ordering. - Jitter on TTLs. If a deploy warms 10 million keys with
TTL 3600, they all expire in the same second an hour later, and the database gets a synchronised miss storm. Add ±10% random jitter to every TTL. It is one line of client code, and it prevents a recurring hourly incident. The Cache Failure Modes: Stampedes, Hot Keys and Penetration page covers the wider family. - Eviction versus expiry. These are separate mechanisms. TTL says "this is no longer valid". Eviction says "we need room". A cache under memory pressure evicts valid keys before their TTL. Policies such as
volatile-lruevict only keys that have TTLs, which protects permanent entries but can fail writes if no key has a TTL.allkeys-lrutreats everything as evictable. A pure cache should use anallkeys-*policy, so writes never fail for lack of memory.
3) How do we partition keys so that load is even and resizing is cheap?#
Basic: hash(key) mod N. Keys are spread perfectly evenly while N stays fixed. When N changes, a key keeps its node only if hash mod N equals hash mod (N+1), which happens for about 1/(N+1) of keys. So going from 10 to 11 nodes moves about 91% of keys, and losing one node of 10 moves about 90%. For a cache, every moved key is a miss. A routine resize then sends the database nearly the whole read traffic, which is how "we added a cache node" becomes a database outage. The same thing happens on every node failure if failed nodes are removed from N.
Better: a consistent-hash ring with virtual nodes. Hash nodes and keys into the same space, 0 to 2^32 − 1 or 2^64 − 1, arranged as a ring. A key belongs to the first node at or after its hash, going clockwise. Adding a node at a point P takes over only the keys between P and its counter-clockwise neighbour. Removing a node gives its keys to its clockwise neighbour. Everything else stays where it was, so the expected movement is 1/N of the keys, the theoretical minimum. The idea dates from David Karger and colleagues' "Consistent Hashing and Random Trees" (STOC 1997), written for web caching. Akamai's CDN grew out of that work.
With one point per node, though, the arcs vary a lot in size. With N random points, the largest arc is about ln N times the average, and a failed node's whole arc lands on one neighbour, doubling that neighbour's load. Virtual nodes fix both problems. Each physical node gets V points, for example by hashing nodeA#0 to nodeA#199. A node's share is then the sum of V small arcs, and its imbalance shrinks roughly as 1/√V. With V = 100-200, nodes typically differ from the mean by about 5-10%. When a node fails, its V arcs go to many different successors, so its load spreads across the cluster. Virtual nodes also allow weighting: a machine with twice the memory gets twice the points. The costs are a lookup structure (a sorted array of N × V points, searched by binary search in O(log NV)) and the need for every client to compute the same ring.
Best for our cache: fixed slots with an explicit assignment table, and an understanding of the other modern variants.
- Fixed hash slots (Redis Cluster).
slot = CRC16(key) mod 16384, and a table maps each slot to a node. With 16 primaries, each owns about 1,024 slots. To add a node, choose about 1/(N+1) of the slots, taking the same number from each existing node, and move only those. Balance is set by the operator or a rebalancer rather than by chance, so it can be exact. Ownership is easy to inspect: "who owns slot 4120?" has one answer in a table. Moving a slot is a well-defined unit of work. The cost is that the table must be kept and distributed, which is the membership problem in Deep Dive 6. The fixed slot count also caps the cluster at 16,384 primaries, which is far beyond any real cache. With many slots per node, slots act like virtual nodes. - Jump consistent hash. John Lamping and Eric Veach's "A Fast, Minimal Memory, Consistent Hash Algorithm" (2014) maps a key to one of N buckets with a few lines of arithmetic and no stored ring. It gives perfect balance and minimal movement when N grows or shrinks at the end. It cannot remove an arbitrary node from the middle, so it fits numbered shards that each have replicas, rather than a set of individual machines that come and go.
- Rendezvous (highest random weight) hashing. For each key, compute
hash(key, node)for every node and choose the highest score. David Thaler and Chinya Ravishankar described it in the late 1990s. It gives minimal movement, natural weighting, and an obvious "second choice" node for replicas: the second-highest score. The cost is O(N) per lookup, which is fine for tens of nodes and can be made hierarchical for thousands. - Bounded-load consistent hashing. Mirrokni, Thorup and Zadimoghaddam's "Consistent Hashing with Bounded Loads" (2016/2018) caps every node at (1 + ε) times the average load, passing overflow on to the next node on the ring. HAProxy added an option based on it (
hash-balance-factor) for consistent-hash load balancing. It addresses traffic imbalance, not just key-count imbalance.
A key point for interviews: even key distribution is not even traffic. Virtual nodes and slots balance the number of keys, which is structural balance. They do nothing when one key gets 1% of all requests, which is workload imbalance. That needs replication of hot keys, client-side caching or key splitting (Deep Dives 8 and 9). It is the distinction the consistent-hashing literature itself draws.
4) How do replication and failover work for a cache?#
Basic: no replication, so a node failure means misses. Since the database is the truth, a lost node loses only performance: its 1/N of keys miss until they are refilled. This is how many Memcached deployments run. It is simple and costs half as much RAM. The risks are the cold-start load on the database, which may be more than it can take if the node held a hot set, and the time to warm up again. Facebook's memcache paper describes a gutter pool: a small set of spare servers that temporarily take over a failed server's keys with short TTLs. This shields the database without rehashing the keys onto healthy nodes, which would spread the failure.
Better: asynchronous primary-replica per shard, with automatic promotion. Each primary streams its writes, in the form of its command or effect log, to one or two replicas in other zones. A replica acknowledges by offset. After a short disconnect it resumes from the primary's replication backlog, a circular buffer of recent writes. Only if it has fallen further behind than the backlog covers does it need a full resync, which means a snapshot plus a stream. On failure:
- Detect it: heartbeats missed for longer than
node-timeout, confirmed by a majority. - Elect a replica, preferring the one with the highest replication offset because it lost the least.
- Promote it with a new epoch.
- Publish the new owner of the slots.
The client sees a few seconds of errors on one shard, then normal service with a nearly full cache. The cost is twice the memory, a small replication stream, and the possibility of losing recent writes, because acknowledgements happen before replication. For a cache that is acceptable by definition.
Best: replication designed around failure domains, read policies and fencing.
- Spread replicas across zones, so one zone outage never takes both a primary and its replica. Use replica migration, as Redis Cluster does: a spare replica moves automatically to a primary that has lost its own replica, so no shard is left without one.
- Fencing with epochs. Every failover increases the epoch. A primary that was cut off and returns sees a higher epoch for its slots, steps down and drops any writes it accepted while isolated. For extra safety, a primary that cannot reach a majority of the cluster for longer than a timeout stops accepting writes by itself. That bounds the split-brain window. See Leader Election and Coordination Services.
- Optional synchronous acknowledgement for hot data.
WAIT 1 50in Redis blocks the client until at least one replica has the write, or until 50 ms pass. It reduces lost writes but cannot guarantee zero: if the replica that acknowledged dies too, the write is still lost. Use it sparingly. It makes the write path wait on the slowest replica. - Read policy per use case. Reading from replicas doubles read capacity and helps with hot keys, but it may return data that is milliseconds stale. Read-your-writes is not guaranteed. A pool can offer
read_from: primary | replica | nearest, and callers choose per key family. Session data stays on the primary, and product catalogue reads can go to the nearest replica. - Quorum replication instead (Dynamo-style). Some caches and key-value stores use leaderless replication: write to W of N replicas and read from R, with R + W > N for overlap. That removes failover entirely, at the cost of more network traffic per operation and conflict resolution. It is a better fit for the durable store in Quorums and Leaderless Replication and the key-value store case study than for a sub-millisecond cache.
- Warm restarts. Some systems can restart a node without losing its memory contents, for example by keeping items in shared memory or a file that is reattached on restart. Memcached added such a restartable mode. That turns planned upgrades into near-zero-miss events.
The general replication trade-offs are covered in Database Replication.
5) How do requests find the right node: smart client, proxy or server redirect?#
Basic: a static server list in every client's config. Each application hashes keys against a hard-coded node list. It works, and many early Memcached deployments did exactly this. But every membership change needs a config push to every application, and during the rollout clients disagree about the list, so the same key is read from and written to different nodes. Stale data and miss storms follow.
Better: a proxy tier. Applications talk to a local or nearby proxy that knows the topology. Twitter built twemproxy for Memcached and Redis. Facebook built mcrouter, which adds routing prefixes, replicated pools, failover and shadow traffic. Envoy can also proxy Redis. Proxies:
- concentrate connections: thousands of application processes become a few connections per cache node,
- hide topology changes from applications,
- centralise retries, failover and metrics,
- let any language use the cache with a simple client.
The costs are an extra hop, about 0.1-0.5 ms (less when the proxy runs as a sidecar on the same host), an extra tier to scale and keep available, and some loss of features such as client-side pipelining across nodes.
Best: smart clients with a cached map, server-side redirects as the safety net, and a proxy only where it earns its keep.
- Clients cache the slot map and route directly: zero extra hops. On connect, and on any
MOVED, they fetch the full map again. Clients do not need to be told about changes in real time, because a wrong guess is corrected by the server, which costs one extra round trip once per moved slot. - Servers redirect instead of proxying. A node that does not own a key answers
MOVED(permanent: update your map) orASK(temporary, during migration: send just this request to the importing node after anASKINGprefix). Nodes never forward requests among themselves, which keeps them simple and keeps load predictable. - Proxies where they help. Use a proxy for languages without a good cluster client, for serverless functions that cannot hold pools of connections, and for huge fleets where connection counts per node become the bottleneck. 50,000 processes × 16 nodes × 2 connections is 1.6M connections, which no cache node wants.
- Batching that respects the topology. A client
MGETof 100 keys is split by owning node and sent in parallel, one pipelined request per node, then merged. Latency is the slowest node's, so large fan-outs make tail latency worse. Deep Dive 10 deals with that.
6) How do nodes agree on membership and slot ownership?#
Every node and client must agree, quickly and safely, on two things: which nodes are alive, and which node owns each slot. Getting this wrong means two primaries for one slot (split brain), or a slot with no owner.
Basic: an operator edits a config file. Membership is static, and failures are handled by a person replacing the node. That is safe because only one actor changes things, but it is slow: minutes to hours to react, and impossible at 3 a.m. without paging someone.
Better: a coordination service holds the truth. Nodes register themselves in etcd or ZooKeeper with a lease, an ephemeral node or a TTL key renewed by heartbeat. If a node stops renewing, its lease expires, and watchers are told it has left. The cluster manager, itself elected through the same service, owns the slot map. It writes new versions with compare-and-set on the version number, and everyone watches the map key. This gives linearizable decisions: one map version at a time, ordered by the coordination service's consensus log (see Consensus: Raft and Paxos). It also gives simple reasoning and a single place to look. The costs are an external dependency, which needs 3 or 5 replicas of its own, and failure detection limited by lease length. Short leases detect failures quickly but cause false positives during GC pauses or brief network glitches.
Best: gossip-based failure detection with epoch-fenced ownership, or a coordination service used only for the decisions that need consensus. Redis Cluster shows the pure gossip design:
- Every node pings a few random peers each second over a cluster bus, and each message carries gossip about other nodes' states. Information spreads epidemically, reaching all N nodes in O(log N) rounds. The approach follows the family of protocols around SWIM, from Abhinandan Das, Indranil Gupta and Ashish Motivala's "SWIM: Scalable Weakly-consistent Infection-style Process Group Membership Protocol" (DSN 2002). SWIM's key ideas are a constant message load per node, indirect probes (ask k other nodes to ping a suspect before declaring it dead), and a suspect state before failed to cut false positives.
- A node that cannot reach a peer within
node-timeoutmarks it PFAIL (possibly failed). When a majority of primaries report PFAIL for the same node within a window, it becomes FAIL, and every node learns that through gossip. - Slot ownership changes only through epochs. A replica promoted after a FAIL takes a new, unique
configEpochby winning a majority vote of primaries. When two nodes claim the same slot, the higher epoch wins everywhere. This is consensus-like agreement on the one thing that needs it (who owns which slot), while membership news spreads cheaply and eventually. - Gossip only spreads information. A majority must agree before a node is declared failed, and a vote must be won before slots change hands. That is why a minority partition cannot promote replicas: it cannot reach a majority.
The trade-off between the two families:
- Coordination service. Easier to reason about, and the decision log is visible. But it is an external dependency, and failure detection is only as fast as the leases.
- Gossip. No external dependency, scales to hundreds of nodes, and fast detection with few false positives thanks to indirect probes. But the protocol is harder to debug and the rules about epochs are subtle.
Many systems mix them: gossip for liveness, a consensus store for ownership.
Only the forward path is shown. Suspect returns to Active when heartbeats resume before a majority agrees, which is the common case for brief pauses. A Failed node that comes back rejoins as a replica of whoever now owns its old slots, never as their primary.
A practical rule for timeouts: make the failure-detection timeout clearly longer than normal pauses, such as GC, fork() for snapshots, or a VM migration. Make it short enough that the outage stays within the availability budget. With 99.99%, about 4.4 minutes a month, a 5-15 second detection plus promotion fits many failovers into the budget. A 60-second timeout does not.
7) Which eviction policy, and how do we implement it at scale?#
Eviction decides what the cache keeps, and that decides the hit ratio, the one number the cache exists to maximise. A 1-point drop from a 95% to a 94% hit ratio sends 20% more traffic to the database (from 5% of reads to 6%).
Basic: exact LRU with a global list. It is easy to explain and works well when recent use predicts reuse, which is true of most web data. It has two problems. First, the list update on every read: a pointer update and a lock on a shared structure, the main source of contention on multi-threaded caches. Second, no scan resistance: one sequential read of cold data, such as a backfill job, an analytics crawl or a cache warm-up of rarely used keys, pushes the hot set out, and the hit ratio crashes until it recovers.
Better: approximate LRU or CLOCK, without a list update on every read.
- Sampled LRU (Redis). Each object stores a 24-bit "last access" clock, so there is no list. On eviction, Redis samples
maxmemory-samplesrandom keys (5 by default) and evicts the one idle the longest. It also keeps a small eviction pool of good candidates between rounds, so the result gets closer to true LRU. With 10 samples it is very close to exact LRU in practice, at a fraction of the memory and with no lock on reads. - CLOCK (second chance). Entries sit in a circular buffer, each with a reference bit. A hit just sets the bit, a cheap write that needs no reordering. An eviction "hand" sweeps the buffer: if an entry's bit is set, the hand clears it and moves on; if the bit is clear, the entry is evicted. Operating systems have long used CLOCK variants for page replacement. It approximates LRU with O(1) hits that never contend over list order.
- Segmented LRU (Memcached's modern LRU). Items enter a cold segment. Only items that are hit again move to warm, and a separate hot segment holds new or very active items. Items are bumped at most once every few seconds, and asynchronously. A scan fills cold, but the hot and warm working set survives. That solves scan resistance in a simple way.
Best: frequency-aware policies with admission control, chosen per pool.
- LFU with decay (Redis
allkeys-lfu). Each object keeps an 8-bit logarithmic counter, a Morris-style probabilistic counter that increments with probability about 1/(counter × factor), so 8 bits can represent millions of hits. The counter decays over time, so yesterday's star can be evicted today. LFU suits stable popularity, such as product catalogues and configuration. Without decay it handles shifting trends badly, so decay is essential. - TinyLFU admission (W-TinyLFU). The insight is that the question is not only "what to evict", but also "should this new item be admitted at all?". TinyLFU keeps a compact, approximate frequency sketch of recent accesses (a count-min sketch with periodic halving). A new item is admitted only if its estimated frequency beats that of the eviction victim. W-TinyLFU adds a small LRU "window" in front, so new items get a chance to prove themselves. Gil Einziger, Roy Friedman and Ben Manes described it in "TinyLFU: A Highly Efficient Cache Admission Policy" (ACM Transactions on Storage, 2017). It powers Caffeine, the widely used Java cache, and often beats LRU's hit ratio by several points on real traces. The sketch is from Probabilistic Data Structures for Big Data.
- ARC (Adaptive Replacement Cache). It balances recency and frequency automatically. ARC keeps two LRU lists, one for entries seen once and one for entries seen at least twice, plus "ghost" lists of recently evicted keys. It shifts space towards whichever list's ghosts are being hit. Nimrod Megiddo and Dharmendra Modha described it in "ARC: A Self-Tuning, Low Overhead Replacement Cache" (FAST 2003). It is used in ZFS. It is a good example of an adaptive policy, but its bookkeeping is heavier than sampled approaches.
- Size-aware and cost-aware eviction. Evicting one 1 MB value frees as much memory as evicting a thousand 1 KB values. If small items are hit as often, keeping them gives more hits per byte. Policies such as GreedyDual-Size weight eviction by size and by the cost to recompute. Most caches do not do this by default, but pools of mixed sizes can gain a lot from separating big and small items into different pools.
- Per-pool policy and quotas. Different workloads want different policies: LRU for session data, LFU for catalogue data, TTL-only for rate-limit counters. They should also not compete for the same memory. One team's bulk job must not evict another team's hot set, so each pool gets its own memory limit.
The general theory, including Bélády's optimal "evict the item used furthest in the future" bound that every policy approximates, is in Cache Eviction and Invalidation. For our design: sampled LRU by default, LFU with decay for pools with stable popularity, and a frequency-sketch admission filter for pools exposed to scans. Measure the hit ratio per pool and compare policies by replaying recorded traces. Do not guess.
8) What happens when one key gets an enormous number of reads?#
Imagine a celebrity's profile, a breaking news story or a flash-sale item read 500k times per second. Its slot lives on one primary that can handle about 100k-200k operations per second in total. With a 10 KB value, those reads are also 5 GB/s on one NIC. The cluster is mostly idle, while one node is saturated and starts timing out for every key it owns.
Basic: scale the node up, or rely on the cluster. Neither helps. Sharding spreads keys, and this is one key. A bigger machine has more cores, but a single-threaded shard uses one. Even multi-threaded, the NIC is the limit.
Better: spread the key's reads over many copies.
- Read from replicas. If the key's primary has R replicas and the client is allowed to read from replicas for this key family, read capacity grows R + 1 times. It is simple and needs no change in the application, but it only scales as far as the replica count, and the data may be slightly stale.
- Key copies (salting). Store the value under k keys,
product:123#0toproduct:123#9, which hash to different slots and therefore different nodes. Readers pick a suffix at random. Writes and invalidations must update all k copies, which is a fan-out. So this works for keys that are read-hot and written rarely, and readers need to know which keys are copied. Keep a "hot key list", detected automatically and distributed to clients like the slot map.
Best: catch hot keys before they reach the cache tier, and detect them automatically.
- In-process L1 cache in the client. Each application server keeps a tiny cache, for example 10k entries or 100 MB, of the hottest keys with a short TTL of 1-5 seconds. With 2,000 application servers, a key read 500k times per second turns into at most about 2,000 cache reads per TTL window, a reduction of hundreds of times. Staleness is bounded by the TTL, so this works for data that can be seconds old, such as profiles, counts and feeds. Facebook, Twitter and others describe client-side caching like this, and Redis 6 added client-side caching with server-assisted invalidation (
CLIENT TRACKING): the server remembers which keys a client has cached and sends invalidation messages when they change. That allows longer L1 TTLs without unbounded staleness. - Automatic hot-key detection. Each node samples its requests and keeps a top-K estimate with a count-min sketch or a heavy-hitters algorithm such as Space-Saving. It publishes keys above a threshold, for example 1% of the node's traffic. Clients then promote those keys to L1, salt them, or route their reads to replicas. Redis exposes approximate hot keys (
--hotkeyswith LFU) and Memcached can stream sampled requests for analysis. Detection should be automatic, because viral events do not page you first. - Request coalescing. When many requests for the same missing or expiring key arrive together, one fetch goes to the cache or database, and the others wait for its result. This is a single-flight lock, kept in the client or in a proxy. It prevents a thundering herd on the database when a hot key expires (Deep Dive 11).
- Serve large hot values from a CDN. If the hot item is a large, public object, such as a rendered page fragment or an image, the right cache is the edge, not the data-centre cache. See Content Delivery Networks (CDN).
The key distinction, again, is that virtual nodes and slots fix structural imbalance, while replication, L1 caching and salting fix workload imbalance. The general techniques are in Pattern: Scaling Reads.
9) What happens when one key gets an enormous number of writes?#
Write-hot keys are harder than read-hot keys, because copies make writes worse. Each extra copy is another write. Typical causes are a global counter ("total likes on this post"), a rate-limit bucket for one huge client, a "last seen" timestamp updated by every request, or a leaderboard entry during a live event.
Basic: send every write to the key's primary. Each INCR is cheap, but at 300k per second on one key the shard saturates, and every other key on that node suffers. Replicas do not help: they must apply every write too.
Better: split the key into sub-keys and aggregate on read. Replace likes:post9 with likes:post9#0 to likes:post9#15 on different slots. Each writer increments a random sub-key, and a reader sums all 16. The write load spreads 16 times. Reads cost 16 times more, which is fine if reads are rarer or are served from a cached total that is refreshed every second. This works for commutative operations such as counters, sets of seen IDs, and max or min. It does not work for "set the value to X", where the last writer must win. Hot-key splitting is a classic in Pattern: Scaling Writes.
Best: absorb writes before they reach the cache tier, and change the data model if needed.
- Coalesce in the client. Each application server buffers increments for 100 ms to 1 s and sends one
INCRBY key n. 2,000 servers that each send one write per second replace 300k writes per second. The cost is that the counter lags by up to the buffering interval, and a crash loses the buffered amount. That is fine for social counts and not for money. - Last-writer-wins with throttling. For "last seen"-style keys, write only when the value has changed meaningfully, for example at most once a minute per user. Most writes then disappear without any loss of product value.
- Stream, then materialise. Send high-rate events to a log such as Kafka, aggregate them in a stream processor, and write the aggregate into the cache once a second. The cache then serves the result, not the raw updates. See Apache Kafka in Practice.
- CRDT counters for multi-writer or multi-region cases. A grow-only counter is kept as a map from writer to count, so writes are local and merges are a per-writer maximum followed by a sum. This avoids coordinating on every write. See Conflict Resolution, OT and CRDTs.
- Isolate. Move a known write-hot key to a dedicated shard, or a dedicated pool, so its load cannot hurt neighbours, and set alerts on per-key operation rates.
10) How do we keep latency low, especially at the tail?#
Average latency for a cache is easy to get right. The problem is the tail, because callers often fan out. A page that reads 100 keys from 16 nodes is as slow as the slowest of those reads. If each node has a 1% chance of a 10 ms hiccup, a page touching 16 nodes hits at least one hiccup with probability 1 − 0.99^16 ≈ 15%. Jeffrey Dean and Luiz André Barroso's "The Tail at Scale" (Communications of the ACM, 2013) made this arithmetic famous.
Basic: one request per key over a new connection. Every operation pays a TCP (and possibly TLS) handshake, plus a full round trip. Throughput per client is one key per round trip, which is about 2,000 operations per second per connection at 0.5 ms.
Better: persistent connections, pipelining and batching.
- Connection pooling or multiplexing. A few long-lived connections per node per process, with many requests in flight on each. The handshake cost then disappears.
- Pipelining. Send many commands without waiting for each reply, then read the replies in order. Throughput per connection goes from one per round trip to many thousands.
- Batch APIs.
MGETandMSET, split by node and sent in parallel, give one round trip per node instead of per key.
Best: also design out the sources of tail latency.
- Avoid slow commands on single-threaded shards. That means
KEYS, unboundedSMEMBERSorLRANGE, aDELof a million-element structure (useUNLINK), and large Lua scripts. One 50 ms command makes every request on that shard wait 50 ms. Run the slow log and alert on it. - Fork and snapshot pauses. If persistence is ever enabled, a
fork()of a 75 GB process can take tens to hundreds of milliseconds of page-table copying, and huge pages make copy-on-write worse. Keep pure caches persistence-free, or snapshot from replicas. - Control fan-out. Co-locate keys that are read together with hash tags so that one request reaches one node. Cap fan-out, and cache the composite result, such as a rendered fragment, rather than its 100 parts.
- Hedged and tied requests, for reads only. If a replica read has not returned by the p95 latency, send it to another replica as well and use whichever answers first. This trims the tail for a few percent of extra load. It is safe because
GETis idempotent. Never hedge non-idempotent writes. - Timeouts and fallbacks. Give each cache call a budget of a few milliseconds. On timeout, treat the call as a miss and read the database, or serve stale data from L1. Add a circuit breaker so that a sick shard does not tie up threads. A cache that is down should make the service slower, not dead.
- Kernel and NIC tuning. Spread interrupts across cores (IRQ affinity, RSS), set sensible TCP buffers, and keep hosts free of noisy neighbours, which is a real issue on shared VMs. At the extreme, kernel-bypass networking with DPDK is used in research and in some specialised caches. It is rarely needed for a general cache tier.
11) How do we keep the cache consistent with the database, and avoid stampedes?#
The cache stores copies. Two things go wrong: stale copies, when the database changes but the cache does not, and stampedes, when the copy is missing and everyone rushes to the database at once.
Basic: cache-aside with TTL only. Read from the cache, and on a miss read the database and SET with a TTL. On writes, update the database and let the TTL take care of the rest. It is simple, and staleness is bounded by the TTL. But a 10-minute TTL means up to 10 minutes of stale data after every update. That is unacceptable for prices or permissions.
Better: invalidate on write. After updating the database, DELETE the cache key, so the next read misses and refills. Delete rather than update: a delete is idempotent and is not affected by write order. Concurrent "update the cache" writers can leave an older value on top of a newer one. This is not airtight, though. The classic race goes:
- Reader A misses and reads the old value from the database.
- Writer B updates the database and deletes the key.
- A then
SETs the old value it read. The cache now holds stale data until the TTL runs out.
Best: leases or versioned sets for the race, coalescing for stampedes, and change-data-capture for reliable invalidation.
- Leases. Facebook's "Scaling Memcache at Facebook" (Rajesh Nishtala and colleagues, NSDI 2013) describes them. On a miss, the cache hands the client a lease token. The later
SETsucceeds only if the token is still valid, and aDELETEin between cancels the token. So A's lateSETof the old value is rejected. Leases also rate-limit refills: only the lease holder refills, while other clients get a "hot miss" and either retry shortly or accept a slightly stale value. That stops stampedes on hot keys. - Versioned or conditional sets. Store a version from the database with the value, such as the row's update counter, and use
CASor a script for "set only if the new version is higher". Late writers holding older data then cannot overwrite newer data. - Invalidation driven by change data capture. Do not rely on every code path remembering to delete. Tail the database's change log (binlog or WAL) with a CDC tool such as Debezium and send deletes to the cache. Facebook's memcache paper describes a daemon (mcsqueal) that reads the MySQL commit log and broadcasts deletes, including to other regions. That makes invalidation as reliable as the database's own log.
- Stampede protection. When a hot key expires, use one of three techniques. Request coalescing (single-flight) lets one caller refill while the others wait. Stale-while-revalidate serves the old value while one caller refreshes it in the background. Probabilistic early expiration has each reader refresh with a probability that rises as the TTL nears zero, so refreshes spread out in time instead of piling up at expiry. Vattani, Chierichetti and Lowenstein analysed the optimal form of this, known as XFetch, in "Optimal Probabilistic Cache Stampede Prevention" (VLDB 2015).
- Negative caching. Cache "not found" briefly, for 30-60 seconds, so that repeated lookups of non-existent keys (cache penetration) do not hammer the database. Use a Bloom filter in front for very high rates of invalid keys.
The full discussion of these failure modes is in Cache Failure Modes: Stampedes, Hot Keys and Penetration.
12) How do we add capacity, warm new nodes and run across regions without miss storms?#
Basic: add nodes and rehash. With modulo hashing, this is the 90% miss storm from Deep Dive 3. With consistent hashing or slots and no migration, about 1/N of keys miss at once. That is usually fine, unless the cache is shielding a database running near its limit.
Better: live slot migration. Move slots one at a time, copying keys in the background with the MIGRATING/IMPORTING and ASK protocol, so the new node starts warm and clients see almost no misses. Pace the migration, for example with a bandwidth cap of 50-100 MB/s per node, so the copy traffic does not hurt foreground latency. Plan capacity changes before memory is full. A node at its memory limit is evicting hard, and adding nodes during an incident is the worst time to move data.
Best: capacity management as a routine process, warm-up for cold caches, and a deliberate cross-region model.
- Headroom and autoscaling signals. Scale on used memory against
maxmemory(above 80%), on eviction rate of non-expired keys (a sign the working set no longer fits), on CPU per shard (above 60-70% for a single-threaded shard), and on network bandwidth. The hit ratio is the result to watch, not the trigger. - Cold-cache warm-up. A whole new pool or region starts empty, at a 0% hit ratio. Facebook's memcache paper describes a cold cluster warm-up: on a miss, a new cluster reads from a warm cluster instead of the database, for a few hours, until its hit ratio recovers. Alternatives are pre-loading known-hot keys from a snapshot or a list of top keys, and shifting traffic to the new pool gradually, at 1%, then 10%, then 50%.
- Multi-region. Run an independent cache cluster in each region next to its applications, never reading across regions on the hot path, which would cost 80-200 ms. Keep regions consistent through invalidation, not replication of values. Database writes in the primary region produce CDC delete events that are broadcast to every region's cache. Each region refills from its local database replica. The cache is then never ahead of the local database, and a slightly stale value is replaced within the replication lag. See Multi-Region and Global Data.
- Multi-tenancy. Give each pool a memory quota and a separate eviction domain, rate-limit clients per pool, and set connection limits. Charge teams for memory, so that caching everything forever has a visible cost. See Multi-Tenant SaaS Architecture.
- Rolling upgrades. Upgrade replicas first, fail over to them, then upgrade the old primaries. Or use warm restarts so that a restarted node keeps its memory. Never restart many primaries at once, because the combined miss storm is the outage.
Bottlenecks and Failure Modes#
| Failure / hotspot | Impact | Mitigation |
|---|---|---|
| Primary node crash | Its slots' keys error out until failover; recent writes lost | Cross-zone replica, majority-confirmed failure, epoch-fenced promotion in about 5-15 s, client timeouts and retries |
| Read-hot key | One node's CPU or NIC saturates; all its keys slow down | L1 client cache with short TTL, replica reads, key salting, hot-key detection, CDN for large public values |
| Write-hot key | One shard saturates on writes | Sub-key splitting, client-side write coalescing, stream-then-materialise, dedicated shard |
| Synchronised expiry or hot-key expiry | Database stampede, cascading overload | TTL jitter, single-flight refills, leases, stale-while-revalidate, probabilistic early refresh |
| Resize with modulo hashing | About 90% of keys move, miss storm | Slots or consistent hashing, live slot migration, gradual moves |
| Network partition between zones | Risk of two primaries for one slot | Majority-only failover, epochs, isolated primary stops taking writes after a timeout |
| Memory fragmentation | Node hits its memory limit with far less live data | Slab or size-class allocator, active defrag, monitor fragmentation ratio, headroom |
| Slow command on a single-threaded shard | Every request on the shard waits | Ban or limit KEYS and huge collections, UNLINK, slow log alerts, bounded scripts |
| Stale data after a race between read and delete | Old value cached until TTL | Leases, versioned or CAS sets, CDC-driven invalidation, short TTL safety net |
| Large fan-out reads | Tail latency multiplies across nodes | Hash-tag co-location, caching composite results, hedged replica reads, per-call timeouts |
| Cold cache after a new pool or full restart | Database overload while warming | Warm from a sibling cluster, pre-load top keys, gradual traffic ramp, gutter pool |
| Connection explosion from huge client fleets | Node memory and CPU spent on connections | Multiplexed clients, proxy tier (mcrouter or twemproxy style), connection limits per pool |
What Interviewers Expect#
Mid-level#
- Define the API (get, set with TTL, delete) and explain a single node as a hash map plus a doubly linked list for O(1) LRU, coding or sketching it if asked.
- Explain lazy plus active expiry, and how LRU eviction runs when memory is full.
- Shard across nodes and explain why consistent hashing (or slots) beats
hash mod Nwhen nodes are added or removed. - Add replicas for availability, and explain at a high level that a replica is promoted when a primary fails.
Senior#
- Discuss virtual nodes against fixed slots with an explicit table, including the movement and balance maths, and how clients route with
MOVEDandASK. - Design replication and failover: asynchronous replication with a backlog for partial resync, majority-confirmed failure detection, epoch fencing, and what is lost during failover and why that is acceptable.
- Tell structural imbalance apart from hot keys, and offer concrete fixes for read-hot keys (L1, replicas, salting) and write-hot keys (splitting, coalescing).
- Discuss eviction beyond LRU: approximate LRU, segmented LRU, LFU with decay, scan resistance, and per-pool policies.
Staff+#
- Treat membership as the core distributed-systems problem: gossip against a coordination service, SWIM-style suspicion, split-brain prevention, and timeouts sized to the availability budget.
- Cover tail latency under fan-out ("The Tail at Scale"), slow commands, fork pauses and allocator fragmentation, the details that decide real p99s.
- Design consistency with the database: invalidation races, leases, CDC-driven deletes, stampede prevention and cold-cluster warm-up, with real systems (Facebook memcache, Redis Cluster) as anchors.
- Plan operations: capacity signals, live resharding pace, rolling upgrades without miss storms, multi-region invalidation, and multi-tenant quotas.
Deep Dive: The mathematics of placement, balance and hit ratioShow
Why modulo moves almost everything. With hash mod N, a key stays where it is after a resize to N + 1 only when h mod N = h mod (N+1). For uniformly distributed h, this holds for about 1/(N+1) of keys, the ones whose hash falls in the low part of each block of N(N + 1) values. So the fraction that moves is N/(N+1): 91% for 10 to 11 nodes, 98% for 50 to 51. Removing a node is symmetric. Any scheme in which a node's identity enters the formula for every key has this problem.
Why consistent hashing moves about 1/N. On a ring with N nodes, each with V virtual points placed at random, a new node's V points each take over the arc just before them. The expected total of those arcs is 1/(N+1) of the ring, which is exactly the share the new node should own. No scheme can move less and still end up balanced. Removing a node moves only its own 1/N.
How virtual nodes fix balance. With one point per node, a node's share of the ring is the gap before its point. The gaps behave like exponential random variables with mean 1/N, so their standard deviation is also about 1/N: a node's load routinely differs from the average by 100%. With V points per node, a node's share is the sum of V such gaps. Its relative standard deviation falls to about 1/√V: 10% at V = 100, about 7% at V = 200. The maximum across N nodes is a few standard deviations higher. That is why systems use 100-256 virtual nodes per server. The memory cost is N × V ring entries, for example 16 × 256 = 4,096 points, which is negligible. The lookup costs one binary search.
Why fixed slots are balanced by choice. With S slots and N nodes, an operator can assign ⌊S/N⌋ or ⌈S/N⌉ slots to each node, so key-count balance is exact up to the variation within slots. With 16,384 slots and 16 nodes, each slot holds about 61,000 keys of our billion, and the law of large numbers makes slots nearly identical in size. Moving one slot moves 1/16,384 of the data, about 60 MB here, which is a convenient unit for paced migration.
Why 16,384 slots? Redis's author has explained that each cluster heartbeat carries a bitmap of the sender's slots. 16,384 bits is 2 KB, small enough to send often, and it is still far more slots than a cluster would ever have nodes.
Hit ratio and cache size: why a small cache works. Web popularity is usually heavy-tailed and often modelled as Zipf: the i-th most popular item is requested with probability proportional to 1/i^α, with α near 1. With α = 1 and N items, a cache holding the top C items hits about H(C)/H(N) of requests, where H is the harmonic number, roughly ln C + 0.58. Worked example: N = 10^9 items and a cache of C = 10^8, 10%:
H(C)/H(N) ≈ (18.42 + 0.58)/(20.72 + 0.58) ≈ 0.89
So 10% of the items gives about 89% of the hits, and doubling the cache to 20% raises the hit ratio only to about 92%. This curve explains three things. Caches are cheap compared with databases. Capacity planning should target the knee of the curve. And small improvements in eviction policy, which effectively give the cache a better C, are worth real money at scale.
For LRU specifically, the "Che approximation" (from Hao Che, Ye Tung and Zhijun Wang's 2002 work on hierarchical web caches) predicts hit ratios accurately. It models each item as staying in the cache for a characteristic time T_C after its last request, and solves for the T_C at which expected occupancy equals cache size. It is the standard tool for answering "what hit ratio would a 2 TB cache give?" without building one.
The value of each hit-ratio point. Suppose there are 1M reads per second, and the database costs about $X per 10k reads per second of capacity. Moving from a 95% to a 96% hit ratio cuts database reads from 50k to 40k per second, 20% less database capacity, for maybe 10% more cache memory. Always express eviction or sizing changes as database load. That is the language in which caches pay for themselves.
Replication lag and loss window. With asynchronous replication, the data lost at failover is about the write rate times the replication lag. At 5k writes per second per shard and 2 ms of lag, about 10 writes are lost. Even at 1 second of lag during a stall, it is about 5,000 entries, which turn into misses or stale reads bounded by TTL. Stating this number lets an interviewer judge whether asynchronous replication is acceptable. For a cache, it nearly always is.
Failover time budget. The unavailability per failure is detection timeout + election + client discovery, roughly 5 s + 1 s + 2 s = about 8 s for one shard's keys. A 99.99% target allows about 260 seconds a month, so about 30 such single-shard failovers a month fit within it. And since each affects only 1/16 of the keys, the request-weighted budget allows far more. This arithmetic tells you whether to invest in faster detection or in fewer failures.
Deep Dive: Real distributed caches and what they teachShow
Memcached. Brad Fitzpatrick created Memcached in 2003 for LiveJournal. It is deliberately simple: a multi-threaded server with a slab allocator, LRU eviction (now segmented LRU, with background crawlers for expired items), and no replication, persistence or clustering in the server. All distribution logic lives in the clients, which use consistent hashing (the ketama scheme popularised it) or in proxies. That simplicity is why it scales so well per node and why it has lasted. It also shows the design principle of keeping servers dumb and putting distribution in the client or a proxy.
Facebook's memcache tier. "Scaling Memcache at Facebook" (NSDI 2013) describes a deployment handling billions of requests per second. Lessons from it appear throughout this page:
- Leases fix stale sets and stampedes.
- Gutter pools absorb failures without rehashing onto healthy nodes.
- mcrouter routes and fans out.
- Separate pools isolate workloads with different churn, so a high-churn key family does not evict a valuable low-churn one.
- Regional replication happens through invalidation from the MySQL commit log (mcsqueal), not through cache-to-cache replication.
- Cold cluster warm-up lets new clusters read from warm ones.
- The paper also notes that the cache was used as a demand-filled look-aside cache, which is cache-aside at enormous scale, with the database firmly as the source of truth.
Redis Cluster. It has 16,384 slots, a gossip cluster bus, majority-confirmed failure detection (PFAIL then FAIL), epoch-based failover voting and replica migration. Clients are smart and follow MOVED and ASK. Execution is single-threaded per node, so atomic scripts and data structures are cheap, but slow commands hurt. It shows the "no external coordinator" design in practice. Kyle Kingsbury's Jepsen analyses showed that Redis's earlier replication and failover setups, built on Sentinel, could lose acknowledged writes under partitions. That is fine for a cache and a real danger for anyone treating Redis as a database of record. It is a good reminder that "replicated" does not mean "durable".
Netflix EVCache. EVCache is built on Memcached with a client library that writes each item to a copy in every availability zone and reads from the local zone, falling back to other zones on a miss. It trades extra memory (a copy per zone) for zone-local reads and survival of zone failures. It also shows how a cache tier can be made highly available without server-side replication.
Managed and newer options. Amazon ElastiCache and Google Memorystore run Redis or Memcached as a service. Amazon MemoryDB adds a durable multi-AZ transaction log, so a Redis-compatible store can be a primary database: a different trade-off, paying write latency for durability. Newer engines such as Dragonfly and KeyDB revisit Redis's single-threaded design with multi-threaded or shared-nothing architectures, to use all of a machine's cores in one process. In-process caches such as Caffeine (Java, W-TinyLFU) are where much of the recent research on eviction policies has landed. They are the natural L1 in front of a distributed cache.
Lessons that keep coming up:
- The database is the real thing being protected. Every cache design decision should be judged by what it does to database load during normal operation and during cache failures, resizes and cold starts.
- Hot keys are not rare. Every large consumer service eventually has a key that gets a large share of all traffic. Automatic detection plus L1 caching is part of the standard design, not an emergency add-on.
- Invalidation is the hard part. The bugs are in the races between reads, writes and deletes, not in the hash map. Leases, versions and CDC-driven deletes are worth their complexity.
- Keep the server simple and the protocol small. Rich features such as scripting and large data structures are powerful, but every slow command is a tail-latency incident waiting to happen on a shared, single-threaded shard.
- Treat cache capacity like database capacity. If the database cannot survive the cache being cold, then the cache is effectively a database, and it needs the same standard of availability and change management.
Deep Dive: Building, testing and operating the cache from launch to large scaleShow
Stage 1: one pool, a few nodes. A managed Redis or Memcached with replicas, smart clients, cache-aside with TTL jitter, allkeys-lru, and dashboards for hit ratio, evictions and memory. Most teams should stop here and not build their own cache. The design work is in key schemas, TTLs and invalidation, not in the server.
Stage 2: growth. Move to a cluster with slots and live resharding. Add hot-key detection and L1 caches for the hottest key families. Add single-flight refills and negative caching. Put CDC-based invalidation behind write paths that are sensitive to correctness. Split pools by workload: sessions, catalogue, feeds, counters.
Stage 3: large scale or a custom platform. Multiple regions with invalidation broadcast. Leases. Gutter pools or EVCache-style zone copies. A proxy tier for fleets of tens of thousands of clients. Per-tenant quotas and chargeback. Policy tuning (LFU, TinyLFU admission) by replaying recorded traces. This is where a company like Facebook or Netflix ends up. It is reasonable only when cache cost and reliability are large enough to need their own team.
Testing.
- Unit and property tests for the node. Random sequences of get, set, delete and TTL operations, checked against a simple reference model. Assert LRU order, byte-accurate memory accounting, and that expired entries are never returned.
- Concurrency tests. Many threads hammer the same keys, checking for torn values, lost CAS conflicts and lock contention.
- Partition and failover tests in the spirit of Jepsen. Partition a primary from the majority, check that it stops taking writes within the timeout, that exactly one primary per slot exists after healing, and that the window of lost writes matches the analysis.
- Resharding tests under load. Move slots while running a production-shaped read and write mix, asserting near-zero errors and bounded latency impact.
- Failure drills in production canaries. Kill a node, fill a node to its memory limit, inject 20 ms of latency into one shard. Verify that client timeouts, breakers and fallbacks behave as designed.
What to measure, per pool and per node.
- Hit ratio, overall and per key prefix. The per-prefix view finds the one key family whose TTL is too short.
- Evictions, split into expired and non-expired. Non-expired evictions mean memory pressure.
- Memory: used, resident and the fragmentation ratio.
- Operations per second and p50/p99/p999 latency per command type.
- Replication: offset lag and full-resync counts.
- Connections and slow log entries.
- Top keys by operations and by bytes.
- On the client side: timeouts, retries,
MOVEDrates (high after resharding, near zero in steady state), L1 hit ratio and single-flight wait times.
Cost. RAM is the dominant cost. At cloud prices, 1.2 TB of cache memory with replicas costs a few thousand to tens of thousands of dollars a month, depending on instance type and region. Compare that with the database capacity it replaces: a database fleet sized for 1M reads per second with no cache would typically cost several times more. It would also have worse tail latency. The levers for reducing cost are:
- compact encodings and compression for large values,
- better eviction, which gives a higher hit ratio with the same memory,
- right-sized TTLs, so the cache does not keep data nobody reads,
- dropping replicas for pools that can tolerate cold misses.
Variants interviewers ask about.
- "Make it durable." Add an append-only log with periodic snapshots, or synchronous replication to a quorum. At that point it is a key-value store, and the design moves towards Quorums and Leaderless Replication and the key-value store case study.
- "Support rich data types." Sorted sets, hashes and streams, as in Redis. These need careful limits on command cost, because they introduce operations that are not O(1). See Redis in Practice.
- "Cache computed results, not rows." Use a key derived from every input parameter, like a search-results cache keyed by query plus filters. Size and TTL are driven by how often the inputs repeat.
- "Use it as a distributed lock or rate limiter." These are possible on the same infrastructure, but correctness-sensitive. See Distributed Locks and the rate limiter case study.
Deep Dive: The client library, protocol and multi-get fan-outShow
Most of a distributed cache's behaviour is decided in the client library, not the server. The client chooses the node, sets timeouts, retries, batches, serializes and compresses. A well-built server behind a careless client still causes outages. This deep dive covers the client side.
Wire protocol. Redis speaks RESP, a simple text-framed protocol with length prefixes. RESP3, added in Redis 6, includes richer types and push messages, which client-side caching invalidations use. Memcached has a classic text protocol, a binary protocol that is now deprecated, and the newer meta protocol (mg, ms, md and others, from the 1.6 line). Meta commands put flags on each request, for example "return the CAS value", "return the remaining TTL" or "mark stale and win the recache". So stale-while-revalidate and lease-like behaviour can be built without extra round trips. A good rule: choose a protocol where one request can carry everything a refill decision needs (value, version, TTL left), so the client never needs a second round trip to decide what to do.
Connections. Each client process keeps a small pool of persistent TCP connections to each node. Opening a connection per request costs a handshake (about 0.5 ms in the same data centre, more with TLS) and burns server file descriptors. The numbers matter at fleet scale: 5,000 application hosts × 32 processes × 2 connections × 16 nodes is about 5 million connections. Each node would hold more than 300,000 sockets, using memory for buffers and making failover reconnect storms painful. Three fixes:
- Multiplexing. One connection per node per process, with pipelined requests matched to responses in order (RESP) or by an opaque request id (Memcached meta).
- A sidecar or proxy such as mcrouter or twemproxy per host, which collapses all local processes into one set of upstream connections.
- Jittered reconnect backoff, so a node restart does not get 300,000 SYNs in the same millisecond.
Timeouts, retries and budgets. A cache GET normally takes 0.2-1 ms. The client timeout should be a small multiple of p99, for example 5-20 ms, not the 1-2 second default that many libraries ship with. A cache that answers slowly is worse than one that is down: a request waiting 2 s for the cache holds a thread, a database connection slot and a user. Treat a timeout as a miss, and decide per key family whether to fall back to the database. Retries are dangerous here. A retry storm against an overloaded shard makes it more overloaded. Use one retry at most, only on a different replica, and only inside a global retry budget, for example retries limited to 10% of requests. Behind that sits a circuit breaker per node. After a burst of errors the client stops calling that node for a short period and treats its keys as misses, protected by the database-side limits described in the failure section.
Serialization and compression. The cache stores bytes, so the client decides the encoding. Compact binary formats such as Protocol Buffers, MessagePack or Avro typically shrink values to 30-60% of their JSON size and parse faster. Compress only values above a threshold, for example 1 KB, with a fast codec such as LZ4, Snappy or Zstandard at a low level. Compressing tiny values wastes CPU and can make them larger. Always put a format version in the value or the key, for example user:v3:42. A deploy that changes the object schema then reads only new-format entries, and old entries age out by TTL. Without this, a rolling deploy has old and new code reading each other's entries and crashing on parse errors. Bumping the version is also the cheapest form of mass invalidation, because the new code simply stops looking at old keys.
Key design. Keys should be short, structured and predictable: {type}:{version}:{id}[:{field}]. Short matters because the key is stored in full with every entry. A 60-byte key on 1 billion entries is 60 GB just for keys. Never put unbounded user input directly in a key without hashing it, because both length and injection-like surprises are possible. Use hash tags, for example {user:42}:profile and {user:42}:prefs, only when a multi-key operation truly needs co-location, because tags concentrate load on one slot.
The multi-get problem. Pages often need many keys at once, such as 100 friends' profiles. The client groups keys by owning node and sends one batched request per node, in parallel. This has three consequences:
- Latency is the slowest node's latency. With 16 nodes involved, the multi-get's latency is the maximum of 16 samples. If each node has a 1% chance of a 10 ms stall, the batch stalls 1 − 0.99^16 ≈ 15% of the time. This is the tail-at-scale effect from the tail latency deep dive, and it is why hedging and per-node timeouts matter even more for batches.
- Adding nodes does not reduce per-node request rate for wide batches. If every page view fetches keys spread over all nodes, each node receives one request per page view no matter how many nodes there are. More nodes reduce bytes per request, but not requests per node. Operators sometimes call this the multi-get hole. The fixes change placement rather than capacity. Replicate the whole pool and send each batch to one complete replica set, so it touches 1/R as many nodes in total. Or co-locate keys that are fetched together with hash tags or by sharding on a shared entity id.
- Incast. Many nodes answering one client at the same moment can overflow the switch buffer for that client's port, causing packet loss and TCP retransmit timeouts measured in hundreds of milliseconds. The Facebook memcache paper describes the fix: a sliding-window flow control in the client that limits outstanding requests, similar to TCP congestion control. That paper also notes that Facebook clients sent GETs over UDP to cut connection overhead, and treated a lost or late UDP reply as a miss.
Worked example: one product page. The page needs 1 product, 40 recommendation cards and 1 cart, so 42 keys. The 40 cards spread over all 16 nodes, so the client sends 16 parallel batches. With a p50 of 0.3 ms per node and a p99 of 2 ms, the batch's p50 is close to the per-node p90 to p95, about 0.8 ms. Its p99 is close to the per-node p99.9, about 5 ms. Two changes cut the tail roughly in half: hedging the slowest 5% of per-node requests to a replica, and caching the top 1,000 products' cards in an L1 with a 2-second TTL.
What belongs in the library vs a proxy. A library is fastest, with no extra hop, and works best when there are few languages to support. A proxy adds about 0.1-0.3 ms per request. In return it centralises routing, pooling, metrics, shadowing and migrations for every language. Many large fleets use both: a thin library speaking to a local sidecar proxy. That gives one routing implementation, near-zero network cost, and connection counts that scale per host instead of per process.
Common mistakes in interviews and in production.
- Choosing
hash mod Nand only discovering the remapping storm at the first resize. - Default client timeouts of seconds. One slow shard then exhausts every application thread pool.
- No TTLs on "permanent" keys. Memory then fills with entries nobody reads, and eviction starts dropping the useful ones.
- Synchronized TTLs. Entries written by a nightly batch all expire in the same second.
- Treating replica reads as consistent, then debugging "read your own write" failures.
- Running
KEYS *or hugeHGETALLcalls on a shared single-threaded node. - Sizing the cache for average load instead of the cold-start case. The database must survive the day the cache restarts empty.
Naming these unprompted, with the fix for each, is one of the clearest senior signals in this interview.
Key Takeaways#
- A node is a hash map plus eviction metadata. Exact LRU with a doubly linked list is the textbook O(1) answer. Production caches use sampled LRU, CLOCK, segmented LRU or LFU with admission for concurrency and scan resistance. TTLs combine lazy and sampled active expiry. Theory in Cache Eviction and Invalidation.
- Partition with consistent hashing or fixed slots, never
mod N. Resizing should move about 1/N of the keys. Virtual nodes or many slots give structural balance. See Consistent Hashing and Partitioning and Sharding. - Replicate asynchronously and fail over with majority agreement and epochs. Accept the small loss window, because the database is the source of truth. Fencing with epochs prevents split brain.
- Membership is the hard distributed-systems core. Gossip for liveness with SWIM-style suspicion, consensus or epoch votes for ownership, and timeouts sized to the availability budget.
- Hot keys need their own design. L1 client caches, replica reads and salting for read-hot keys. Splitting and coalescing for write-hot keys. Automatic detection for all of them. See Pattern: Scaling Reads.
- Protect the database from the cache's failures. Use TTL jitter, single-flight refills, leases, CDC invalidation, warm-up and gradual resizing. See Cache Failure Modes: Stampedes, Hot Keys and Penetration.