AlgoViz

Cache replication and failover

medium 28 min

Replication 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

ClientPrimaryusers 1, 2Replica 1users 1, 2Replica 2users 1, 2

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

ClientPrimarynew nameReplica 1old nameReplica 2old name

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

    critical

    Its own network fault looks like a dead primary, and you get two primaries.

    Wrong
    if not ping(primary):    promote(replica)
    Right
    if agree(primary) >= QUORUM and votes() >= MAJORITY:    promote(best_replica())
  • A fixed primary address in clients

    critical

    After the failover they still talk to the old machine.

    Wrong
    r = Redis(host="10.0.0.5")
    Right
    r = sentinel.master_for("mymaster")
  • Holding a lock while pinging

    major

    A read lock is held around a call that needs the write lock. The monitor stops for ever.

    Wrong
    with read_lock:    for n in nodes:        check(n)     # takes the write lock
    Right
    ids = snapshot(nodes)for n in ids:    check(n)         # locks only to store the result
  • Automatic restart without persistence

    critical

    The primary returns empty before failover, and every replica copies the empty data.

    Wrong
    save ""appendonly no# restart: always
    Right
    appendonly 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.