What you'll learn: By the end of this lesson you will be able to size a shared cache cluster from memory rather than from request rate, choose between client-side, proxy and redirect routing, explain why a fixed slot map beats
hash mod n, say what asynchronous replication costs a cache, design for stale sets, hot keys and cold replacements, and defend the design in an interview.
A hotel concierge keeps a clipboard of the answers guests ask for most: the taxi number, the breakfast hours. Reading it takes a second; phoning a department takes minutes. The clipboard is sometimes wrong, so the concierge crosses out old entries and, once it is full, rubs out the answers nobody has asked about lately. Now imagine a hundred concierges sharing a hundred clipboards. Which clipboard holds which answer, and who tells the others when one changes?
That is the design problem of a distributed cache. This lesson is an educational reference design, not the verified internal architecture of any company. It names Redis and Memcached as examples of products and cites two published papers for what they report, and every number in the sizing is an illustrative assumption. The deep treatment of individual pieces lives in other lessons: consistent hashing, cache invalidation, eviction policies, cache stampede and hot keys and Redis and Memcached. This one puts them into a single design and shows how the decisions interact. The case-study format is introduced in the advanced overview.
The core idea
A distributed cache is a memory-sized, loss-tolerant copy of data that lives somewhere else. Three consequences shape every decision:
- Memory sizes the cluster, not request rate. One cache node can usually answer far more requests than it can hold bytes. You add nodes because the data does not fit, and because you want a failure to take away a slice of the cache rather than all of it.
- Losing an entry is allowed, serving a wrong one is the danger. The source of truth is the backing store, so a cache may drop any entry at any time. What hurts is an entry that stays after the data changed. Most of the hard parts (invalidation races, lost deletes on failover, long TTLs) are about stale data, not missing data.
- The cache protects the backing store. Every miss becomes a read on a more expensive system. A cache that falls over, or restarts empty, hands its whole load to the database at once.
Three illustrations run through the lesson: a minimal example (one key's journey through the read path), a realistic example (the ShopStream catalogue and session cache) and a failure example (a primary dies and loses an invalidation).
Requirements and scope
Functional
get,setwith a time to live (TTL),deleteand a batchedgetof many keys.- Optional conditional operations: set only if absent, set only if the version is unchanged, atomic counters.
- Values are opaque bytes up to a modest size limit (assume 1 MB).
Out of scope
- Durable storage. Use the cache as a copy, not as the only place data lives (see cache strategies for read-through, write-through and cache-aside).
- Rich data structures (see Redis data structures).
- Cross-region consistency: one region only.
- A CDN or browser cache (see cache layers).
Non-functional (illustrative assumptions)
- Read latency at the client: p99 under 5 ms.
- Availability: a single node failure must not stop reads for more than a short window, and must not take the backing store down.
- Scale out without a miss storm: adding a node must move a small fraction of keys.
- Bounded staleness: a stale entry may live at most as long as its TTL, and the TTL is chosen per data type.
Back-of-envelope estimate
Every figure below is an illustrative assumption. See back-of-envelope estimation for the method.
| Quantity | Assumption | Result |
|---|---|---|
| Peak read rate | 200,000 per second | |
| Peak write and delete rate | 20,000 per second | One tenth of reads |
| Live keys | 500 million | |
| Average value plus per-entry overhead | 2 KB plus 100 bytes | 2.1 KB per entry |
| Data size | 500 million x 2.1 KB | about 1.05 TB |
| Usable memory per node | 50 GB (assumption) | 21 primaries minimum, about 25 with headroom |
| Replication | One replica per primary | about 50 nodes in total |
| Per primary | 200,000 x 2 KB = about 400 MB per second in total, over 25 primaries | about 16 MB per second each |
| Backing-store load at a 95% hit ratio | 5% of 200,000 | 10,000 reads per second |
| Backing-store load at a 90% hit ratio | 10% of 200,000 | 20,000 reads per second |
Two readings matter. Memory is the binding constraint: 25 primaries hold the data while traffic per node is small, and replicas buy availability and read capacity, not storage. And five points of hit ratio double the load on the database, so eviction policy, TTLs and key design are capacity decisions, not tuning details.
API design
The client library is the API. Over the wire it speaks a simple request and response protocol; the design does not depend on which.
GET key -> value | miss
MGET key1 key2 ... -> values and misses, in request order
SET key value ttl=300 -> ok (ttl in seconds; every key has one)
SET key value ttl=300 nx -> ok | exists (set only if absent)
CAS key value version -> ok | conflict (set only if the version still matches)
DELETE key -> ok | not_found
INCR key by -> new value (atomic counter)
Three rules keep the contract small and safe:
- Every key carries a TTL. A TTL turns "invalidate on every write" from a correctness requirement into a best effort, because anything the invalidation misses still dies on schedule. It also bounds how long a lost delete (see the failure modes) can hurt.
MGETis a first-class call. A page often needs many keys, and the client library splits oneMGETby owning node and sends the pieces in parallel. A slow node then delays only the keys it owns (see tail latency).- Misses are not errors. The client tells "not there" from "node unreachable"; the second needs a fast fallback, not a retry against the same node.
Data model
A cache entry is small: key, value bytes, an absolute expiry time, a version for conditional writes, and eviction bookkeeping. The interesting data is the map from key to node, which lives in a small control plane.
Figure 1. The slot map is the only thing that must be shared. How to read this: a key hashes to a slot, a slot belongs to one shard, a shard has one primary and some replicas. The epoch tells a client whether its copy of the map is old. Entries themselves are not in the control plane.
High-level design
Figure 2. The cache sits beside the database, not in front of it. How to read this: the client library holds the slot map and sends each request straight to the owning primary. A miss makes the application read the backing store, then fill the cache. Replicas copy their primary asynchronously.
The routing decision in the figure (client-side, with a map) is one of three, discussed in the next section. The read path itself, for the minimal example of one key:
Figure 3. Minimal example: one key, one miss. How to read this: the cache never reads the database itself in this pattern. The application does, and writes the result back. The next reader of the key hits the cache until the TTL ends or the entry is evicted.
Deep dive 1: partitioning and routing
Why not hash mod n. Placing a key on node hash(key) mod n is simple, but when n changes almost every key changes owner, and a cache that moves nearly all of its keys has just emptied itself. The consistent hashing lesson measures it in a lab: going from 10 to 11 nodes moved 91.12% of 100,000 keys with modulo placement, against about 1/11 for a ring.
Two ways to get "move only a few keys".
- A ring with virtual nodes. Dynamo's paper treats the hash range as a ring: each node takes positions on it, a key goes to the first node clockwise from its position, and a node arriving or leaving affects only its neighbours. Virtual nodes (several positions per node) even out the load.
- A fixed slot map. The Redis Cluster specification divides the key space into 16384 slots with
HASH_SLOT = CRC16(key) mod 16384. Each master serves a subset of slots, and moving a slot between nodes is how the cluster rebalances. The hash never changes; the table from slot to node does.
For a cache, the slot map makes rebalancing an explicit, incremental operation, and the map is a small versioned object every client can fetch and compare. A ring needs every client to agree on a node list, and clients that disagree route the same key to different nodes.
Three places to route.
| Routing option | How it works | Use when | Cost |
|---|---|---|---|
| Client-side, with a slot map | The library hashes, looks up the owner and talks to it directly | You control the clients and want the fewest hops | Every client needs the map and library upgrades are slow to roll out |
| Proxy tier | Clients talk to a proxy fleet that routes and hides cluster changes | Many languages, or you need to change topology without client releases | An extra hop and a fleet to run |
| Redirect from the server | A node answers "not mine" and names the owner | Clients are thin or the map changes under them | An extra round trip while the client's map is stale |
The Redis Cluster specification describes the third option: a node that does not own the slot replies with a MOVED error naming the slot and the endpoint that serves it, and the client reissues the query there. Real clients combine the first and third: a map for speed, MOVED as the signal that it is old. The Facebook memcache paper describes a proxy, mcrouter, that presents the memcached interface and routes requests, partly so clients stay stateless.
Figure 4. A decision, not a ranking. How to read this: the first branch is about who can upgrade clients. Every branch ends at the same last step, because a map that is only fetched sometimes is stale sometimes.
Multi-key operations. A batched read touches many slots, so the client splits it per owner and runs the parts in parallel. For operations that must stay on one node, Redis Cluster hash tags hash only the {...} part of a key, so {user:42}:cart and {user:42}:profile share a slot. Use them sparingly: they concentrate keys on purpose, which is how a hot tag becomes a hot slot (see hot partitions and resharding).
Deep dive 2: replication, failover and what a cache may lose
Each primary has one or more replicas, in a different failure zone. Replication is asynchronous: the primary acknowledges the write and copies it afterwards. The Redis Cluster specification is direct about the consequence: there are windows in which acknowledged writes can be lost. A write can reach the master, the master can reply to the client, and then the master can fail before the write reaches its replicas; if a replica is promoted, the write is gone. It also notes that nodes do not wait for other nodes' acknowledgement unless a WAIT command is used.
For a database that is a serious limit. For a cache it is usually acceptable, with one exception that this case study exists to point out:
- A lost set is harmless. The next reader misses and refills from the source of truth.
- A lost delete is not. The invalidation that told the cache "this price changed" disappears with the old primary, the promoted replica still holds the old price, and the entry stays wrong until its TTL ends.
So three rules follow. Make TTLs the safety net for every entry, sized by how long a stale value is tolerable for that data. Do not use the cache as the only place a fact lives, so a lost write is repairable. And have a "purge by namespace or version" escape hatch: if keys carry a version prefix (catalogue:v7:product:42), a failover incident can be repaired by bumping the version, which makes every old key unreachable at once instead of waiting for TTLs.
Failover is a cold start in disguise. When a primary fails, a replica takes over its slots. That replica has most of the data, so the loss is a small tail of recent writes. But a node that is replaced with an empty one has nothing, and its whole share of traffic (about 1/25 of reads in our sizing) misses at once. The Facebook memcache paper describes its answer: a small set of spare machines, called Gutter (about 1% of the servers in a cluster), takes over for failed servers. A client that gets no response asks the Gutter pool, and if that misses too it fills the entry there, with a short expiry, instead of sending everything to the database. The paper states the trade: Gutter limits load on the backing services at the cost of slightly stale data.
Reads from replicas add read capacity and make staleness worse, because a replica trails its primary. Allow them only for data whose TTL already tolerates lag.
Deep dive 3: memory, eviction and TTLs
A full cache must choose what to drop. Each node decides locally, with no coordination, which is what keeps the design simple and fast.
The Redis documentation lists the policies you choose from when maxmemory is reached: noeviction (return an error on writes that need memory), allkeys-lru and allkeys-lfu (evict the least recently or least frequently used keys), allkeys-random, and the volatile-* variants that only consider keys with a TTL, including volatile-ttl, which evicts keys with the shortest remaining TTL. Its rule of thumb is that allkeys-lru is a good default when a subset of elements is accessed far more often than the rest. Two details matter for the design:
- LRU is approximated. Redis samples a small number of keys and evicts the one with the longest time since last access, instead of keeping an exact global order, because exact LRU costs more memory. The sample size is configurable (
maxmemory-samples). You do not need to model a perfect LRU: the LRU lesson shows the exact structure, and the point here is that a production cache trades exactness for memory and speed. - Replication and persistence buffers are not counted against
maxmemory. The documentation recommends leaving some RAM free for them, because counting them could create a feedback loop of evictions. In capacity terms, "50 GB usable" in our estimate must already be net of those buffers and of fragmentation.
Mixing different kinds of data in one pool is a known hazard. The memcache paper describes partitioning servers into pools: a small pool for keys that are accessed often but cheap to miss, and a large pool for keys that are rarely accessed and expensive to miss. It reports that low-churn keys that are still valuable can be evicted before high-churn keys that are no longer being accessed, and that separate pools prevent this. The design consequence: one pool per access pattern, each with its own sizing and policy, rather than one big shared pool.
Deep dive 4: invalidation, stale sets and leases
With cache-aside, the application reads the database on a miss and writes the result into the cache, and on a write it updates the database and deletes the cache entry. The failure is a race on the delete:
- Reader A misses and reads the old value from the database.
- Writer B updates the database and deletes the cache entry.
- Reader A, delayed, sets the old value into the cache.
The entry is now stale and nothing will correct it before the TTL. The memcache paper calls this a stale set: a value that does not reflect the latest data, caused by concurrent updates reordered. Its fix is a lease: when a client misses, the cache returns a 64-bit token bound to the key; the client must present the token with its set; and the server rejects the set if the token was invalidated in the meantime, for example by a delete. The paper compares it to load-linked and store-conditional.
Figure 5. Failure example: the stale set that a lease stops. How to read this: the delayed writer carries evidence of when it looked. The cache compares that evidence with later deletes and refuses the write.
Where leases are not available, the practical substitutes are shorter TTLs on data that is read often and changes often, a version number in the key or value so that an older value never overwrites a newer one (the CAS operation in our API), and write paths that publish an invalidation event rather than relying on one delete (see cache invalidation for the options and their failure modes).
Deep dive 5: hot keys and stampedes
Two different problems both look like "one key is too popular".
The stampede. A popular key expires or is deleted, and hundreds of clients miss at once and all query the database for the same value. The lease mechanism in the memcache paper also addresses this: each server regulates how often it hands out tokens, by default one token per key every 10 seconds in that paper's configuration, and a client that arrives within the window is told to wait briefly and retry, by which time the first client has usually set the value. The paper reports, for one set of keys prone to thundering herds over one week, a peak database query rate of 17,000 per second without leases and 1,300 per second with them. That is the paper's measurement on its own workload, not a number to reuse. Other defences are in cache stampede and hot keys: coalesce identical requests inside a process, refresh popular entries before they expire, and jitter TTLs so entries do not expire together.
The hot key. One key gets more traffic than its owning node can serve, however well the slots are balanced, because a key lives on exactly one primary. Options, in order of cost:
| Approach | Use when | Cost | Alternative |
|---|---|---|---|
| Tiny local cache in each app server (seconds of TTL) | Read-heavy key, brief staleness is fine | Memory per app server, short-lived inconsistency | Replicated key copies |
Replicate the key under several names (key#0 to key#k) and read a random copy |
A known hot key, read-mostly | Invalidation must delete every copy | Local cache |
| Serve reads from replicas | Node CPU or bandwidth is the limit | Replication lag | Replicate the key |
| Split the key's contents (shard a counter into many) | Hot counters | Aggregation on read | Approximate counts |
The memcache paper also replicates a category of keys within a pool when the application fetches many keys at once, the data fits on one or two servers and the request rate exceeds what one server can handle, with invalidations delivered to all replicas.
Reference deployment topology
Figure 6. Where each part lives. How to read this: primaries and replicas sit in different zones so one zone loss leaves a full copy. The slot map is small and replicated separately from the data. The proxy tier is optional; without it the client library talks to primaries directly.
Bottlenecks and scaling
- Memory first. Grow by adding shards and moving slots a few at a time, watching hit ratio and backing-store miss rate. Never rebalance in the middle of a promotion.
- Per-node CPU and network. Rare in this sizing (about 16 MB per second per primary), common with tiny values at extreme rates or with large values. Watch per-node request rate and bytes, not the fleet average.
- The control plane. If the slot map store is down, clients keep working on the map they have and refresh on the first redirect.
- The backing store is the real capacity limit. Plan it for the cache's worst day, a cold or half-empty cache (see capacity planning).
- Connection counts. Every app server opens connections to every shard; the product grows fast, which is one reason to add a proxy tier.
Failure modes
| Failure | Effect | Mitigation |
|---|---|---|
| One primary dies | Its slots are unavailable until a replica is promoted | Replica in another zone, fast detection, clients treat errors as misses with a short timeout |
| Failover loses recent writes | Lost sets are harmless, lost deletes leave stale entries | TTL on every key, version prefixes for a bulk purge, repair events |
| Node replaced with an empty one | Miss storm on its slice of keys | Warm from a replica, Gutter-style spare pool, rate-limit refills |
| Stale slot map in clients | Wrong node, redirects or misses | Epoch in the map, refresh on redirect, bounded retries |
| Stampede on a hot key | Database overload | Leases or request coalescing, jittered TTLs, refresh-ahead |
| Hot key saturates one node | High latency for every key on that node | Local cache, key copies, replica reads |
| Cache pollution by a scan | Hit ratio drops | Separate pools, LFU-style policy, no caching of one-time reads |
| Network partition | Clients on one side see errors | Timeouts, fall back to the backing store with a concurrency cap (see load shedding) |
Trade-offs worth stating
| Decision | Option A | Option B | How to choose |
|---|---|---|---|
| Routing | Client library with slot map | Proxy tier | Library if you control clients, proxy for many languages or frequent changes |
| Placement | Fixed slots | Ring with virtual nodes | Slots for explicit, incremental rebalancing |
| Consistency | Short TTL only | Delete on write plus leases or versions | Short TTL if staleness is cheap |
| Pools | One shared pool | One pool per access pattern | Separate as soon as one pattern hurts another |
Interview cheat sheet
| Step | What to say |
|---|---|
| Requirements | get, set with TTL, delete, batch; loss-tolerant; bounded staleness |
| Estimate | Memory sizes the cluster (about 25 primaries, 50 nodes with replicas); hit ratio sizes the database |
| Design | Client library or proxy, slot map, shards with async replicas, backing store beside the cache |
| Deep dives | Slots versus ring, lost deletes on failover, stale sets and leases, hot keys |
| Failures | Primary loss, cold replacement, stale map, stampede |
| Trade-offs | Routing location, consistency method, pools |
Build it
This lesson has no lab of its own: it composes pieces that have labs, and no part of it has been run here. Run the labs where they live. The consistent hashing lesson has Java labs that measure how many keys move under modulo, ring and rendezvous placement. The LRU cache lesson builds the eviction structure, and cache stampede and hot keys has a lab for request coalescing. A good exercise is to wire them together: a ring-routed pool of in-memory LRU caches, driven by a skewed key sequence, counting hit ratio before and after a node is added.
In practice: the ShopStream catalogue and session cache
This is the realistic example, on the course's running example. Every number is an illustrative assumption, and ShopStream is a teaching scenario, not a company.
This is a realistic scenario, not a case history.
The situation
ShopStream's browsing path peaks at about 2,300 requests per second (shared course figure). Assume each page view makes about 10 cache reads (product, price, stock, promotion, session), so the cache sees about 23,000 reads per second at peak. The catalogue is 100,000 products at about 4 KB each, roughly 400 MB. Assume 200,000 concurrent sessions at 2 KB each, roughly 400 MB. Everything fits in under 1 GB.
Starting architecture
One cache node holds everything: catalogue entries, price lists and sessions, in one pool, with a primary and one replica. The application reads with cache-aside and invalidates on a price change by deleting the key.
Options considered
| Option | Benefit | Cost | Risk |
|---|---|---|---|
| A. Keep one pool on one primary | Nothing to change | None | A scan of rarely seen products can evict sessions, and a primary loss loses everything |
| B. Shard the catalogue across a cluster for throughput | Looks scalable | Operational cost of slots and clients | Throughput was never the limit: the size sizing shows under 1 GB and 23,000 reads per second |
| C. Two pools: an evictable catalogue pool and a separate session pool, each with a replica in another zone | Isolation of eviction and failure | Two small clusters to run | Two things to monitor |
The decision
Option C. The sizing method above is the same, but the answer is different: the limit at this scale is isolation, not capacity. Sessions are state, not a cache, so they get their own pool where an eviction means a forced logout, with a conservative policy and alerting on any eviction at all. The catalogue pool uses allkeys-lru as the default for skewed access, with TTLs of minutes for prices and longer for descriptions. Each pool has a replica in a different zone. A proxy tier and slot-based sharding are deferred until the data approaches a node's memory, which is a metric to watch, not a date.
Rollout and verification
Create the pools beside the old node and move readers pool by pool behind a flag. Watch hit ratio and evictions per pool (the session pool should show zero), backing-store read rate, replication lag and p99 cache latency. Rehearse a primary failover in staging and record how long the catalogue pool takes to return to its normal hit ratio.
The 2 a.m. failure
A merchant lowers a price. The application writes the database and deletes the catalogue key. At the same moment the catalogue primary fails and a replica is promoted; the delete had not reached the replica because replication is asynchronous (Figure 5 shows a different race, this is the lost-delete one). Shoppers keep seeing the old price on one product. The checks: the failover time against the time of the price update, and the TTL on the key. The mitigation is to delete the key explicitly and, if many keys changed near the incident, bump the catalogue version prefix so every old entry becomes unreachable. The lasting fixes are a TTL on prices short enough that the business accepts the worst case, an invalidation retried until acknowledged, and a post-failover job that re-invalidates recently changed keys.
Architect's notes
- Ask what the cache is protecting. Database reads call for a hit-ratio and miss budget; latency calls for a percentile. The answer changes how much you spend on replicas.
- Treat the TTL as part of the data contract. A TTL is how long a wrong answer can live. Write it next to the key family and get the product owner to sign it.
- Separate state from cache. Anything where an eviction is a user-visible bug (sessions, rate-limit counters) gets its own pool, policy and alerts, or a different store (see Redis and Memcached).
- Multi-region is a different problem. The memcache paper describes extra machinery for cross-region invalidation, including daemons that replay invalidations from the database commit log. Do not promise cross-region freshness without that design.
- Build the cold-cache drill before you need it. Empty one pool in a test and measure what the backing store sees.
Common mistakes
- Sizing by requests per second and ending up with ten times the nodes the data needs.
- Using
hash mod nand discovering during a scale-out that most keys moved. - Giving keys no TTL and relying on delete-on-write alone, so one lost delete lives forever.
- Mixing sessions, counters and cache entries in one evictable pool.
- Giving every key a 300-second TTL, so a whole family expires together and stampedes.
- Reading from replicas without deciding which data tolerates their lag.
Key takeaways
- Memory sizes the cluster; hit ratio sizes the backing store. A few points of hit ratio can double database load.
- Use a placement rule that moves few keys when the cluster changes: fixed slots with explicit rebalancing, or a ring with virtual nodes.
- Asynchronous replication means a cache can lose acknowledged writes. Lost sets are harmless, lost deletes are not, so every key needs a TTL.
- Stale sets come from reordered concurrent updates; leases or versioned writes stop them.
- Stampedes and hot keys are different problems with different fixes.
- A replaced node is a cold start. Keep state out of the cache pool.
Practice exercises
Exercise 1 (30 min). Redo the estimate for 100 million keys of 500 bytes, 80,000 reads per second and 8 GB usable memory per node. State which of memory and traffic binds.
Exercise 2 (45 min). A product key is read 40 times more than the next hottest. Using the hot-key table, choose an approach and say what invalidation looks like.
Exercise 3 (1 hour). Draw the timeline of the lost-delete failure and mark where a short TTL, a version prefix and a retried invalidation each act.
Exercise 4 (1 hour). Compare client-side routing and a proxy tier for five languages and weekly topology changes. List what breaks in each when the slot map store is down.
Related reading
- Consistent Hashing: the placement rule and the lab numbers.
- Cache Invalidation: options and their failure modes.
- Cache Strategies: cache-aside, read-through, write-through.
- Eviction Policies: LRU, LFU and TTL.
- Cache Stampede and Hot Keys: the miss storm and its damping.
- Redis and Memcached: the two products.
- Hot Partitions and Resharding: when one slot is too busy.
- ShopStream Stage 3: scale reads: the cache tier in context.
Official documentation
- Redis documentation, Redis cluster specification: slots,
MOVEDredirection, hash tags, asynchronous replication and write safety. - Redis documentation, Key eviction:
maxmemory, eviction policies, approximated LRU and LFU. - Nishtala et al., Scaling Memcache at Facebook (NSDI 2013): leases, pools, Gutter, replication within pools, regional pools.
- DeCandia et al., Dynamo: Amazon's Highly Available Key-value Store (SOSP 2007): section 4.2 on consistent hashing and virtual nodes.