Replication fundamentals
medium 28 minHow 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
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
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.
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.
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.
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.
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.
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
One insert, start to finish
The five steps
- 1
Client write
The application sends an INSERT to the primary.
- 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
Log shipped
The log records travel to the replica.
- 4
Replica applies
The replica stores the records and replays them in order.
- 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
| Statement | Row (logical) | WAL (physical) | |
|---|---|---|---|
| What travels | SQL text | Row values | Page changes |
| Same result everywhere | Only if deterministic | Yes | Yes, byte for byte |
| Size of the log | Smallest for big updates | Largest for big updates | In between, depends on the change |
| Different versions | Often | Often | Generally no |
| Example | MySQL STATEMENT | MySQL ROW, PostgreSQL logical | PostgreSQL streaming |
Which mechanism?
Mode
Synchronous, asynchronous and in between
Synchronous: done means two copies
Asynchronous: done means one copy
| Synchronous | Semi-synchronous | Asynchronous | |
|---|---|---|---|
| Waits for | Every named replica, or a chosen number | At least one replica | Nobody |
| Extra latency | Round trip plus the replica's disk write | The fastest replica's round trip | None |
| Confirmed writes lost if the primary dies | None, if you promote a replica that confirmed | None, if you promote the one that confirmed | The newest ones may be |
| A replica is down | Writes wait, unless others can take its place | Writes wait, or fall back | Nothing happens |
Waiting for the k-th fastest replica
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
| Level | Commit waits until | Good for |
|---|---|---|
off | Nothing, not even the local disk | Data you can afford to lose in a crash |
local | The primary's disk | Normal asynchronous use |
remote_write | The standby has written it to its operating system | Fast protection, weaker if the standby's machine crashes |
on | The standby has flushed it to disk | No loss when one machine dies |
remote_apply | The standby has replayed it | Reads from that standby see the write |
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
| Cause | What you see | What helps |
|---|---|---|
| Network | Sent position far ahead of received | Bandwidth, a nearer replica, compression |
| One huge transaction | Lag jumps, then drains | Split it into small batches |
| Replay slower than the primary writes | Lag grows all day | Parallel apply, a bigger replica, fewer indexes, less write load |
| A long query on the replica blocks replay | Lag equals the query's age | Cancel such queries, or use another replica for reports |
| Replica disk or CPU busy | Received but not replayed | Same size as the primary, fewer reads |
How long until it has caught up?
What users see
Three things that go wrong
| Problem | What happens | The promise that prevents it |
|---|---|---|
| Own write missing | You save your name, reload, and see the old one | Read your writes |
| Back in time | A refresh shows fewer comments than before, because another replica answered | Monotonic reads |
| Reply before question | Two related changes arrive in the wrong order, for example from two shards | Consistent prefix |
Going back in time
Promises
Four guarantees and how to keep them
| Guarantee | Promise | Usual way |
|---|---|---|
| Read your writes | After you write, you always see it | Read from the primary for a while, or wait for your position |
| Monotonic reads | You never see older data than before | Stick to one replica, or remember the newest position you saw |
| Consistent prefix | Related changes are seen in order | Keep related data in one ordered log, or track dependencies |
| Bounded staleness | Data is at most X seconds or K versions old | Measure lag and stop using replicas beyond the limit |
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.
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)) # primarySaying it in an interview
Interviewer
You said reads go to replicas. A user edits a comment and it looks unchanged.
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.
Interviewer
And if they open the page on their phone?
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
| Copy | Mechanism | Mode | Serves |
|---|---|---|---|
| Standby, other zone | Physical | Synchronous, flushed to disk | Nothing, or light reads |
| Two read replicas | Physical | Asynchronous | Reads that may be a second old |
| Far region | Physical or logical | Asynchronous | Local reads, disaster recovery |
| Search and warehouse | Row stream | Asynchronous | Other systems |
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.