AlgoViz

Replication fundamentals

medium 28 min

How a change travels from one copy to another: what is written in the log (statements, rows or physical bytes), when the client is told it is done (synchronous, semi-synchronous, asynchronous), why replicas lag, and which promises keep users from seeing confusing old data.

Video lesson · Chapter 1 of 5

Receipt is earlier than visibility

0:00 / 4:07

How a change reaches a replica, in 85 seconds

1:25Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Replication has three moving parts. The mechanism says what is copied: the statement, the changed rows or the physical log. The mode says when the client hears "done": before or after a replica confirms. The guarantee says what a reader may see in the meantime.

All three rest on one thing: an ordered log of changes. A replica that applies the same log in the same order ends with the same data. Its place in the log is a number, so being behind is a difference between two numbers.

Why it exists

Sending whole tables again and again would be far too slow. Sending only the changes works, but only if they arrive in order, none is missing, and a replica that was away can continue where it stopped. A log with positions gives exactly that.

The mode exists because safety and speed pull in opposite directions. The guarantees exist because users do not care how the copies work. They care that their own change is there and that the page does not go back in time.

A short history

  1. 2010

    PostgreSQL 9.0, released on 20 September, adds streaming replication: the write-ahead log is sent over a network connection as it is produced.

  2. 2011

    PostgreSQL 9.1, released on 12 September, adds synchronous replication, so a commit can wait for a standby to write the log to disk.

  3. 2014

    PostgreSQL 9.4 adds replication slots, which keep the log until a standby has received it, and logical decoding, which turns the log into row changes.

  4. 2017

    PostgreSQL 10 adds logical replication with publications and subscriptions.

Words to know

Write-ahead log (WAL)
The file where a database records every change before it changes the data files.
Binary log (binlog)
MySQL's log of changes, which replicas read.
LSN
Log sequence number: a position in the PostgreSQL WAL.
Replay (apply)
Making the logged change in the replica's own data.
Stale read
A read that returns a value which has already been replaced.
Session guarantee
A promise about what one user or session will see.
Deterministic
Gives the same result every time it runs on the same data.

How it works

Step through the idea, or press Play.

Step 1 of 3

Log. The primary records the change in order

Understand it

Start here

The conductor and the score

A conductor writes a new piece of music one bar at a time, on a score with numbered bars. Two musicians copy the score, bar by bar, in order. Nobody skips a bar, so anyone can say exactly how far they have come.

Copying the score
123Conductor123Noor123Max

What the musicians copy is the mechanism, when the conductor says done is the mode, and what Asha may be told is the guarantee.

The log

One ordered list of changes

Where a change lives on its way

A client sends an insert to the primary, where it is appended to the write-ahead log and then applied to the tables. The log is streamed to the replica's own copy of the log, and from there it is replayed into the replica's tables.
The dashed orange arrow is the log being streamed. The replica first stores the received log, then replays it. Stored and replayed are two different moments, and the difference matters below.

One insert, start to finish

The five steps

  1. 1

    Client write

    The application sends an INSERT to the primary.

  2. 2

    Log write

    The primary appends the change to its write-ahead log. This also makes crash recovery possible, as ACID explains under durability.

  3. 3

    Log shipped

    The log records travel to the replica.

  4. 4

    Replica applies

    The replica stores the records and replays them in order.

  5. 5

    In sync

    The replica has reached the primary's position. Both hold the same data until the next write.

Mechanism 1

Statement-based: send the SQL

Replicate the SQL statement and let every replica run it again. The log is small: an UPDATE that changes a million rows is one line. The trouble is non-determinism.

Good

  • Simple idea, easy to read
  • Very little to send for large updates

Costs

  • A random number or a unique id differs on each copy
  • An UPDATE with LIMIT and no ORDER BY may pick other rows
  • Triggers and functions may have side effects

Mechanism 2

Row-based: send the changed rows

Record what each row looked like after the change (and usually how to find it). It does not matter how the value was computed: the replica stores the result. MySQL calls this ROW format and it is the default. PostgreSQL's version is logical replication.

