Database architecture: replicas
This course explains how a Postgres read replica works and when one is worth adding. It covers streaming and replaying the write-ahead log, asynchronous replication and replication lag, and the writing and reading roles in Rails, with replica: true and connected_to. It examines read-your-own-writes failures, measures one application's read share and database time, and identifies the single query that could justify a replica. It also shows how GET requests can write. It ends with a challenge to implement replica routing logic.
What you'll learn
- ✓How a replica streams and replays the primary's write-ahead log
- ✓Why replication lag grows with write volume and causes read-your-own-writes failures
- ✓Declaring writing and reading roles in Rails and routing with connected_to
- ✓Measuring whether the primary is saturated before adding a replica
- ✓Finding writes hidden in GET requests before routing by HTTP verb
- ✓Implementing the choice between primary and replica for each request
What a replica actually is
A read replica is a second database that copies everything the first one does, a little later. Both halves of that sentence matter, and the second half is where every replica problem comes from.
Read the full lesson free →Curriculum
7 lessonsWhat a replica actually is
A replica streams and replays the primary's write-ahead log asynchronously, and it is neither a backup, a shard nor failover.
The reading role
Rails declares writing and reading roles in connects_to, marks replicas with replica: true, and routes explicitly with connected_to.
Replication lag is the whole problem
Replication lag causes read-your-own-writes failures, grows with write volume, and is covered by a two-second default window.
This application has no replica
The application has no replica because only about 21 ms of a 72 ms request is database time.
When a replica actually helps
A replica helps when expensive reads that tolerate stale data saturate the primary, as Admin::StatsQuery could.
The writes hiding in your reads
TrackLessonVisitService and the activity tracker write during GET requests, which breaks routing to a replica by HTTP verb.
Putting it together
A recap of the course and a challenge to implement choose_connection, including the case where elapsed time equals the lag.