Database replication copies data from one database (primary) to one or more replicas. It enables read scaling, high availability, disaster recovery, and geographic distribution. The key challenge is maintaining consistency across replicas while handling network partitions and failures.
Primary-Replica (Leader-Follower)
The most common pattern: one primary handles all writes, replicas serve read queries. The primary streams its write-ahead log (WAL) to replicas, which replay it to stay in sync.
Use replay_lagto monitor replica health. A growing lag means the replica can't keep up with the primary's write throughput. Consider upgrading the replica or reducing read traffic.
Change Data Capture (CDC)
CDC captures row-level changes from the database and streams them to other systems (Kafka, Elasticsearch, analytics). Unlike replication, CDC is designed for downstream consumers, not database sync.
Use Debezium for complex CDC pipelines (Kafka, Elasticsearch). Use PostgreSQL's native logical replication for simpler database-to-database sync without external dependencies.
# 5. Reconfigures the old primary as a replica when it recovers
⚠
warning
Automatic failover requires careful configuration. A false positive (promoting a replica when the primary is just slow) can cause split-brain. Always set maximum_lag_on_failover and test failover scenarios regularly.