Database Replication

Copy data across machines for availability and read scale — and pay for it in consistency.

Replication in 30 seconds

  • Replication keeps copies of the same data on multiple machines for availability and read scale.
  • The cost is consistency: for a window, the copies will disagree.
  • Single-leader is the sane default — one node takes writes, followers copy and serve reads.
  • Multi-leader and leaderless buy multi-region writes or tunable consistency, but bring conflict resolution.
  • Sync waits for a follower (no loss, slower); async acks immediately (fast, can lose recent writes).
  • Replication lag causes read-your-writes surprises — route a just-wrote user to the leader briefly.

One master ledger, or many photocopies?

Imagine a shop that keeps all its records in a single paper ledger. It works beautifully — until the day the ledger is lost in a fire, and the whole business is gone with it. There's also only one copy, so only one clerk can read it at a time; a queue forms. The obvious fix is to photocopy the ledger and keep copies in several rooms. Now a fire in one room isn't fatal, and many clerks can read at once.

But the moment you have copies, a new problem appears: when someone writes a new line in the master ledger, the photocopies are briefly out of date until the change is copied over. A clerk reading an old copy sees stale information. That's database replication in a nutshell — copies buy you survival and read capacity, and the price you pay is that, for a window, the copies disagree.

The problem it solves

A single database is a single point of failure and a single point of load. Replication keeps copies of the same data on multiple machines so you can survive a node dying and spread reads across replicas. The cost is that keeping copies in agreement is hard, and for a window they will disagree.

The core idea, plainly

One node accepts writes (the leader); others copy its changes (the followers). Reads can go to any copy. The central question is when a write is considered done: the moment the leader has it (fast, but a crash loses recent writes), or only after followers confirm (durable, but slower).

Leader applies locally, then ships the log entry (python)
def leader_write(entry):
    wal.append(entry)         # 1. durably record the change in the write-ahead log
    apply_to_state(entry)     # 2. update the leader's own copy
    for follower in followers:
        follower.send(entry)  # 3. stream the same log entry to each follower

# Followers replay the leader's log in the SAME ORDER,
# which is what keeps every copy converging to one state.
def follower_receive(entry):
    wal.append(entry)
    apply_to_state(entry)

Why ship a log, not the data?

Notice the leader sends log entries — a description of each change — not a fresh copy of the whole database. This is the key to how replication stays cheap and correct. The leader writes every change to an ordered write-ahead log first, and followers simply replay that same log in the same order. Replaying an ordered list of changes guarantees each follower lands in exactly the state the leader was in. It's the difference between mailing someone the full ledger every minute versus mailing them just the new lines to copy in.

Leader-follower: writes to one node, reads from many.

Topologies and their trade-offs

There's more than one way to arrange leaders and followers, and the arrangement decides what you can and can't do — especially around where writes are allowed.

TopologyWritesProsConsUse when
Single-leaderOne nodeSimple; no write conflicts; strong per-key ordering.Leader is a write bottleneck and failover point.Most apps — the sane default.
Multi-leaderSeveral nodesWrites survive a region outage; low write latency per region.Conflicts are unavoidable and must be resolved.Multi-region write availability is required.
Leaderless (quorum)Any nodeNo failover step; tunable consistency via W + R > N.Reads may see stale replicas; needs read repair.High availability with tunable guarantees.

The gap single-leader can't fill — and the conflict it creates

Single-leader is lovely because one node decides the order of everything, so writes never conflict. But it has a hard limit: all writes funnel through that one leader. If your users are spread across continents, a user in Sydney writing to a leader in Virginia eats a painful round trip, and if that region goes dark, nobody can write at all.

Multi-leader replication answers this by letting several nodes accept writes — one per region, say. Now the Sydney user writes locally and fast. But you've opened a door you can't fully close: two leaders can accept conflicting writes to the same record at the same time, with no single authority to order them. Resolving those conflicts is now your problem, and there's no free answer.

A multi-leader conflict, and the rules used to resolve it (pseudocode)
# Same row, same instant, two regions:
#   Leader US:  name = "Ada Lovelace"   @ 10:00:00.100
#   Leader EU:  name = "Ada King"       @ 10:00:00.090
# Both commit locally, then replicate -> which one wins?

# Common resolution rules (none are free):
#   last-write-wins (LWW): pick the higher timestamp -> DATA LOSS (US drops EU)
#   merge:                 app-specific join of both edits
#   CRDTs:                  data types that mathematically merge without loss
#   keep both:              store a conflict for a human/app to resolve
Multi-leader: fast local writes, but concurrent edits to one key collide.

