Database Replication
Replication keeps copies of your database on multiple servers. It buys you three things: high availability (a replica takes over if the primary dies), disaster recovery (a copy survives a regional failure), and read scaling (replicas absorb read traffic so the primary handles writes).
The central trade-off is synchronous vs asynchronous — whether the primary waits for replicas to confirm. That single choice decides whether you can lose data on failover and how much it costs you in write latency.
TL;DR
- Use replicas for high availability and read scaling.
- Synchronous = no data loss, higher write latency; asynchronous = faster, possible loss.
- Route writes to the primary, reads to replicas — and account for lag.
- Have a tested failover procedure and monitor replication lag.
Quick Example
Route reads and writes to different connections — the foundation of read scaling:
Core Concepts
Synchronous vs asynchronous
Topologies
- Primary-replica — one writer, many read replicas (the common case).
- Multi-primary — multiple writers (complex conflict resolution).
- Cascading — replicas feed other replicas.
Replication lag
Asynchronous replicas trail the primary by some delay. A read from a lagging replica can miss a write that just committed — the read-after-write problem.
Best Practices
- For read-after-write consistency, read from the primary right after a write (or until lag clears).
- Don't run transactions or writes against read replicas.
- Monitor lag (seconds/bytes behind) and alert when it grows.
- Document and rehearse failover; verify integrity afterward.
Common Mistakes
Reading your own write from a lagging replica
No lag monitoring
FAQ
Synchronous or asynchronous replication?
Synchronous when you cannot lose committed data (financial records) — the primary waits for a replica to confirm, at the cost of write latency. Asynchronous for read scaling and lower latency, accepting that a failover could lose the last few unreplicated writes.
Is replication the same as sharding?
No. Replication copies the whole dataset to multiple servers (for HA and read scaling). Sharding splits the dataset into partitions across servers (for write scaling). They're complementary — large systems often do both.
What is replication lag and why does it matter?
It's how far a replica trails the primary. Reads from a lagging replica can miss recent writes, causing "I just saved it but don't see it" bugs. Monitor it, and route read-after-write reads to the primary.
How does failover work?
Monitoring detects the primary's failure, a replica is promoted to primary, connection strings/endpoints are updated, data integrity is verified, and the old primary is rebuilt as a replica. Managed databases automate much of this.
Related Topics
- PostgreSQL — Streaming replication
- High Availability — HA architecture
- Database Backups — The other half of DR
- Caching — Reducing read load on the primary
- Databases — Scaling data stores