AlgoViz

Cache replication and failover

medium 28 min

Replication keeps copies of a cache on other servers.

Video lesson · Chapter 1 of 5

A second copy lags the first

0:00 / 3:41

Theory

Read or listen first. About 1 min.

What it is

Cache replication keeps the same cached data on more than one server. Usually one server, the primary, takes all writes and sends them on to replicas. Reads may go to any of them.

Failover is what happens when the primary stops: something notices, picks a replica, makes it the new primary and tells everybody else.

Why it exists

A cache often protects a database that could not serve all reads by itself. If the cache disappears, the database may follow. A warm copy that can take over keeps the site up.

Copies also add read capacity and can sit closer to users. They do not add write capacity: every replica must apply every write.

A short history

  1. 2003

    Memcached is released without replication. Clients or layers around it add copies if they need them.

  2. 2007

    Amazon's Dynamo paper describes a store where several servers accept writes and conflicts are resolved later.

  3. 2013

    Redis 2.8 is released in November with a rewritten Redis Sentinel.

  4. 2015

    Redis 3.0 adds Redis Cluster, with a replica promoted for a part of the keys when its primary fails.

Words to know

Primary
The server that takes writes. Older texts call it master.
Replica
A server that follows the primary. Often read-only.
Replication lag
How far a replica is behind, in time or in bytes.
Quorum
How many watchers must agree before something counts.
SDOWN and ODOWN
Subjectively down: one watcher thinks so. Objectively down: enough watchers agree.
Split brain
Two servers both act as the primary.

How it works

Step through the idea, or press Play.

Step 1 of 3

Copy every write. The primary answers, then sends the write to its replicas

Understand it

Start here

The drummer and the understudy

A band has one drummer. At the side stands an understudy with a small practice pad, copying each beat a moment later.

The show must go on
1234

The understudy was good because they had been copying all along, not because they were quick to learn.

The idea

Why copy something that can be rebuilt

  • Availability

    Reads and writes go on after a server stops, without a storm of misses.

  • Read capacity

    Reads can be spread over copies.

  • Data survives one loss

    Most of it: the last unsent writes may not.

  • Nearer to users

    A copy in another place can answer local reads.

A primary, two replicas and three watchers

An application writes to one primary cache machine and reads from two replica machines. The primary sends copies to both replicas. Three watchers check the primary.
Blue is reads, pink is writes, orange is copies. The watchers run on separate machines.

Reads and memory

Rmax=n×r(3×80,000=240,000/s)Mpaid=n×M(3×40=120 GB)R_{max} = n \times r \quad (3 \times 80{,}000 = 240{,}000/\text{s}) \qquad M_{paid} = n \times M \quad (3 \times 40 = 120\,\text{GB})
An example with three servers that each serve 80,000 reads a second and hold 40 GB. After one loss, plan for two. Write capacity stays that of one server.

One writer

Primary and replicas

A write and two reads

The client had its answer before the replica had the value. The first read was stale.

Advantages

  • One writer, so no write conflicts
  • Reads grow with replicas
  • Easy to reason about
  • A warm copy is ready

Limits

  • The primary is a single point of failure until failover works
  • Writes are limited to one server
  • Lag causes stale reads
  • Failover needs coordination

When to answer

Asynchronous, synchronous and in between

ModeAnswer the clientWrite timeLoss when the primary dies
AsynchronousAt onceLowestWrites not yet copied
Semi-synchronousWhen at least N replicas have itOne more tripNone if a replica that has it is promoted
SynchronousWhen all replicas have itThat of the slowest replicaNone, but one slow replica stops writes
Caches normally copy asynchronously. Data replication covers this for databases.

How much a failover can lose

lost writes≈write rate×lag=5,000/s×0.02 s=100\text{lost writes} \approx \text{write rate} \times \text{lag} = 5{,}000/\text{s} \times 0.02\,\text{s} = 100
With 20 ms of lag and 5,000 writes a second, about 100 acknowledged writes. Lag grows when the replica or the network is busy.

Two settings that limit loss on the primary

Setting in RedisMeaning
min-replicas-to-writeRefuse writes when fewer replicas than this are connected. Off by default
min-replicas-max-lagCount only replicas heard from within this many seconds. 10 by default
They trade availability for safety: a primary cut off from its replicas stops taking writes.

Many writers

Several primaries