Leaderless and quorum reads

A third arrangement drops the leader entirely: in leaderless replication any node can take a write, and the client (or a coordinator) writes to several nodes and reads from several nodes. The trick that keeps it correct is quorum math — if your write touches enough nodes and your read touches enough nodes that the two sets must overlap, your read is guaranteed to catch the latest write.

Quorum math (leaderless) (sql)
-- N replicas, W write acks required, R read responses required.
-- Guarantee overlap (read sees latest write) when:
--     W + R > N
-- Example: N = 3
--   W = 2, R = 2  ->  strong-ish, balanced
--   W = 3, R = 1  ->  fast reads, slow writes
--   W = 1, R = 1  ->  fast but can read stale

Sync vs async replication

Synchronous: the leader waits for a follower to confirm before acknowledging the write. No data loss on leader failure, but one slow follower stalls every write. Asynchronous: the leader acknowledges immediately and ships changes in the background. Fast, but a leader crash can lose the last few writes. A common middle ground is semi-sync: wait for one follower, let the rest catch up async.

Where the leader acks: sync vs async vs semi-sync (python)
def leader_write(entry, mode):
    wal.append(entry)
    sent = [f.send_async(entry) for f in followers]

    if mode == "async":
        return ack()                 # fast: ack before any follower confirms
    if mode == "sync":
        wait_all(sent)               # durable: every follower confirmed
        return ack()                 # one slow follower stalls the write
    if mode == "semi_sync":
        wait_any(sent, count=1)      # middle ground: just one follower
        return ack()                 # bounds data loss without full stall

Replication lag — the surprise that bites users

With async replication there's always a brief window where a follower hasn't caught up to the leader — that window is replication lag. It's usually milliseconds, but it's enough to confuse a real user. The classic case: a user updates their profile (write goes to the leader), then the page reloads and reads from a lagging follower that doesn't have the change yet. From their chair, their edit just vanished.

A read during the lag window sees the pre-write value — stale.
Read-your-writes: route the just-wrote user to the leader (python)
def read_profile(user):
    # If the user wrote within the last few seconds, their change
    # may not have reached the followers yet -> read the leader.
    if seconds_since_last_write(user) < 10:
        return leader.read(user)         # guaranteed to see their own edit
    return random.choice(followers).read(user)  # otherwise, cheap follower read

# This narrowly spends leader capacity only where staleness would
# actually surprise the user, instead of sending ALL reads to the leader.

Replication is the foundation of both surviving failure and scaling reads — and it's the clearest place to watch the availability-versus-consistency trade play out in a real design.

Why it matters

  • Copies are what let a system lose a node without losing data or going dark.
  • Read replicas absorb enormous read volume cheaply, which is most systems' first scaling win.
  • The sync/async and topology choices are a direct, tunable dial on how much data loss and lag you'll tolerate.

If ignored

  • A single database stays a single point of failure — one crash takes the whole system down.
  • Async replication silently loses the last few acknowledged writes when the leader fails over.
  • Forgetting read-your-writes means a user saves something and sees it vanish on the next refresh.

Where it fits

  • Sits across the data tier, between the write path and the many nodes serving reads.
  • The read-scaling and availability step of the database scaling playbook.
  • Pairs with sharding, which splits data for write scale rather than copying it for read scale.

Related topics

  • Sharding: the complement — splits data for write scale instead of copying it
  • CAP & PACELC: replication is where the consistency-vs-availability trade becomes concrete
  • Database scaling: read replicas are the key read-scaling step of the playbook
  • Consistency models: read-your-writes and monotonic reads are the guarantees lag forces you to pick

Interview lens

Questions it unlocks

  • How do you scale reads on a relational database?
  • What happens to in-flight writes when the leader fails?
  • A user complains their profile update 'disappeared' on refresh — why?

60-second answer

I'd start single-leader with async read replicas, because it's simple and handles most read-scaling needs. I'd name the two costs out loud: replication lag (so I'd add read-your-writes routing for the just-wrote user) and the failover window (so I'd use semi-sync to bound data loss). I'd only reach for multi-leader or quorum if the requirement is multi-region write availability, and I'd be explicit that it brings conflict resolution I now have to design.

Common traps

  • Claiming replicas give you both more reads and stronger consistency for free.
  • Forgetting that async replication can lose recently acknowledged writes on failover.
  • Ignoring read-your-writes and surprising the user who just saved something.

Search topics

↑↓ to move · Enter to open · Esc to close