Replication

In one sentence

Keep copies of the same data on several nodes for durability, availability and read scale. You choose who accepts writes (one, many or any node) and whether to wait for copies before acknowledging.

Analogy: A head chef (leader) changes the recipes; line cooks (followers) copy them onto their cards. A cook who copies late serves yesterday's dish: that's replication lag.

One sync follower means no committed write is lost on failover; async followers serve reads but can lag. The failover manager promotes the sync follower.

How it works

  • Single-leader: the leader takes all writes and streams its log to followers, which serve reads but can lag.
  • Sync followers prevent data loss on failover but add latency; async ones are fast but can lose recent writes.
  • Multi-leader gives low write latency in every region but needs conflict resolution; last-write-wins loses data.
  • Leaderless stores write to W of N replicas, read from R and fix stale copies with read repair.
  • Failover risks split brain; consensus-based election plus fencing makes sure the old leader's writes get rejected.

Check yourself

Answer to mark it learned; your answers aren't scored.

Your support bot stores chunks in Postgres + pgvector: a primary plus two async read replicas that serve retrieval. A nightly re-embedding job pushes replica lag to 40 s. A customer uploads a PDF, asks about it, and the bot can't find it. Best fix?

Go deeper

Quorums: N, R, W Interactive lab
Full explanation

Replication keeps the same data on several machines so you survive node loss and spread reads. Three topologies:

  • Single-leader (Postgres, MySQL, MongoDB): all writes go to the leader, which streams its log to followers. Synchronous followers ack before the commit returns: no data loss on failover, but more latency, and a dead follower can block writes. Asynchronous followers are fast but lag, so failover can lose the last seconds of writes. The usual compromise: one sync follower, the rest async.
  • Multi-leader: a leader per region accepts local writes and replicates to the others. Low write latency everywhere, but two regions can edit the same row, so you need conflict resolution (last-write-wins loses data; CRDTs or app-level merges don't).
  • Leaderless (Dynamo, Cassandra): clients write to W of N replicas and read from R. Read repair fixes stale replicas during reads; background anti-entropy fixes the rest.

Failover promotes a follower when the leader dies. The danger is split brain: two nodes both accepting writes. Use consensus-based election (Patroni on etcd) plus fencing, so the old leader's writes are rejected.

Read replicas scale reads but add lag anomalies: users who don't see their own update need read-your-writes routing, see Consistency models.

Code Semi-sync replication and lag checks in Postgres
sqlSemi-sync replication and lag checks in Postgres
-- Primary: commit waits for ANY 1 of 2 standbys to flush (RPO = 0 for one failure);
-- a single slow standby no longer blocks every write.
ALTER SYSTEM SET synchronous_standby_names = 'ANY 1 (replica_a, replica_b)';
ALTER SYSTEM SET synchronous_commit = 'on';  -- 'remote_apply': also visible on the standby
SELECT pg_reload_conf();

-- Low-value writes can skip the wait, scoped to their own transaction
BEGIN;
SET LOCAL synchronous_commit = 'local';
INSERT INTO usage_events (tenant_id, tokens) VALUES (42, 1830);
COMMIT;

-- Primary: lag per standby (PostgreSQL 10+)
SELECT application_name, sync_state, write_lag, flush_lag, replay_lag
FROM pg_stat_replication;

-- Replica: how stale am I? (overstates lag when the primary is idle)
SELECT now() - pg_last_xact_replay_timestamp() AS replica_lag;
Real example

An AI support platform keeps chunks and embeddings in Postgres + pgvector: a primary plus two async read replicas that serve retrieval. A nightly re-embedding job rewrites 2M rows and replica lag climbs to 40 s. A customer uploads a PDF and immediately asks about it; retrieval hits a replica and the bot says it can't find the document. Fixes: route that tenant's retrieval to the primary for ~60 s after an upload, throttle the batch job, and alert when replay_lag exceeds 5 s.

Trade-offs +3 · −3

+ You gain

  • Survives node and zone loss; with a sync follower, without losing committed writes.
  • Read replicas scale read-heavy workloads such as retrieval and dashboards.
  • Replicas in other regions cut read latency and give you a disaster-recovery copy.

− You pay

  • Async lag creates stale reads and can lose the last writes on failover.
  • Sync replication adds a round trip to every commit and ties write availability to followers.
  • Multi-leader and leaderless setups push conflict resolution into your design.

Use it when

For essentially all production data: at least one replica in another zone for failover, read replicas when reads dominate, and cross-region replicas for disaster recovery or local reads.

Avoid it when

As your backup strategy: replicas copy a bad DELETE within milliseconds, so keep point-in-time backups. Don't serve from replicas reads that must see the latest write.

Numbers to know 5
  • Amazon Aurora: up to 15 read replicas, with lag typically under 100 ms (AWS docs).
  • RDS Multi-AZ (one standby) failover typically completes in 1–2 minutes.
  • Patroni's default leader-lock TTL is 30 s: roughly how long a dead leader goes unnoticed before promotion starts.
  • RF=3 is the common choice: with quorum 2, it survives losing one replica.
  • GitHub, Oct 2018: a 43 s network partition led to a cross-region failover and ~24 h of degraded service.
Common pitfalls 4
  • Reading from a replica right after a write and showing users, or the LLM, stale data.
  • Aggressive automatic failover: short timeouts promote on a GC pause or network blip, causing flapping or split brain.
  • Failover without fencing: the old leader comes back and keeps accepting writes.
  • Last-write-wins in multi-leader setups silently drops one of two concurrent edits.
Interview questions 2

Answer out loud first, then reveal.

Sync or async replication for the primary database?Show answer

Neither alone: semi-sync. One synchronous standby in another availability zone, so a committed write survives losing the primary, giving zero RPO for a single failure at the cost of a ~1–2 ms cross-zone round trip per commit. With ANY 1 over two standbys, one slow standby doesn't stall writes. Cross-region replicas stay async for disaster recovery, accepting a few seconds of RPO, because a synchronous cross-region commit would add ~70–150 ms to every write.

How do you prevent split brain during failover?Show answer

Three layers. Leadership comes from a consensus store, like etcd behind Patroni, as a lease: a node that can't renew it must stop accepting writes. Then fencing: each leadership term gets an increasing epoch, and storage or downstream services reject writes from an old one. Finally, conservative automation across regions: GitHub's 2018 incident began with a 43-second partition and a cross-region promotion, and ended in about 24 hours of degraded service. For a short blip, waiting beats failing over.