Skip to main content
Database Replicationlesson 1 of 4 · 2 min read

Leader-Follower Basics

One door for writes

Almost everyone runs the same shape, called single-leader replication. One machine, the leader, takes every write.

It writes each change into a log, and streams that log to follower machines, which replay it in the same order and end up holding the same data. Reads can go to any of them. Writes have exactly one door.

There is only one door for a reason, because everything else follows from it. If any machine could take writes, two of them could take conflicting changes to the same row in the same instant. Somebody would then have to invent a rule for who wins.

With one leader, every write happens in one order, the order the leader picked, and followers simply apply it. You gave up spreading writes around, and in return you never think about write conflicts again. For most systems that is obviously the right trade.

What the copies buy you

What the followers buy stacks up fast. Reads first. A typical web app is at least 80 percent reads, so moving those onto two or three copies can quadruple your capacity while the leader coasts.

Isolation second, so the analytics team's ugly report runs on its own copy and cannot slow down checkout. Geography third, so a copy in Frankfurt gives European users 5 millisecond reads while their writes still travel to the leader in Virginia.

Underneath all of it sits failover: a current copy standing by for the day the leader's hardware dies.

Your application has to take part, which catches people out. Your code, or a proxy sitting in front of the database, decides for every single query whether it goes to the leader or a copy.

Send a write to a copy and it fails loudly. Fine. Send a read to a copy that is three seconds behind and it fails quietly, which is what the third lesson of this chapter is about.

the shape of it
App serversLeaderall writesReplica 1web readsReplica 2analyticswritesreadsWAL streamWAL stream
step 1 of 2
The leader takes every write and streams its log to replicas, which absorb the read traffic.

Worked example

Nina's SaaS runs a single Postgres for a product doing 3,000 queries per second, 95 percent of them reads, and the machine is busy 85 percent of every afternoon. She adds two streaming replicas and routes reads by connection string: the web app's GET paths use the replica pool, everything else keeps hitting the leader. The leader drops to 30 percent busy. The louder win is the analytics team: their hourly dashboard queries, some scanning 40 million rows, move to a third dedicated replica, and the mysterious afternoon latency spikes on the product, which nobody had connected to the dashboards, stop the same day. Total change to application code: about 30 lines and one config file.