TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท databases ยท scaling ยท reliability

Replication and read replicas

Keeping copies of a database on other servers by replaying the primary's change log. Replicas scale reads and take over on failure, but asynchronous copies can lag behind.

10 min4 animations

๐Ÿ–จ๏ธ Cheat sheet

The master ledger

Head office keeps the master ledger. Every change is also written in a diary. Copy rooms around town read the diary and repeat each change in their own copy of the ledger. Lots of people only want to look things up, so they ask a copy room, and head office isn't swamped.

Primary and replicas

In single-leader replication, all writes go to the primary. It records changes in its log (Postgres WAL, MySQL binlog), and replicas stream and replay it. Benefits:

  • Read scaling: send read queries to replicas.
  • High availability: a replica can take over if the primary fails.
  • Isolation: analytics and backups run on a replica, not the primary.

Spring apps often route @Transactional(readOnly = true) methods to a replica data source.

The master ledger and its copies3 steps
Change diary01234๐Ÿง‘โ€๐Ÿ’ผClerk๐ŸขHead office๐Ÿ Copy room 1๐Ÿ Copy room 2
Press play and watch it happen!

A little behind

The diary takes a moment to reach the copy rooms. If you change your address at head office and look it up at a copy room a second later, you might see the old one. So right after you change something, read your own details from head office for a little while.

Replication lag

Replication is usually asynchronous: the primary commits without waiting for replicas, which apply changes slightly later. That's eventual consistency for replica reads. Problems it causes, and fixes:

  • Read-your-writes: read from the primary for a short while after a user writes.
  • Monotonic reads: pin a user to one replica, so they don't see time go backwards.
  • Monitor lag, and take lagging replicas out of rotation.

Synchronous replication waits for a replica to confirm before committing: no lag for that replica, at the cost of write latency.

The copy is a little behind3 steps
๐Ÿง’Customer๐ŸขHead office๐Ÿ Copy room
Press play and watch it happen!

When head office closes

If head office closes, the most up-to-date copy room becomes the new head office, and everyone is told the new address. Anything written in the diary but not yet copied might be lost.

Failover

Failover promotes a replica to primary and points clients at it. With async replication, writes not yet replicated are lost. Automatic failover needs a reliable way to decide the old primary is really dead, often a consensus system, to avoid split brain, where two primaries accept writes at once.

Head office burns down3 steps
๐Ÿง‘โ€๐Ÿ’ผClerk๐ŸขHead office๐Ÿ Copy room 1๐Ÿ Copy room 2
Press play and watch it happen!

When the copying goes wrong

Three things can go wrong. First, head office tells the clerk "done" and closes before the copy is made, so the new head office never hears about that change. The fix is to hold the "done" until one copy room has copied it, which makes every change a little slower.

Second, a rumour spreads that head office is gone, and two copy rooms each start acting as head office. People write different changes in each. To stop it, the old head office is locked out until it agrees to copy from the new one, and only one office may act as head office at a time.

Third, a copy room gets so far behind that it can't catch up from the diary at all. It is thrown out of the rota and starts again from a fresh copy of the ledger.

What can go wrong

