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.
See it run
What travels, when the client is told done, how far behind a copy is, and what a user may see.
Operations
A change travels by log
One INSERT from the client to the replica, with the two positions that matter.
Step 1 of 5
Client write
The application sends an INSERT to the primary.
Step 1: Client write
position = primary.log.append(change) # 1 log firstprimary.apply(change) # 2 then the datastream(primary.log, replica.log) # 3 shipreplica.log.flush() # 4 storedreplica.replay() # 5 visible to readers- Adds
- Transfer + replay
- Risk
- Stale reads
Stored on the replica and visible on the replica are two moments. Interviewers like this difference.
In the real world
The same replication fundamentals doing real jobs. Pick one and step through it.
Two healthy replicas, one confused user.
Step 1 of 3
First look
6 comments
The user reads from replica A and sees 6 comments.
Step 1: First look
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Measuring the received position
majorIt shows what has arrived, while readers see what has been replayed.
Wronglag = primary.lsn - replica.received_lsnRightlag = primary.lsn - replica.replayed_lsnExpecting fresh reads from a synchronous standby
criticalIt confirms when the log is stored. Replay comes later.
Wrong# standby is synchronous, so this is currentstandby.read(balance)Rightprimary.read(balance)# or commit with remote_applyWaiting for a far replica
majorEvery commit then pays the distance, and one outage over there stops your writes.
Wrongsynchronous = ["other-continent"]Rightsynchronous = any_one_of(["zone-b", "zone-c"])asynchronous = ["other-continent"]One giant transaction
minorIt is shipped and replayed as one block, and everything behind it waits.
WrongDELETE FROM events WHERE day < '2020-01-01'Rightrepeat: delete 10_000 rows pause until lag is small
Interview tips
How to explain it
- An ordered log, shipped and replayed.
- Mechanism, mode, guarantee.
- Lag is a difference of two positions.
Memory trick: SWLC
- Statement, row and WAL methods.
- Write-ahead log is the key.
- Lag is network plus apply time.
- Consistency guarantees matter.
Wait when
- A confirmed write must survive one machine.
- A replica is in a nearby zone.
- Any one of several may confirm.
Watch out when
- Semi-synchronous falls back.
- Long queries run on the replica.
- Nobody writes and the lag clock still grows.