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

Synchronous vs Asynchronous

ModeBehaviorTrade-off
SynchronousLeader waits for follower to confirm writeNo data loss, but slower writes
AsynchronousLeader doesn't waitFaster 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