AlgoViz

Introduction to data replication

easy 25 min

Replication keeps the same data on several machines and keeps the copies up to date.

Video lesson · Chapter 1 of 5

Can a nearby catalog answer the lunch rush

0:00 / 3:58

Why we copy databases, in 80 seconds

1:20Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Data replication means keeping a copy of the same data on more than one machine, and keeping every copy up to date as the data changes. Each copy is called a replica.

Making a copy once is easy. Replication is the second part: data changes all day, so every change made on one copy must reach all the others, in an order that makes sense.

Replication is different from partitioning. Replicas hold the same rows. Partitions, also called shards, hold different rows. Large systems use both, and sharding covers the second one.

Why it exists

A single database server is a single point of failure: when it stops, so does everything that needs the data. A second copy means a failure becomes a short interruption instead of a long outage.

Copies also do useful work while nothing is broken. Read queries can be spread over them, reports can run on one without slowing customers down, and a copy in another region answers the people there without a trip across an ocean.

The price is that copies can disagree for a while. Almost every hard question about replication is about what users see during that while.

A short history

  1. 1979

    David Gifford publishes weighted voting for replicated data: give every copy a vote, and require enough votes to read or write.

  2. 1996

    Jim Gray and others publish The Dangers of Replication and a Solution. They show that letting every copy accept transactional updates becomes unstable as the number of nodes grows.

  3. 2007

    Amazon describes Dynamo, a store in which any of several nodes can accept a write and conflicting versions are reconciled later.

  4. 2010

    PostgreSQL 9.0 ships built-in streaming replication and hot standby, so a standby server can also answer read-only queries.

Words to know

Primary (leader)
The copy that accepts writes. The source of truth in single-leader replication.
Replica (follower)
A copy that receives changes from a leader. It normally serves reads only.
Replication lag
The delay between a write on the primary and the moment it can be seen on a replica.
Failover
Making a replica the new primary after the old one fails.
Write conflict
Two copies accepted different changes to the same record at about the same time.
Quorum
The number of copies that must answer before an operation counts as done.
Convergence
All copies end up with the same value once changes stop.

How it works

Step through the idea, or press Play.

Step 1 of 3

Copy. Start a new server from a full copy of the data

Understand it

Start here

The treasure map

Some friends own one treasure map. If rain ruins it, the treasure is lost. So they make copies, agree that one friend adds new marks first, and everyone else copies those marks.

One map becomes three
Sam

Everything on this page is a detail of this picture: who may draw, how marks travel, and what a friend sees before the mark arrives.

The idea

The basic architecture

Writes to one, reads from many

Users call an application. The application sends writes to the primary database and reads to replica 1 and replica 2. The primary sends its changes to both replicas.
Pink is the write path, blue is the read path, dashed orange is replication.

Four words you need

  • Primary, or leader

    Accepts all the writes. The source of truth.

  • Replica, or follower

    A read-only copy that follows the primary.

  • Replication lag

    How far behind the primary a replica is.

  • Failover

    A replica becomes the primary when the original fails.

One write and two reads

The first read came before the change arrived. That gap is replication lag.

Why

Three reasons to replicate

Before and after

QuestionOne serverReplicated
Who does the work?One server handles everythingSeveral servers share the reads
The server crashesTotal outageFailover to a copy, if it is set up and tested
More read trafficLimited by one machineAdd replicas
Users far awayEvery read crosses the distanceReads come from a replica in the region
MaintenanceDowntimePatch replicas in turn, then switch over
Automatic failover does not come free with copies. Something has to detect the failure, choose and switch.

High availability. A replica can take over. How long that takes depends on detection and promotion, which implementing replication covers step by step. Read scaling. Many applications read far more often than they write. Geography. A nearby copy removes the distance from each read.

How much does read scaling give?

reads=n (C−W)4×(10,000−1,000)=36,000 per second\text{reads} = n\,(C - W) \qquad 4 \times (10{,}000 - 1{,}000) = 36{,}000 \text{ per second}
Assume each of nn equal nodes can do CC operations per second and must apply all WW writes. Four nodes do not give 4 times 10,000 reads, because every copy repeats every write. If WW reaches CC, adding replicas adds nothing.

Why distance costs time

tround trip≥2×6,000 km200,000 km/s=60 mst_{\text{round trip}} \ge \frac{2 \times 6{,}000 \text{ km}}{200{,}000 \text{ km/s}} = 60 \text{ ms}
Light in glass fibre travels at about 200,000 km per second. A user 6,000 km away waits at least 60 ms, however fast the database is. A copy in the same region removes that wait for reads.

Type 1

Single-leader replication

One primary accepts all writes and sends them to its replicas. Older texts call it master-slave. PostgreSQL streaming replication, MySQL replication, MongoDB replica sets and Redis replication all work this way.

Good

  • Simple to understand and run
  • No write conflicts between leaders
  • Strong reads are possible: read from the primary

Costs

  • Writes stop until failover if the primary dies
  • Write throughput is one machine's throughput
  • Reads from replicas can be old

Single leader

Type 2

Multi-leader replication

Several nodes accept writes and send changes to each other. It is common to put one leader in each region, so local users write locally and a region keeps working when the link between regions is cut. CouchDB databases that replicate both ways are an example, and so is an app that lets you edit offline: each device is a small leader.

Good

  • Local writes in each region are fast
  • A region survives losing another region or the link
  • Offline editing becomes possible

Costs

  • Two leaders can change the same row: a write conflict
  • Conflict resolution is complex
  • Unique and foreign-key checks are hard across leaders

How to resolve a write conflict

