Courses / Databases for Backend Interviews / Chapter 22
Module 10 · Replication, partitioning and sharding · Chapter 22 of 27
Replication: Streaming Standbys, Lag, Failover and Logical Replication
Builds on Transactions: ACID, the Write-Ahead Log and Crash Recovery, Isolation Levels and MVCC: Anomalies, Snapshots and Vacuum and Locks and Concurrency Control: Row Locks, Deadlocks and Optimistic Updates. Next up: Partitioning and Sharding: Partition Keys, Routing and Resharding.
Part 1 · Why replicate, and leader and follower
One writer, many copies
A cricket score feed is written by one scorer and read by lakhs of people at once. Replication copies every change from one database server to others, so reads spread out and a copy survives when a machine does not.
There are three common reasons to keep copies. The first is availability: if the server fails, another one that already holds the data can take over. The PostgreSQL documentation describes this as letting a second server take over quickly if the primary fails. The second is read scaling: copies can answer read-only queries, so the primary has less to do. The third is backup and maintenance: a copy can be used to take backups, run reports or test an upgrade without touching the primary.
The simplest arrangement is leader and follower. One server, the primary, accepts every write. The documentation calls the servers that track its changes standby servers. A standby that cannot be connected to until it is promoted is a warm standby, and one that accepts read-only queries is a hot standby. Writes flow in one direction only, from the primary to the followers, which is why there is never a question of which copy is right.