What you'll learn: By the end of this lesson you will be able to say why a cache shared by many application servers differs from an in-process cache, describe what Memcached and Redis each store and how each spreads keys over several servers, explain what Redis replication, Sentinel and Cluster do and do not promise about acknowledged writes, predict what a node failure or a resize does to database load, and read the stale-after-rejoin failure in a client-side sharding stand-in lab that needs no cache server.
Picture an office where every employee keeps sticky notes at their own desk. Lookups are instant, but when the price list changes, thirty desks hold thirty opinions. Move the notes to a whiteboard in the corridor and everyone agrees, but each lookup is a walk and a blocked corridor leaves nobody able to read it. A distributed cache is that whiteboard. Put several in different corridors and a new question appears: which one holds which note?
The previous lesson covered the strategies on an in-process cache. This one moves the cache out of the process: what the two best-known servers store, how keys reach the right server, and what happens when a server goes away. Consistent hashing explains the ring used below. A Redis data structures lesson in the NoSQL module covers the types in depth (plain text until it is published).
Verified with Java 25, Spring Boot 4.1.2, the Redis, Memcached and Spring Data Redis documentation, read on 2026-12-01, and a lab whose nodes and client are stand-ins.
The core idea
A distributed cache moves entries out of the application process into servers that every instance shares. That buys one shared view and more memory than a process has, and costs a network hop on every lookup, a new failure mode (the node is down), and a placement problem (which node owns which key).
| In-process cache (Caffeine) | Distributed cache (Memcached, Redis) | |
|---|---|---|
| Lookup cost | A memory read | A network round trip |
| Other instances' writes | Not seen: one copy per process | Seen: one shared copy per key |
| Capacity | One process's heap | The memory of all nodes |
| Failure | Dies with the process | A node fails while the application lives |
| Placement | Not needed | Someone decides which node owns a key |
Three illustrations run through the lesson: a minimal example (the stand-in lab), a realistic example (ShopStream's cache tier losing a node at peak) and a failure example (a node that returns with old data).
Memcached: a small, plain key-value store
The Memcached documentation calls it an in-memory key-value store for small arbitrary data, and says the server treats values as opaque: the application serializes objects first. In the text protocol a key is a string of up to 250 bytes; set stores, possibly overwriting; add stores only if the key is absent; cas stores only if nobody updated the data since you read it; delete removes. An expiry of 0 means never, and values up to 30 days are relative.
Memory is divided into 1 megabyte pages, each given to one size class and "never moved", and each class has its own LRU. When a class has no free chunk and no free page, memcached evicts an item that has not yet expired if it finds no expired one.
Spreading keys over servers is the client's job here. The performance guide says most clients calculate the server hash table once at startup and reuse it, so finding the server for a request is a hash lookup. It names no hash scheme; the lab tries two.
Figure 1. A client that picks the server. How to read this: the client hashes each key and sends the request to one server, so the client alone decides where a key goes. The key letters are an example, not a real distribution.
Redis: a data structure server
Redis describes itself as a data structure server: strings, hashes (field-value records), lists, sets, sorted sets, streams, bitmaps, geospatial indexes and probabilistic types such as HyperLogLog. A string value is at most 512 MB by default. For a cache, a product can be a hash with one updatable field instead of a serialized blob.
- Expiry.
EXPIREsets a timeout; overwriting the key withSETclears it. - Eviction. With
maxmemoryset, Redis evicts bymaxmemory-policy; cache entries are copies of stored data, so evicting them is usually safe. - Persistence. RDB snapshots, an append-only file, both or none; none is "sometimes used when caching". After a crash expect to lose the latest minutes with RDB and up to one second with AOF's default.
- Replication. Asynchronous by default.
WAITasks for replica acknowledgement, but does not make Redis strongly consistent: acknowledged writes can still be lost in a failover. - Sentinel. Monitors, fails over and tells clients the primary's address; at least three instances are recommended, and the system "does not guarantee that acknowledged writes are retained during failures".
Redis Cluster: servers own slots
Redis Cluster "does not use consistent hashing". Each key belongs to one of 16384 hash slots, the CRC16 of the key modulo 16384, and each node owns a subset (the documentation's example splits 0 to 5500, 5501 to 11000 and 11001 to 16383 over three nodes). Moving slots needs no downtime, so adding a node means moving slots, not rehashing keys. Multi-key operations work only inside one slot, and a hash tag forces that: user:{123}:profile and user:{123}:account share the part in braces, so they share a slot.
Figure 2. The documentation's three-primary example. How to read this: the client sends each command to the node owning the key's slot; nodes can redirect a client that guessed wrong, and a serious client caches the slot map. Dashed arrows are asynchronous replication.
The documentation is blunt about guarantees: Cluster "does not guarantee strong consistency" and can "lose writes that were acknowledged". One cause is asynchronous replication: a primary acknowledges, crashes before sending the write on, and a replica without it is promoted. The other is a partition that leaves a client with a minority side containing a primary for longer than the node timeout. Three primaries are the minimum. For a cache this is usually acceptable, because the database holds the truth and a lost write is a missing or stale entry; it is not acceptable if Redis holds the only copy.
| Question | Memcached (per its documentation) | Redis (per its documentation) |
|---|---|---|
| Data model | Opaque values under string keys | Typed values: strings, hashes, sorted sets and more |
| Who spreads keys | The client, from a server table | One server with replicas, or Cluster slots owned by nodes |
| Memory pressure | Per-class LRU; may evict unexpired items | maxmemory with a chosen policy |
| Replication | Not described in the pages read (not the same as "not supported") | Asynchronous; Sentinel or Cluster for failover |
From Spring, Spring Data Redis's RedisCacheManager implements the cache abstraction. Its documented defaults include no key expiry, JDK serialization for values, nulls cached and statistics off, so a cache with no TTL and no memory policy only grows.
Build it: a client-side sharding stand-in
No Redis or Memcached server is available to the lab, so none of its output comes from one. The nodes and the client are stand-ins: in-process maps with expiry, and a client that routes keys and decides what to do when a node fails, with Spring's @Cacheable on top through a small Cache adapter. It models only key distribution, resizing, and a node that disappears and returns.
Setup. From examples/spring-labs:
cd examples/spring-labs && ./gradlew :labs:sharded-cache-client:test
It runs 15 tests, including GoldenRunTest, which compares the report below with examples/spring-labs/golden/sharded-cache-client.txt. The code is in examples/spring-labs/labs/sharded-cache-client/src/main/java/buildingai/labs/shardedcache/.
How the model works. Router is hash mod N or a consistent-hash ring. ShardedCacheClient routes get, set and delete. When a call fails it either keeps the node in the list (reads become misses, writes and deletes are dropped) or ejects it at the first failure, so its keys go elsewhere:
private void onFailure(CacheNode node) {
failedCalls++;
if (policy == FailurePolicy.EJECT_NODE && members.remove(node.name())) {
rebuildRouter();
}
}
Real clients decide a server is dead in their own ways; this one ejects at the first failed call to keep the numbers readable.
Placement and resizing
Expected output, captured from a real run (Java 25, Spring Boot 4.1.2, 2026-12-01):
== 1. Where 10000 keys land on four nodes ==
router n1 n2 n3 n4 smallest largest
hash mod N 2573 2457 2465 2505 2457 2573
ring, 1 point per node 1740 3306 824 4130 824 4130
ring, 10 points per node 1864 3757 2951 1428 1428 3757
ring, 100 points per node 2299 2417 2583 2701 2299 2701
An even split would be 2500 each. One point per node leaves large gaps; more points per node smooth them out.
== 2. Adding a fifth node: how many of the 10000 keys change owner ==
router keys moved share
hash mod N 8040 80.4%
ring, 1 point per node 2585 25.9%
ring, 10 points per node 1810 18.1%
ring, 100 points per node 2186 21.9%
One fifth (20.0%) is the least that can move, because the new node must take a fifth of the keys. Every key that moves is a miss.
With four nodes, hash mod N and a ring with 100 points per node both split 10,000 keys evenly enough; one point per node does not (824 to 4,130). Adding a fifth node is where they part: a fifth is the least that can move, the ring moves 21.9% and hash mod N 80.4%. Every key that moves is a miss.
Failure policies
Expected output, captured from a real run (Java 25, Spring Boot 4.1.2, 2026-12-01):
== 3. Spring @Cacheable over the stand-in cluster: ring, 100 points per node, 1000 products ==
first pass over the products: 1000 database reads
keys held per node: n1=239 n2=234 n3=253 n4=274
second pass: 0 database reads
== 4. Node n2 becomes unreachable after the cache is warm; two more passes over the 1000 products ==
client setup keys n2 pass 1 reads pass 2 reads failed nodes in list
ring, keep node, treat as miss 234 234 234 936 n1,n2,n3,n4
ring, eject node 234 234 0 1 n1,n3,n4
hash mod N, eject node 248 747 1 1 n1,n3,n4
Keep node: the keys on n2 reach the database on every pass for as long as n2 is down. Eject with a ring: only n2's keys are re-read, once.
Eject with hash mod N: three nodes now share the keys, so most keys change owner and most of the cache is re-read.
The one read in its pass 2 is a key that was read (a hit) before the first failed call and changed owner when the list shrank.
The first pass over 1,000 products costs 1,000 database reads and the second none. Then node n2, holding 234 keys, becomes unreachable. Kept in the list, its keys reach the database on every pass (936 failed calls). Ejected from a ring, they are re-read once and cached on the survivors, and nothing else moves. Ejected under hash mod N, 747 of 1,000 keys are re-read.
Figure 3. A node leaving and rejoining the client's list. How to read this: ejecting protects the database while the node is gone. The danger is the way back: a node with old data can serve entries replaced elsewhere.
The failure example: a node that returns with old data
Expected output, captured from a real run (Java 25, Spring Boot 4.1.2, 2026-12-01):
== 5a. One key (product:9) while n2 drops out and comes back with its data intact (ring, eject node, entry lifetime 60 s) ==
step owner db reads result
priceOf: first read, filled with the database price n2 1 price 100
n2 becomes unreachable (nothing is called yet) n2 0 n2 still in the node list: true
changePrice(120): database written, delete sent to the owner n2 0 database 120; n2 in the node list: false
priceOf: read, now routed to a surviving node n4 1 price 120
n2 is reachable again and rejoins, data intact n4 0 n2 holds 1 entries
priceOf: read after the rejoin (database holds 120) n2 0 price 100 <- STALE
61 seconds later: priceOf n2 1 price 120
The delete went to n2 while it was down, so it was lost. The old entry came back with the node and was served until its lifetime ended.
The key lives on n2 at price 100. n2 becomes unreachable, the price changes to 120, and the service's delete is lost because the owner is down (the client ejects n2 at that call). A surviving node loads 120. When n2 rejoins with its data, the key routes back to it and the read returns 100 while the database holds 120, until the 60-second lifetime ends. The same run with n2 returning empty:
Expected output, captured from a real run (Java 25, Spring Boot 4.1.2, 2026-12-01):
== 5b. One key (product:9) while n2 drops out and comes back EMPTY (ring, eject node, entry lifetime 60 s) ==
step owner db reads result
priceOf: first read, filled with the database price n2 1 price 100
n2 becomes unreachable (nothing is called yet) n2 0 n2 still in the node list: true
changePrice(120): database written, delete sent to the owner n2 0 database 120; n2 in the node list: false
priceOf: read, now routed to a surviving node n4 1 price 120
n2 restarts empty and rejoins n4 0 n2 holds 0 entries
priceOf: read after the rejoin (database holds 120) n2 1 price 120
An empty node holds nothing old, so the first read after the rejoin is a miss and loads the current price.
An empty node holds nothing old, so the first read after the rejoin is one miss and loads 120.
Break it. In ShardedCacheClient.onFailure, delete rebuildRouter(): the ejecting-with-a-ring test fails because the dead node stays in the routing table. Restore it and run the tests again.
The model leaves out real servers and clients, latency, replication and memory limits, and says nothing about how any particular client library behaves.
Trade-offs
Figure 4. A decision tree for where the cache lives. How to read this: the second question matters most. A cache can lose entries safely only when the database still holds them.
| Option | Gain | Cost | Wrong when |
|---|---|---|---|
| In-process cache | No network hop | One copy per instance; invalidation reaches one process | Instances must agree |
| Client-side sharded nodes | Simple servers; capacity grows by adding nodes | Every client must share the node list and failure policy | Clients run different lists |
| Redis with replicas and Sentinel | Typed values; failover without client logic | Asynchronous replication can lose acknowledged writes | Redis holds the only copy |
| Redis Cluster | Slots move without downtime | Multi-key operations need hash tags | Many cross-key operations |
In practice: ShopStream's cache tier loses a node at peak
This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company. Numbers are illustrative except the shares taken from the lab.
This is a realistic scenario, not a case history.
The situation
ShopStream's catalogue is cached on four nodes shared by all application instances. Peak browsing is about 2,300 requests per second (the course's illustrative figure); at an assumed 95% hit ratio the database sees about 115 per second. One node becomes unreachable.
Starting architecture
Figure 5. The cache tier with node 2 unreachable. How to read this: requests for node 2's keys fail, and the failure policy decides how many reach the database and for how long.
Options considered
| Option | Behaviour when a node dies | Database load |
|---|---|---|
| A. Keep the node, treat as miss | Its keys hit the database on every request | About a quarter of cached traffic misses until it returns |
| B. Eject, consistent-hash ring | Only its keys move and refill on survivors | A quarter of keys miss once, then recover |
C. Eject, hash mod N |
Most keys change owner | Most of the cache goes cold |
With the lab's shares (23.4% of keys on the failed node, 74.7% re-read after a mod-N eject) and the assumed 95% hit ratio, the miss ratio is 0.05 + 0.95 x 0.234 = 27% for A and for B at first, about 626 database requests per second (5 times normal); for C it is 0.05 + 0.95 x 0.747 = 76%, about 1,747 per second (15 times). This is arithmetic on illustrative inputs, not a prediction.
The decision
Option B with a ring, a short TTL on prices as the bound on stale data, and a rule that a node rejoins only after it has been cleared. The team also bounds concurrent catalogue queries (see load shedding) so a bad minute degrades the page, not the database.
Rollout and verification
A rollout rehearses the failure as the lab does: stop one node in a test environment under replayed traffic and record database requests per second, once returning with data and once empty. In production the checks are hit ratio and failed calls per node, database requests per second, and a sampled comparison of cached and database prices. Verification is "database load stays inside its limit, and no price differs from the database for longer than the TTL after a rejoin".
The 2 a.m. failure
A switch fault isolates node 2 for two minutes. Clients eject it; an owner edits a price and the delete goes to the dead node. When the network heals, node 2 rejoins with its old data and shoppers who hit its keys see the old price until the TTL ends (the lab's section 5a). The checks: compare the cached and database price for the edited product and read the client's node-list history. The mitigation is to clear the rejoined node's keys. The lasting fixes are to clear a node on rejoin, keep the TTL below the longest stale price you can tolerate, and never make the displayed price the basis of the charge.
Architect's notes
- Decide placement and failure policy together, and write the node list and ejection rule down.
- Prefer a ring or slots to
hash mod N. A resize or ejection should move a fraction of the keys. - Treat a rejoining node as suspect. Clear it, or rely on a short TTL, and set a memory policy too.
Common mistakes
- Using Redis as the only copy of data and calling it a cache. Acknowledged writes can be lost.
- Adding a node at peak under
hash mod N. Most keys move and most reads miss. - Letting a node rejoin with old data. It can serve entries replaced while it was away.
Key takeaways
- A distributed cache gives one shared copy and more memory, and costs a network hop, a failure mode and a placement problem.
- Memcached's client spreads the keys; Redis Cluster uses 16384 slots owned by nodes, and can lose acknowledged writes.
- In the lab a ring moved 21.9% of keys on a resize and
hash mod N80.4%; ejecting a dead node re-read 234 of 1,000 keys with a ring and 747 withhash mod N. - A node that returns with old data can serve stale entries; clear it on rejoin or bound it with a short TTL.
Practice exercises
Exercise 1 (20 min). For 4 nodes at a 95% hit ratio, compute the miss ratio after losing one node with a ring (a quarter of keys) and with hash mod N (three quarters), and the database rate at 2,000 requests per second.
Exercise 2 (45 min). Run the lab. In section 5a, write the exact order of events that produced the stale price and name two changes that prevent it.
Exercise 3 (1 hour). Run "Break it", then set the TTL in ClusterConfig to 10 seconds and say what changes in section 5a.
Related reading
- Cache strategies: the strategies these servers run under.
- Consistent hashing: the ring used for placement.
- Eviction policies: what leaves a full node.
- Cache stampede and hot keys: what a cold node does to the database.
Official documentation
- Redis documentation: Scale with Redis Cluster, Replication, Persistence, Key eviction and High availability with Sentinel.
- Redis documentation: Data types and EXPIRE.
- Memcached documentation: overview, basic protocol and performance guide.
- Spring Data Redis reference: Redis cache.