MethodHow it worksWhat you lose
Avoid itEach record has a home region that takes its writesWrites travel when the user moves
Last write winsKeep the change with the newest timestampThe other change disappears, and clocks must agree
Keep bothStore both versions and let the application chooseExtra code, and users may have to decide
MergeUse a data type that merges safely, such as a counter or a setOnly some data has a sensible merge
CouchDB picks one winning revision with the same deterministic rule on every peer and keeps the losing revisions so that the application can repair them. DynamoDB global tables in eventual mode use last writer wins per item.

Type 3

Leaderless replication

Any replica of a record can take a read or a write. The client, or a coordinator node, sends each operation to several replicas and waits for enough answers. With N copies, writing to W and reading from R overlaps when R + W > N. The proof, and what it does not promise, live in implementing replication. Apache Cassandra is the best-known example, and Amazon's Dynamo paper describes the idea.

Good

  • No leader whose loss stops writes
  • Stays available while some nodes are down
  • Consistency can be tuned per request

Costs

  • Often eventually consistent
  • Copies that missed a write need repair
  • Concurrent writes conflict and need a rule

Leaderless with three copies

Two of three copies answered, so the write succeeds. Node 3 is repaired later.

Compare

The three side by side

AspectSingle leaderMulti-leaderLeaderless
Write conflictsNone between leadersPossiblePossible
ConsistencyStrong if you read from the primaryEventual between leadersTunable
ComplexityLowHighMedium
Write availabilityLowest: waits for failoverHigherHighest while a quorum answers
FitsMost applicationsRegions that must write alone, offline appsVery large, always-on key lookups

Which type do I need?

Speed or safety

Wait for the copies, or not?

A primary can wait for a replica before it tells the client the write is done (synchronous), or answer immediately and send the change afterwards (asynchronous). Waiting protects the last writes when the primary dies. Not waiting is faster, and a slow replica cannot hold up customers.

When to use what

Wait (synchronous)Do not wait (asynchronous)
Money movementsHigh write throughput
Data that must not be lostCopies far away
The business accepts extra latencyLow latency is critical
A standby nearby, in the same regionSlightly old reads are acceptable
Waiting is about durability. It does not by itself make reads from replicas fresh. The details and the levels in between are in replication fundamentals.

Using replicas

Route reads and writes

Read/write splitting sends every write to the primary and most reads to replicas. It can live in the application, in the database driver or in a proxy between them.

  1. 1

    Classify

    Is this a write, a read that must be current, or a read that may be old?

  2. 2

    Send writes to the primary

    A read inside a transaction that writes goes there too.

  3. 3

    Send current reads to the primary

    For example an account balance before a payment.

  4. 4

    Send the rest to a healthy replica

    Take turns, skip replicas that are down or too far behind.

  5. 5

    Fall back

    If no replica is healthy, use the primary only if it has the spare capacity. Otherwise shed the least important reads.

A primary at home, replicas near users

Users in Europe read from a replica in the Europe region. Users in the United States read from a replica in the United States region. Writes from both regions go to the primary in the United States, and the primary sends changes to both replicas.
Reads are local. Writes from Europe still cross the ocean, because there is one leader.

Three patterns that hide the lag

PatternWhat you doWhat the user notices
Read your writesAfter a write, send that user's reads to the primary for a short timeTheir own change is always there
Sticky sessionsKeep sending a user to the same replicaData does not jump back in time, until that replica is lost
Causal orderRemember what a user has seen, and only read from copies that have itNever an answer before its question
What goes wrong without them, and how to measure it, is in replication fundamentals.

Not the same

A replica is not a backup

A replica copies everything, quickly, including the mistakes. Delete a table by accident and every replica deletes it moments later. Backups keep older versions that nothing overwrites. You need both, and you need to practise restoring.

Do

  • Pool connections to each node
  • Route writes to the primary only
  • Monitor replication lag
  • Test failover regularly
  • Health-check replicas and retry safely

Do not

  • Read everything from the primary
  • Ignore the lag
  • Skip retry logic
  • Write to a replica directly
  • Forget that the network between copies can break

Examples

What to pick for four systems

Worked choices, with reasons

SystemChoiceReason
Bank ledgerSingle leader, synchronous standby in the same regionLosing a confirmed payment is worse than a slower one
Social feedSingle leader per shard, asynchronous read replicasA like that appears a second late harms nobody
ShopPrimary for stock and orders, replicas for the catalogueProduct pages are read far more than they change
Viewing history in several regionsLeaderless, eventualIt must accept writes everywhere, and an old position is easy to live with
These are example designs, not descriptions of a particular company.

How it sounds in an interview

  1. Interviewer

    Your recipe site has 1,000 reads a second on average and 20 writes. What does the data layer look like?

  2. You

    Peak is about 3 times average, so 3,000 reads and 60 writes a second. I assume one node serves 2,000 simple reads a second, so I need two nodes for the load and a third so that losing one is fine: a primary and two replicas. Writes are tiny, so one leader is enough.

  3. Interviewer

    A cook saves a recipe and does not see it.

  4. You

    That read hit a replica that was behind. I send a user's reads to the primary for a few seconds after they save. Everyone else can wait a second.

Summary

The whole topic in one minute.

Replication keeps copies of the same data on several machines. You gain survival, read capacity and nearness to users, and you pay in storage, in extra work for every write, and in copies that briefly disagree.

Choose who may write first. One leader is the simplest and is right for most systems. Several leaders help when regions must keep writing on their own, and cost you conflicts. Leaderless stores ask several nodes on each operation. A replica is never a backup, because it copies your mistakes too.

  • Replication is the same data on several machines, kept up to date.
  • It buys availability, read capacity and nearness to users. It does not add write capacity.
  • Single leader first. Several leaders or no leader only when a requirement forces it, with a conflict rule.
  • Route writes to the primary, current reads to the primary, the rest to healthy replicas.
  • A replica is not a backup.

Sources