codequest / system design
Core concept 4 of 21

Database replication

Copy the database to read replicas to scale reads and survive failures, at the cost of replication lag.

Primary and replicas

In leader-follower (primary-replica) replication, one database, the primary, accepts all writes. It streams every change to one or more read replicas, which serve reads. Two benefits: more read capacity, and a standby that can take over if the primary fails (failover).

Replicas do not add write capacity. Every replica still has to apply every write, so in a write-heavy system adding replicas helps far less than you'd expect. When writes are the limit, the next step issharding.

Synchronous vs asynchronous

  • Asynchronous (common): the primary confirms a write before replicas have it. Fast, but replicas lag behind, and a crash can lose the latest writes.
  • Synchronous: the primary waits for a replica to confirm. No data loss on failover, but every write is slower and one slow replica stalls writes.

Replication lag

With async replication a user can write something and immediately read an older value from a replica. Common fixes:read-your-writes (send a user's reads to the primary for a few seconds after they write) or read from the primary for data that must be fresh.

Other topologies

  • Multi-leader: several primaries (often one per region) accept writes. Lower write latency worldwide, but you must resolve write conflicts.
  • Leaderless (Dynamo, Cassandra): any node accepts writes; reads and writes use quorums (for example 2 of 3 nodes).

Try it

The single primary is overloaded by reads the cache misses. Add a read replica and watch the reads spread out.

Primary DB overloaded
p95 latency (server)
99 ms
Error rate
2.3%
Est. cost / month
$570
excl. bandwidth
App servers
400 req/s each · $40/mo
10
Hit rate
DB read replicas
+1,250 reads/s each · also applies every write · $120/mo
0

Primary DB: 1,250 queries/s (1 query per request). How the numbers work

In the interview

  • For read-heavy systems: one primary for writes, replicas for reads, and a cache in front.
  • Say that replication is asynchronous and what lag means for the user, and how you'd handle read-your-writes.
  • Mention failover: a replica is promoted if the primary dies.
  • If writes outgrow one primary, move on to sharding.