Good

  • Deterministic, works with any SQL
  • Can copy only some tables
  • Can cross major versions, and feed other systems

Costs

  • One large update becomes many row records
  • Rows need a key so that the replica can find them
  • In PostgreSQL, schema changes are not replicated

The same row stream can also feed search indexes, caches and warehouses. That is change data capture.

Mechanism 3

Physical: send the write-ahead log

Ship the database's own log, which says which bytes changed in which page. The replica is a byte-for-byte copy of the whole server. This is PostgreSQL streaming replication.

Good

  • Exact copy of everything, schema changes included
  • Little extra work: the log exists anyway
  • Best base for failover

Costs

  • Same hardware architecture, and in general the same major version
  • All or nothing: the whole server is copied
  • The replica is read-only

The three mechanisms

StatementRow (logical)WAL (physical)
What travelsSQL textRow valuesPage changes
Same result everywhereOnly if deterministicYesYes, byte for byte
Size of the logSmallest for big updatesLargest for big updatesIn between, depends on the change
Different versionsOftenOftenGenerally no
ExampleMySQL STATEMENTMySQL ROW, PostgreSQL logicalPostgreSQL streaming
MySQL also has MIXED, which uses statements and switches to rows when a statement is unsafe. Choosing the binlog format has been deprecated since MySQL 8.0, with row expected to remain.

Which mechanism?

Physical or row, depending on the product. Statement-based is rarely the right new choice.

Mode

Synchronous, asynchronous and in between

Synchronous: done means two copies

Asynchronous: done means one copy

SynchronousSemi-synchronousAsynchronous
Waits forEvery named replica, or a chosen numberAt least one replicaNobody
Extra latencyRound trip plus the replica's disk writeThe fastest replica's round tripNone
Confirmed writes lost if the primary diesNone, if you promote a replica that confirmedNone, if you promote the one that confirmedThe newest ones may be
A replica is downWrites wait, unless others can take its placeWrites wait, or fall backNothing happens
The added wait is one round trip to the replica, so it depends on distance: well under a few milliseconds between nearby zones, tens of milliseconds between continents.

Waiting for the k-th fastest replica

tcommit=tlocal+t(k)replicas at 1, 2, 70 ms:;k=1→1,;k=2→2,;k=3→70t_{\text{commit}} = t_{\text{local}} + t_{(k)} \qquad \text{replicas at } 1,\,2,\,70 \text{ ms}:; k=1 \to 1,; k=2 \to 2,; k=3 \to 70
Waiting for all three makes every commit as slow as the farthest copy. Waiting for any one or two ignores it. PostgreSQL writes this as ANY 2 followed by the list of standbys.

Finer control

What exactly did the replica confirm?

"The replica has it" can mean three things: received in memory, safe on disk, or visible to readers. PostgreSQL lets every transaction choose with synchronous_commit.

PostgreSQL levels with a synchronous standby

LevelCommit waits untilGood for
offNothing, not even the local diskData you can afford to lose in a crash
localThe primary's diskNormal asynchronous use
remote_writeThe standby has written it to its operating systemFast protection, weaker if the standby's machine crashes
onThe standby has flushed it to diskNo loss when one machine dies
remote_applyThe standby has replayed itReads from that standby see the write
Only the last level makes the standby's reads fresh. A synchronous standby on the default level can still serve old data for a moment.
  • Payment

    Synchronous, safe on a second disk. Slower is fine.

  • New post

    Semi-synchronous. One nearby copy is enough.

  • Page view

    Asynchronous. Losing a few is acceptable.

  • Far region

    Asynchronous. Do not make each commit cross an ocean.

Lag

Why a replica is behind

A row written at 10:00:00.000 that becomes visible on the replica at 10:00:00.150 has 150 ms of lag. The time goes into sending the log and into replaying it.

Where lag comes from

