System Design
Primary-Replica Replication (Read Replicas)
O(1) time to append one write to the primary's log · O(k) time for a replica to catch up on k unapplied log entries.
The idea, in plain English
Picture a teacher — the 'primary' — writing notes on the whiteboard. Several students — the 'replicas' — copy those notes into their own notebooks. That way everyone can read them without crowding around the board. Only the teacher writes new notes; students just copy. That's replication. One primary database handles all the writes, and streams every change to one or more replica copies. Spreading reads across the replicas lets far more people read at once. But a slow-copying student's notebook might briefly lag behind what's on the board. This is called replication lag.
How it works
- 1Every write goes to exactly one server: the primary. It applies the change, and appends it, in order, to a running log of everything that changed.
- 2Each replica reads that log and applies the same changes, in the same order, to its own copy of the data.
- 3Reads get spread across the replicas, instead of all hitting the primary. This way, read traffic doesn't overload the one server that also handles writes. A replica that hasn't caught up yet may return slightly stale — out-of-date — data.
When you'd use it
Use this once your app is popular and has far more reads than writes — like a blog, a product catalog, or a news feed. Add several read replicas, so all that read traffic doesn't pile onto the one server that's busy handling writes.
Common beginner mistakes
- Sending a write straight to a replica. Replicas are meant to be read-only copies. Writing to one breaks the whole replication setup.
- Assuming a replica is always instantly up to date. Reading from a lagging replica right after a write can show you the old value. This is called the 'read-your-own-writes' problem.
Try it — edit and run
Click the code to edit · press ⌘/Ctrl+↵ to run
Editable code. Tab and Shift+Tab indent. Press Escape, then Tab, to move focus out of the editor.
Primary: title=Hello World v2, views=25
Replica A (caught up): title=Hello World v2, views=25
Replica B (lagging): title=Hello World, views=10
Replica B has applied 2 of 4 writes — reads from it may be stale.Not sure this is the right topic? See the learning paths → or where this leads →