Module 4 · Caching and performanceLesson 44 of 887 minIntermediate
Distributed caching
When one cache server isn't enough, spread keys across a cluster, and choose a scheme that doesn't reshuffle everything when nodes change.
With "hash mod N", change the number of cache nodes and count the keys that now miss. Switch to "Hash ring" and do the same.
One Redis or Memcached server can hold maybe tens of gigabytes and handle a few hundred thousand operations a second. Big systems need more, so they run a cluster of cache nodes.
Who owns which key?
Clients (or a proxy) decide where each key lives.
Hash mod N: node = hash(key) % N. Simple, but when N changes, almost every key maps to a different node. Lose one of 10 nodes and roughly 90% of keys suddenly miss, all hitting the database at once.
Consistent hashing: imagine a ring of hash values. Each node takes many points on the ring (virtual nodes). A key belongs to the first node clockwise from its hash. Add or remove a node and only the keys in its slices move, about 1/N of them.
Hash slots: Redis Cluster splits keys into 16,384 fixed slots and assigns slots to nodes. Moving capacity means moving whole slots, in a controlled way.
Handling node failures
A cache node dying isn't data loss (the database has everything), but it causes a burst of misses. Mitigations:
- Consistent hashing to keep the burst small.
- Replicas for each cache node, so a standby takes over with a warm cache.
- Capacity planning so the database can survive the miss burst.
Local vs distributed
- Local cache (in each app server's memory): fastest, no network, but each server has its own copy, so invalidation means telling every server.
- Distributed cache: one shared copy, consistent across servers, one network hop away.
Many systems use both: a tiny local cache for the hottest keys (with a TTL of seconds) in front of a distributed cache for everything else.