Sub topic 15
Distributed Caches and Consistent Hashing
This chapter assumes you know the basics from earlier chapters: hit ratio, cache-aside, TTL, and eviction policies such as LRU. It also assumes you are comfortable with client-server requests and with Python. Here you will learn how a cache spreads across several machines, why a naive scheme for choosing a machine breaks, and how consistent hashing fixes most of that breakage.
Why one cache node is not enough
A single in-process cache, like the dictionary in the cache-aside example, has three limits.
- Memory. The working set may not fit on one machine.
- Throughput. One node can only serve so many requests per second.
- Sharing. Each application server has its own private cache. Ten servers hold ten copies of the same hot data, and each copy warms up and expires separately. A write on one server cannot easily invalidate the entry held by the others.
A distributed cache is a cache made of several nodes that applications reach over the network. Memcached and Redis are common examples. Applications keep their cache logic (cache-aside, TTL, invalidation) and send reads and writes to a cache cluster instead of a local dictionary.
There are two main shapes.
| Shape | How it works | Main benefit | Main cost |
|---|---|---|---|
| Partitioned (sharded) | Each key lives on exactly one node. | Capacity and throughput grow with the number of nodes. | Losing a node loses that node's share of keys. |
| Replicated | Every node holds all keys. | Reads scale and a node failure loses nothing. | Capacity does not grow, and writes must reach every copy. |
Most large caches are partitioned, often with replicas of each partition for failover. The rest of this chapter is about partitioning, because it raises the question of which node owns a given key.
Partitioning with modulo hashing
The simplest rule is to hash the key and take the remainder by the number of nodes.
import hashlib
def stable_hash(key):
# Python's built-in hash() changes between runs for strings,
# so use a digest that is the same on every client.
return int(hashlib.md5(key.encode("utf-8")).hexdigest(), 16)
def node_for(key, nodes):
return nodes[stable_hash(key) % len(nodes)]
nodes = ["cache-a", "cache-b", "cache-c"]
print(node_for("user:42", nodes))Every client that uses the same node list and the same hash function picks the same node for a key. No central lookup is needed.
The resharding problem
The rule breaks when the node count changes. Going from 3 nodes to 4 changes the divisor, so most keys map to a different node. The code below measures how many.
import hashlib
def stable_hash(key):
return int(hashlib.md5(key.encode("utf-8")).hexdigest(), 16)
keys = [f"user:{i}" for i in range(10000)]
def moved_fraction(old_count, new_count):
moved = sum(
1 for k in keys
if stable_hash(k) % old_count != stable_hash(k) % new_count
)
return moved / len(keys)
print(f"3 -> 4 nodes: {moved_fraction(3, 4):.0%} of keys move")Roughly 75% of keys change owner. For a cache this means most lookups miss right after the change, because the data sits on the old node while clients ask the new one. The misses fall through to the database all at once, which is the same load spike as a cache stampede, caused here by a scaling or failure event instead of an expiring TTL.
Consistent hashing
Consistent hashing limits how many keys move when nodes are added or removed. With N nodes, adding one node moves only about 1/(N+1) of the keys, and those keys move only to the new node.
The idea:
- Imagine the output range of the hash function as a circle (a ring). The largest value wraps around to zero.
- Hash each node's name to a position on the ring.
- Hash each key to a position on the ring.
- A key belongs to the first node found moving clockwise from the key's position.
Read the diagram as a circle laid out in a line. Each key points to the next node clockwise, and that node owns it.
If node B is removed, only the keys that B owned are reassigned. They go to the next node clockwise, which is C. Keys owned by A and C do not move. If a new node D is added between A and B, it takes over only the keys between A and D from B.
Virtual nodes
With only a few nodes, the positions on the ring are uneven. One node may own a much larger arc than the others and take more load. Virtual nodes fix this. Each physical node is placed on the ring many times, for example 100 positions named cache-a#0 through cache-a#99. Arcs average out, and when a node leaves, its keys spread across many other nodes instead of all landing on one neighbor. Virtual nodes also let you give a bigger machine more positions than a smaller one.
A working implementation
import bisect
import hashlib
def stable_hash(value):
return int(hashlib.md5(value.encode("utf-8")).hexdigest(), 16)
class HashRing:
def __init__(self, nodes=(), vnodes=100):
self.vnodes = vnodes
self.ring = [] # sorted list of positions
self.owners = {} # position -> node name
for node in nodes:
self.add_node(node)
def add_node(self, node):
for i in range(self.vnodes):
pos = stable_hash(f"{node}#{i}")
bisect.insort(self.ring, pos)
self.owners[pos] = node
def remove_node(self, node):
for i in range(self.vnodes):
pos = stable_hash(f"{node}#{i}")
self.ring.remove(pos)
del self.owners[pos]
def node_for(self, key):
if not self.ring:
raise LookupError("no nodes in the ring")
pos = stable_hash(key)
idx = bisect.bisect(self.ring, pos) % len(self.ring) # wrap around
return self.owners[self.ring[idx]]
keys = [f"user:{i}" for i in range(10000)]
ring = HashRing(["cache-a", "cache-b", "cache-c"])
before = {k: ring.node_for(k) for k in keys}
ring.add_node("cache-d")
after = {k: ring.node_for(k) for k in keys}
moved = sum(1 for k in keys if before[k] != after[k])
print(f"3 -> 4 nodes: {moved / len(keys):.0%} of keys move")The output is close to 25%, compared with 75% for modulo hashing. The % len(self.ring) handles the wrap-around when a key hashes past the last position. Hash collisions between virtual node positions are possible in principle but negligible with a 128-bit digest.
Failure modes and gotchas
- Clients must agree on the ring. If two clients have different node lists, they send the same key to different nodes. You get duplicate entries and, worse, stale ones: an invalidation sent to one node leaves a copy on another. Distribute the node list from one source, or use a cluster that manages it.
- A node failure still causes misses. Consistent hashing keeps the other nodes' keys in place, but the failed node's keys are gone from the cache. Their requests go to the database. Replicas, or a small number of extra nodes of headroom, reduce this.
- Hot keys are not fixed by hashing. One extremely popular key lives on one node no matter how evenly the ring is balanced. Common fixes are a short-lived local cache in each application server, or storing several copies under suffixed keys such as
home:1tohome:8and picking one at random. - Removed and re-added nodes can serve stale data. Suppose a node leaves the ring, a key is updated and cached on its successor, and then the node returns with its old copy. Clients now read the stale value. A TTL on every entry bounds this, and some deployments flush a node before it rejoins.
- Redis Cluster does not use a ring. It divides the key space into 16,384 fixed hash slots and assigns slot ranges to nodes. Moving slots between nodes is the resharding step. The effect is similar: only the moved slots' keys change owner.
- Cache keys and hash tags. Operations that touch several keys, such as multi-key commands, only work if the keys land on the same node. Redis Cluster supports hash tags, where only the part of the key inside
{}is hashed, so{user:42}:profileand{user:42}:cartshare a slot. Use this sparingly, since it concentrates load.
Choosing between approaches
| Situation | Reasonable choice |
|---|---|
| Small, fixed cluster that rarely changes | Modulo hashing is acceptable. |
| Nodes join and leave, and clients compute placement | Consistent hashing with virtual nodes. |
| You want the server side to manage placement and failover | A cluster-aware store such as Redis Cluster. |
| A few very hot keys dominate traffic | Local caching or key replication on top of any partitioning scheme. |
Exercise
A cache cluster uses hash(key) % N to pick a node. You add a fifth node to a four-node cluster and the database load triples for several minutes. Explain why this happens, and explain what changes if the cluster uses consistent hashing with virtual nodes.
Show answer
With modulo hashing, changing N from 4 to 5 changes the owner of about 80% of keys (only keys whose hash gives the same remainder under both divisors stay put). Clients now look for those keys on nodes that do not hold them, so the lookups miss and fall through to the database until the cache refills. With consistent hashing, adding the fifth node takes over only about 1/5 of the keys, and only from existing nodes' arcs. The other 80% stay on their current nodes, so the hit ratio drops far less. Virtual nodes also spread the moved keys evenly, so the new node takes a small share from every existing node instead of a large share from one neighbor.
Exercise
In the HashRing class, what would go wrong if node_for returned self.owners[self.ring[idx]] without the % len(self.ring)?
Show answer
When a key hashes to a position greater than every position on the ring, bisect.bisect returns len(self.ring). Indexing the list at that value raises an IndexError. The modulo wraps the index back to 0, so the key is owned by the first node on the ring, which is what the circular model requires.