With several primaries, each takes writes and tells the others. Writing stays possible in each place, but two places can change the same key at the same time. Something must settle that.

Settling a conflict

WayIdeaCost
Last writer winsKeep the one with the later timeA write is dropped, and clocks differ
Mergeable types (CRDTs)Types that merge the same way in any orderOnly for some shapes of data
Vector clocksTrack what each write had seen, to detect a conflictSomething must still resolve it
Application codeYour own rule, such as joining two cartsWork for each type of data

Noticing

Is it down, or just slow?

A watcher sends a ping and waits. No reply could mean a crash, a pause or a broken cable between the two. So one watcher's view is only an opinion.

From an opinion to a decision

SDOWN is one opinion. ODOWN is an agreed state, and only it can start a failover.

Two numbers people mix up

NumberWhat it decidesWith 3 watchers and quorum 2
QuorumHow many must agree that the primary is down2
MajorityHow many must authorise the failover2
With 5 watchers and quorum 2, two can raise the alarm but three must authorise.

Majority

m=⌊n2⌋+1n=2⇒2,n=3⇒2,n=5⇒3m = \left\lfloor \frac{n}{2} \right\rfloor + 1 \qquad n = 2 \Rightarrow 2, \quad n = 3 \Rightarrow 2, \quad n = 5 \Rightarrow 3
Two watchers need both, so losing one stops failover. This is why three on separate machines is the minimum that helps.

Taking over

Failover in five steps

  1. 1

    Detect

    The watchers agree: the primary is objectively down.

  2. 2

    Elect

    One watcher is authorised by a majority to lead this failover, under a new version number.

  3. 3

    Choose a replica

    Skip those cut off too long. Then take the best priority, then the one that processed most data, then the smallest run ID.

  4. 4

    Promote

    Send REPLICAOF NO ONE to it. It now takes writes.

  5. 5

    Reconfigure

    Point the other replicas and the clients at it. When the old primary returns, it becomes a replica.

Text
sentinel monitor mymaster 127.0.0.1 6379 2sentinel down-after-milliseconds mymaster 30000sentinel parallel-syncs mymaster 1sentinel failover-timeout mymaster 180000
A Redis Sentinel configuration. The 2 is the quorum. 30,000 ms is how long without a valid reply before SDOWN. One replica at a time copies from the new primary.

Automatic failover

Clients must ask again after a broken connection. A fixed address in a configuration file defeats the whole plan.

How long writes are unavailable

T=Tdetect+Telect+Tpromote+Treconnect=5+1+1+2=9 sT = T_{detect} + T_{elect} + T_{promote} + T_{reconnect} = 5 + 1 + 1 + 2 = 9\,\text{s}
Example values. Detection is the part you choose: a shorter wait finds a crash sooner and mistakes a pause for a crash more often.

Two at once

Split brain and empty primaries

Two primaries during a network split

A network split. On one side a client still writes to the old primary. On the other side two watchers and a replica: the replica has been promoted and other clients write to it.
When the split heals, the old primary becomes a replica and its writes from the split are thrown away.
  • Limit the old side

    With a minimum number of replicas, the cut-off primary stops taking writes after a few seconds.

  • Place watchers well

    Put them on machines that fail independently, so the majority is on the side that should win.

  • Empty restart

    A primary without persistence that restarts by itself comes back empty, and its replicas copy the emptiness.

  • No automatic restart

    In that setup, do not restart the process automatically. Let failover happen first.

Trade-offs

Choose for your cache

QuestionOne primarySeveral primariesQuorum writes
Write while the primary is downNot until failoverYes, elsewhereYes, if enough servers remain
ConflictsNoneMust be settledHandled by versions
ComplexityLowHighHigh

Do I need replicas?

Summary

The whole topic in one minute.

One primary takes writes, replicas copy them, usually after the client already has its answer. That makes writes fast and lets a replica be slightly behind, so reads can be old and a failover can lose the last moment.

A safe failover needs several watchers in different places, a quorum, a clear choice of replica, and clients that find the new primary. Limit the loss with settings, and make sure losing it does not matter.

  • The primary takes writes, replicas follow with a small lag.
  • Reads from replicas can be old, and a failover can lose the latest writes.
  • One watcher has an opinion. A quorum decides, and a majority authorises.
  • Promote the replica with the best priority and the most data.
  • Clients must discover the new primary by themselves.

Sources