Lag and failover are covered above (see Replication lag and Failover). These are the failures that hurt in production:

  • Acknowledged writes lost on failover. With asynchronous replication the primary acks a commit before any replica has it. If it dies then, the promoted replica never had the write, and when the old primary returns its extra transactions have diverged from the new timeline. Symptom: customers hold confirmations for rows that don't exist. Fix: synchronous or semi-synchronous replication for data you can't lose, and never let the old primary rejoin as is. Rewind it (Postgres pg_rewind) or rebuild it from the new primary, and keep its extra transactions for review.
  • Split brain. A network partition or a slow primary makes the failover tool promote a replica while the old primary is alive, so two nodes take writes and the data forks. Symptom: duplicate keys, conflicting rows, two nodes reporting as primary. Fix: elect the primary through a quorum or consensus store (as Patroni does with etcd or Consul), and fence the old one: shut it down (STONITH), or have clients and storage reject its stale term or fencing token. Prefer a primary that demotes itself when it loses its lease.
  • Stale and out-of-order reads: see Replication lag above. Symptom: "I saved it and it's gone." A further fix: wait until the replica has replayed past the write's log position before reading from it.
  • A replica falls far behind or breaks. Heavy writes, a long query on the replica or a slow disk make lag grow, and a replica that is offline too long can no longer find the log it needs. In Postgres an unused replication slot makes the primary keep WAL until the disk fills, unless max_slot_wal_keep_size caps it, and a long standby query can be cancelled with a recovery conflict. Symptom: growing replay_lag in pg_stat_replication or Seconds_Behind_Source in MySQL, stale reads, a full WAL disk. Fix: alert on lag, remove the replica from the read pool when it exceeds a threshold, cap or drop stale slots, and rebuild it from a fresh base backup.
ChoiceYou gainYou pay
Sync vs asyncSync: no acknowledged write is lost on failover. Async: fast commits, primary unaffected by replicasSync: slower commits, and writes can block if the replica is down. Async: lag, and lost writes on failover
Semi-sync (MySQL)At least one replica has the write before the ackExtra latency, and it falls back to async after a timeout
Replica reads vs primary readsReplicas: reads scale out, primary less busy. Primary: always the latest dataReplicas: stale and out-of-order reads. Primary: carries all the load
Automatic vs manual failoverAutomatic: quick recovery without waking anyone. Manual: a human checks before switchingAutomatic: risk of split brain or needless failover on a blip. Manual: longer outage

In Postgres, synchronous_standby_names chooses which standbys a commit waits for, and synchronous_commit how far (remote_write, on = flushed, remote_apply). In Spring, a stale read shows up as a plain successful query with old data, not an exception, so route reads deliberately (for example @Transactional(readOnly = true) only where staleness is fine).

The acknowledged write that vanished5 steps
Head office diary0123Copy room diary0123๐Ÿง‘โ€๐Ÿ’ผClerk
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 4 questions about Replication and read replicas, told the same way as the story.
  1. Why do copy rooms help head office?
  2. You change your address at head office, then look it up at a copy room a second later. What might you see?
  3. Head office closes. What happens?
  4. Head office tells the clerk a change is done, then closes before it is copied, and a copy room takes over. What happens to that change?
Answer every question to check.Passing marks Replication and read replicas as done.
Got the hang of Replication and read replicas? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ•ธ๏ธ Distributed systems from zeroStep 1 of 7

Next on the path โ†’๐Ÿ—ณ๏ธ Consensus (Raft)

๐Ÿ—๏ธ Storing data at scaleStep 5 of 7

โ† Previous on the path๐Ÿ—‚๏ธ LSM treesNext on the path โ†’๐Ÿ“• Sharding

๐Ÿ‘‰ Read next

  • ๐Ÿ›๏ธAmazon RDS and AuroraKeeping your records at a council-run records office that fixes the building, copies the files and keeps a twin office.
  • ๐Ÿฅ–AWS Regions and Availability ZonesA bakery chain with branches in many cities, each city with several bakeries that have their own power and water.
  • โš–๏ธCAP theoremTwo shop branches whose phone line goes down: close until it's back, or stay open and risk different prices.
  • ๐Ÿ—ณ๏ธConsensus (Raft)A club choosing a captain and keeping one official notebook, where a decision counts once most members copy it.
  • ๐Ÿ—„๏ธNoSQL data modelsSwapping one big ruled ledger for storage furniture built for each job: pegs, filing cabinets, card catalogues.
  • ๐ŸงพRedis persistence and replicationA till that keeps everything in memory, with photos and a receipt roll to rebuild it after a power cut.
  • ๐Ÿ’ŒVector clocks and ordering eventsPen pals who number their letters and note the latest number seen from every friend.