CauseWhat you seeWhat helps
NetworkSent position far ahead of receivedBandwidth, a nearer replica, compression
One huge transactionLag jumps, then drainsSplit it into small batches
Replay slower than the primary writesLag grows all dayParallel apply, a bigger replica, fewer indexes, less write load
A long query on the replica blocks replayLag equals the query's ageCancel such queries, or use another replica for reports
Replica disk or CPU busyReceived but not replayedSame size as the primary, fewer reads

How long until it has caught up?

t=backlogreplay rate−write rate=600 MB30−20 MB/s=60 st = \frac{\text{backlog}}{\text{replay rate} - \text{write rate}} = \frac{600 \text{ MB}}{30 - 20 \text{ MB/s}} = 60 \text{ s}
If replay is not faster than the incoming writes, the bottom of the fraction is zero or negative and the replica never catches up.

What users see

Three things that go wrong

ProblemWhat happensThe promise that prevents it
Own write missingYou save your name, reload, and see the old oneRead your writes
Back in timeA refresh shows fewer comments than before, because another replica answeredMonotonic reads
Reply before questionTwo related changes arrive in the wrong order, for example from two shardsConsistent prefix

Going back in time

Both replicas are healthy. The user still thinks that comments were deleted.

Promises

Four guarantees and how to keep them

GuaranteePromiseUsual way
Read your writesAfter you write, you always see itRead from the primary for a while, or wait for your position
Monotonic readsYou never see older data than beforeStick to one replica, or remember the newest position you saw
Consistent prefixRelated changes are seen in orderKeep related data in one ordered log, or track dependencies
Bounded stalenessData is at most X seconds or K versions oldMeasure lag and stop using replicas beyond the limit
These are promises to one session or about age. They are weaker and cheaper than making every read current. Isolation between transactions is a different subject: see concurrency control.

The position method. When a write commits, remember its log position with the user's session. Before a read, pick a replica whose replayed position is at least that number. If there is none, wait a few milliseconds or go to the primary. It is exact, where "use the primary for 5 seconds" is a guess.

Python
def choose(replicas, needed):    """replicas: {name: replayed position}. Return one that is fresh enough, or the primary."""    fresh = [name for name, position in replicas.items() if position >= needed]    return fresh[0] if fresh else "primary"replicas = {"noor": 5, "max": 4}print(choose(replicas, 4))   # noorprint(choose(replicas, 5))   # noorprint(choose(replicas, 6))   # primary
The position method in a few lines
Edit and run it in your browser

Saying it in an interview

  1. Interviewer

    You said reads go to replicas. A user edits a comment and it looks unchanged.

  2. You

    That breaks read your writes. I store the log position of the edit in the session. The next reads use a replica that has replayed at least that position, otherwise the primary.

  3. Interviewer

    And if they open the page on their phone?

  4. You

    Then the position must be stored per user on the server, not in one browser. For a comment I might accept a second of delay on the other device and say so.

Summary in one picture

Put it together

A sensible default for one region

CopyMechanismModeServes
Standby, other zonePhysicalSynchronous, flushed to diskNothing, or light reads
Two read replicasPhysicalAsynchronousReads that may be a second old
Far regionPhysical or logicalAsynchronousLocal reads, disaster recovery
Search and warehouseRow streamAsynchronousOther systems
How the standby takes over is in implementing replication.

Summary

The whole topic in one minute.

A replica follows an ordered log. Statement-based logs are small but unsafe for anything non-deterministic. Row-based logs are safe and larger. Physical logs are exact copies, and tie both servers to the same major version and hardware architecture.

Synchronous replication protects confirmed writes and adds a round trip. Asynchronous replication is fast and can lose the newest writes. Lag is transfer time plus apply time, and you hide it with session guarantees: read your writes, monotonic reads, consistent prefix and bounded staleness.

  • Replicas follow an ordered log, so being behind is a number.
  • Statement: small, unsafe if not deterministic. Row: safe, larger. Physical: exact, same major version.
  • Synchronous adds a round trip and protects confirmed writes. Asynchronous may lose the newest.
  • Lag is transfer plus replay. It only shrinks if replay is faster than writing.
  • Hide lag with read your writes, monotonic reads, consistent prefix and bounded staleness.

Sources