Module 3 · Database designLesson 25 of 888 minIntermediate

Database replication

Keep live copies of your database on other machines, to share the reading and to survive a crash.

Try it

Read from replicas and raise the delay to see stale reads. Crash the primary and count lost writes. Then turn on "Wait for replicas" and try again.

Replication keeps copies of the same database on several machines.

Primary and replicas

The most common setup (also called leader and followers):

  • All writes go to the primary.
  • The primary sends every change to its replicas, which apply them in the same order.
  • Reads can go to the primary or to replicas.

This gives you two things:

  1. More read capacity: most apps read far more than they write, so replicas take a big share of the load.
  2. Survival: if the primary dies, a replica can be promoted to be the new primary (failover).

Sync vs async

  • Asynchronous: the primary confirms the write straight away and sends it to replicas in the background. Fast, but replicas lag behind, and if the primary dies before sending, those confirmed writes are lost.
  • Synchronous: the primary waits until a replica has the write before confirming. Nothing is lost, but every write is slower, and a stuck replica can block writes.
  • Semi-sync is a common middle ground: wait for one replica, not all.

Replication lag in practice

Lag is usually milliseconds, but under heavy load it can grow to seconds. Users then see odd things:

  • You post a comment, refresh, and it's gone (your read went to a lagging replica).
  • A list shows an item, then the next page doesn't.

Common fixes: read your own recent writes from the primary, keep a user on the same replica, or show the data you just wrote from the client. These are consistency models, which you'll explore in module 5.

Multi-primary

Some systems accept writes on several nodes (multi-leader or leaderless, like Cassandra). That helps with multiple regions and availability, but two nodes can accept conflicting writes, which must be merged later.

Quick check

With asynchronous replication, the primary crashes right after confirming a write. What can happen?