Chapter 27: Replication — Leader-Follower, Multi-Leader, Leaderless
Replication = keeping copies of data on multiple machines. Provides: high availability (survive node failure), read scaling, and geographic distribution.
Leader-Follower (Master-Slave)
Writes ──► [Leader/Primary] ──WAL stream──► [Follower/Replica 1]
│ [Follower/Replica 2]
│
Reads can go to any node
- All writes go to the leader
- Leader streams changes (WAL) to followers
- Followers are read-only copies
- If leader dies → promote a follower (failover)
Synchronous vs Asynchronous
| Mode | Behavior | Trade-off |
|---|---|---|
| Synchronous | Leader waits for follower to confirm write | No data loss, but slower writes |
| Asynchronous | Leader doesn't wait | Faster writes, but follower may lag (data loss on failover) |
Multi-Leader
Multiple nodes accept writes. Used for multi-datacenter setups. Challenge: conflict resolution when two leaders modify the same data.
Leaderless (Dynamo-style)
Any node accepts reads and writes. Uses quorum: write to W nodes, read from R nodes. If W+R > N, you're guaranteed to read the latest write.
// Quorum example: N=3 nodes, W=2, R=2
// Write succeeds if 2/3 nodes acknowledge
// Read queries 2/3 nodes, takes latest version
// W+R=4 > N=3, so reads always see latest write
PostgreSQL Streaming Replication
# On primary (postgresql.conf):
wal_level = replica
max_wal_senders = 3
# On replica:
primary_conninfo = 'host=primary port=5432'
# Replica continuously receives and replays WAL from primary
Key Takeaways
- Leader-follower: simple, one write point, read scaling. Most common.
- Multi-leader: multi-datacenter writes, complex conflict resolution
- Leaderless: high availability, tunable consistency via quorums
- Replication lag = followers may serve stale data (eventual consistency)
- PostgreSQL uses WAL streaming for replication — same log used for crash recovery