Cheatsheet

Database Replication

Replication topologies, sync vs async, replication lag anomalies and fixes, quorum maths, failover and split-brain, sharding vs replication, metrics.

01Why replicate

  • Availability: another copy can take over when a node fails.
  • Read scaling: spread read queries across replicas.
  • Latency: place copies close to users in other regions.
  • Durability: data survives the loss of a disk or machine.

Replication copies the same data to several nodes. It does not increase write capacity in single-leader setups; for that you shard.

02Topologies

Replication topologies compared
TopologyWrites go toStrengthWeaknessExamples
Single-leader (primary-replica)One primarySimple, no write conflictsPrimary limits write throughput; failover neededPostgreSQL, MySQL, SQL Server
Multi-leaderAny of several leaders (often one per region)Local writes in each region, tolerates region lossWrite conflicts need resolution rulesMulti-region MySQL setups, CouchDB
LeaderlessSeveral replicas directly (quorum)No failover step, tolerates node lossEventual consistency, read repair, conflict handlingCassandra, DynamoDB-style stores
Conflict resolution
Last-writer-wins (simple, loses data), version vectors with merge, or CRDTs for mergeable types.
Statement vs log shipping
Replicate SQL statements (non-deterministic functions break) or the write-ahead log / row changes (preferred).

03Synchronous vs asynchronous

Acknowledgement modes
ModeCommit acknowledged whenDurability on primary lossWrite latencyAvailability
SynchronousAll (or the chosen) replicas have the changeNo acknowledged writes lostHighest: slowest replica plus networkA slow or failed replica blocks writes
Semi-synchronousAt least one replica has itSurvives one node lossOne extra round tripFalls back to async if no replica answers (configurable)
AsynchronousPrimary has written it locallyRecent writes can be lostLowestReplicas never block the primary
  • A common production choice: one synchronous replica in the same region plus asynchronous replicas elsewhere.
  • Cross-region synchronous replication adds the inter-region round trip (tens of ms) to every commit.

04Replication lag anomalies

Read anomalies caused by lag, and fixes
AnomalyWhat the user seesFix
Read-your-writes violationSaves a profile, reloads, sees the old versionRead own data from the primary for a short window, or wait until the replica reaches the write’s log position
Non-monotonic readsA comment appears, then disappears on refreshPin each user to one replica (hash of user id)
Inconsistent prefixSees an answer before the questionWrite causally related data to the same partition; carry causal metadata
Stale reads after failoverData seems to go back in timePromote the most up-to-date replica; fence the old primary
  • Lag is usually milliseconds but can grow to minutes under heavy writes, long queries on replicas, or network trouble.
  • Alert on lag in seconds and stop routing reads to a replica beyond a threshold.

05Quorum maths

N replicas, W write acknowledgements, R read responses
W + R > N   → every read set overlaps every write set (sees the latest acknowledged write)
W > N / 2   → two conflicting writes cannot both reach a quorum

N = 3, W = 2, R = 2   tolerates 1 node down for reads and writes (common default)
N = 3, W = 3, R = 1   fast reads, any node down blocks writes
N = 3, W = 1, R = 1   fastest, no overlap guarantee (eventual consistency)
N = 5, W = 3, R = 3   tolerates 2 nodes down
  • Quorum overlap is not linearizability: concurrent writes, sloppy quorums and clock-based conflict resolution still allow anomalies.
  • Read repair and anti-entropy (Merkle tree comparison) bring stale replicas back in line.

06Failover and split-brain

Failover steps (single-leader)
1. Detect: primary misses heartbeats for a timeout (e.g. 10–30 s)
2. Choose: elect the replica with the most recent log position (consensus or orchestrator)
3. Fence: stop the old primary accepting writes (revoke lease, STONITH, block at proxy)
4. Promote: new primary starts accepting writes
5. Repoint: clients and other replicas follow the new primary (DNS, proxy, service discovery)
Split-brain
Two nodes both believe they are primary and accept writes; the data diverges. Prevent with fencing tokens, leases and a majority quorum for election.
Timeout trade-off
Short timeouts cause needless failovers on brief pauses; long ones mean longer outages.
Lost writes
With async replication, writes the old primary acknowledged but never shipped are lost on promotion. Decide whether that is acceptable (RPO).
RPO / RTO
Recovery point objective: how much data you may lose. Recovery time objective: how long recovery may take.

07Sharding vs replication, and what to watch

Replication and sharding solve different problems
AspectReplicationSharding (partitioning)
Each node holdsA full copyA subset of the data
ScalesReads, availabilityWrites and total data size
Main costLag, failover complexityCross-shard queries and transactions, rebalancing
Used together?Yes: each shard is usually replicatedYes: each shard is usually replicated
  • Replication lag (seconds and bytes behind) per replica.
  • Replica health and replication slot / log retention growth.
  • Primary write throughput and commit latency (sync replicas add to it).
  • Read distribution: are replicas actually taking read load?
  • Failover drills: time to promote, and data lost, measured regularly.