Replication, Read Replicas and Failover
Copy data to other database servers for read scaling, high availability and disaster recovery.
Intermediate · about 4 hours · difficulty 3/5
Learn first: Connection Pooling, When Databases Misbehave
Replication keeps copies of your database on other servers. It is usually the first scaling and reliability step after tuning queries and adding caching.
Primary and replicas
In the common single-leader setup, one primary accepts writes and streams its changes (in Postgres, the write-ahead log) to one or more replicas, which serve reads. Uses:
- Read scaling: send heavy read queries and reports to replicas.
- High availability: if the primary dies, promote a replica (failover).
- Backups and analytics from a replica without loading the primary.
Synchronous vs asynchronous
- Asynchronous replication is fast, but replicas lag behind, and a failover can lose the last few transactions.
- Synchronous replication waits for a replica to confirm each commit: no data loss, but higher write latency and risk of stalls if the replica is slow.
Replication lag in your code
Reads from a replica can be stale. A user who updates their profile and is redirected to a page served by a lagging replica sees the old data. Common fixes: read-your-writes by routing a user's reads to the primary for a short time after they write, or reading critical paths from the primary always.
Other topologies
Multi-leader and leaderless replication (Cassandra, DynamoDB) accept writes in several places but must resolve conflicts. Managed databases (RDS, Cloud SQL, Neon, Aurora) handle replicas and automatic failover for you, which is the right default for most teams.
Replication is not a backup
A bad DELETE replicates instantly. You still need point-in-time recovery backups that you have actually tested restoring.
You are ready to move on when you can set up a primary and replica, route reads correctly and describe what happens to in-flight writes during failover.
Key concepts
- Primary and read replicas
- Synchronous vs asynchronous
- Replication lag and read-your-writes
- Failover and promotion
- Backups and point-in-time recovery
- Multi-leader and leaderless replication
Mini project
Run a Postgres primary and streaming replica with Docker Compose, route read-only endpoints to the replica, and demonstrate lag by pausing replay.
Check yourself
Why can a user not see a comment they just posted, and how do you fix it without sending all reads to the primary?
Free resources
- PostgreSQL: High Availability, Load Balancing, and Replication (PostgreSQL)
- MySQL: Replication (MySQL)
- Designing Data-Intensive Applications (Martin Kleppmann)