Cache replication and failover
medium 28 minReplication keeps copies of a cache on other servers.
See it run
Follow a write to its copies, then take the primary away and watch a replica take over.
Operations
Copy a write
The primary answers the client and then sends the write to both replicas.
Step 1 of 5
A write arrives
All three nodes hold user:1 and user:2. The client sets user:3 on the primary.
Step 1: A write arrives
def set(key, value): primary.store(key, value) reply("ok") # answer first for r in replicas: send_later(r, key, value) # copy afterdef get(key): return next_replica().get(key) # may be behind- Delay
- None for the client
- What may be lost
- Unsent writes
- Synchronous
- client waits for copies
A replica that is 20 ms behind gives answers that are up to 20 ms old.
In the real world
The same cache replication and failover doing real jobs. Pick one and step through it.
A user saves a new name and reloads the page.
Step 1 of 3
Save
The name is written to the primary.
Step 1: Save
Common mistakes
The bugs interviewers watch for, with the fix beside each.
One watcher decides
criticalIts own network fault looks like a dead primary, and you get two primaries.
Wrongif not ping(primary): promote(replica)Rightif agree(primary) >= QUORUM and votes() >= MAJORITY: promote(best_replica())A fixed primary address in clients
criticalAfter the failover they still talk to the old machine.
Wrongr = Redis(host="10.0.0.5")Rightr = sentinel.master_for("mymaster")Holding a lock while pinging
majorA read lock is held around a call that needs the write lock. The monitor stops for ever.
Wrongwith read_lock: for n in nodes: check(n) # takes the write lockRightids = snapshot(nodes)for n in ids: check(n) # locks only to store the resultAutomatic restart without persistence
criticalThe primary returns empty before failover, and every replica copies the empty data.
Wrongsave ""appendonly no# restart: alwaysRightappendonly yes# or no automatic restart, so failover happens first
Interview tips
How to explain it
- One primary takes writes, replicas copy.
- Copies lag, so reads can be old.
- Watchers agree, then a replica is promoted.
Memory trick: REPLICA
- Replicate, every write to the primary, primary writes.
- Load balance reads, inspect health.
- Choose the best, automate promotion.
Use it when
- The database cannot take the misses.
- Reads exceed one server.
- A warm copy in another zone is needed.
Say the limit
- The last writes may be lost.
- Write capacity does not grow.
- Failover must be tested.