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

Quick Example

Route reads and writes to different connections — the foundation of read scaling:

Core Concepts

Synchronous vs asynchronous

Topologies

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

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

References