Distributed caching
medium 26 minA distributed cache spreads keys over several servers, so it can hold more and answer more than one machine.
See it run
How a key finds its server, what happens when servers come and go, and what a local copy saves.
Operations
Route a key
A client works out the node from the key and asks only that one.
Step 1 of 4
Three nodes, one rule
Each node holds part of the keys. The application knows the rule, not the contents.
Step 1: Three nodes, one rule
def get(key): node = ring.node(key) # same answer on every client value = servers[node].get(key) if value is None: value = database.read(key) servers[node].set(key, value, ttl=300) return value- Keys that move
- None
- Extra work
- One hash
- Ask every node
- 3 requests for one value
Every client needs the same hash and the same list of nodes.
In the real world
The same distributed caching doing real jobs. Pick one and step through it.
A live match page gets 40% of all reads.
Step 1 of 3
One node is hot
- Node B
- 95%
The key lives on node B. A and C have time to spare.
Step 1: One node is hot
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Routing with a remainder
criticalOne more node moves most keys. All those reads reach the database together.
Wrongnode = servers[hash(key) % len(servers)]Rightnode = ring.node(key) # few keys moveUsing a hash that differs between runs
criticalPython's built-in hash of text changes between processes, so each process routes differently.
Wrongnode = servers[hash("user:1") % 3]Rightnode = ring.node("user:1") # md5 or crc, same everywhereWaiting for a dead node
majorWithout a timeout, each read that maps to it hangs and threads run out.
Wrongvalue = client.get(key)Rightvalue = client.get(key, timeout=0.05)# on a timeout, treat it as a missTesting for a hit by truth
minor0 and empty text are real values. They look like misses and are loaded again and again.
Wrongif not value: value = load(key)Rightif value is None: value = load(key)
Interview tips
How to explain it
- Several servers act as one cache.
- A rule turns a key into a server.
- The rule should move few keys when servers change.
Memory trick: RING
- Rotate clockwise to find the node.
- Insert moves only adjacent keys.
- Nodes get virtual positions, and scaling is graceful.
Use it when
- Hot data is larger than one machine.
- Many application servers need the same data.
- Sessions must outlive an application server.
Look out for
- Cold nodes at peak time.
- One hot key on one node.
- Clients with different lists of servers.