Lesson 04

Read Replicas and Lag

Building block

A read replica is a full copy of the database that answers reads while the primary takes every write. It is the read path's second tool, and it answers what a cache cannot: the misses, and the queries no cache key holds, such as a search by attribute or a range of dates.

It is paid for in freshness. Every replica is behind the primary by its lag, and this lesson is about what that lag breaks for a user and the routing that puts it right. How one engine does all of this is PostgreSQL Deep Dive's chapter on replication.

Reads Spread Over Copies

Replicas scale reads, never writes, because each one applies every write the primary takes. Behind a 99 percent cache, the store sees 200 misses a second at peak, the figure from Caching at Scale. Assume three replicas: they take about 70 each, and the primary is left to the writes.

Each replica also applies all of the writes, 200 a second at peak in the URL shortener of Chapter 7, and holds the whole data set. So replicas do nothing for a load heavy in writes, or for data too big for one machine; that is partitioning, in Chapter 3. The number of replicas comes from a rate per replica that you state as an assumption, because this course has no figure for what one relational node can serve.

The cache first, three replicas for its misses, every write to the primary
App serversroute each read Cache tier99% of reads Replicabehind by its lag Replicabehind by its lag Replicabehind by its lag Primaryevery write key miss, 1% async own write write readwriteasynccache miss
Read Replica vs Cache

A cache answers the hot set by key at memory speed, and is stale by its expiry time or its invalidation. Use it when reads repeat a small set of keys.

A read replica answers any query the database can, ranges and searches included, and is stale by its lag. It costs a full copy of the data and applies every write. Use it when the reads left after the cache are varied, or when the misses need more than one node. Most read-heavy designs draw both: the cache first, and the replicas behind it for the misses.

Where Lag Comes From

With asynchronous replication, the primary acknowledges a write before any replica has it; synchronous replication, and what it costs, comes in Chapter 4. Lag is usually small and never bounded. It grows in a burst of writes, behind a long query running on the replica, and after a restart.

Distance sets a floor. A replica in western Europe of a primary in US east is behind by at least half of the 85-millisecond round trip, about 40 milliseconds, before anything else adds to it. And a replica promoted when the primary fails has lost every write it never received. How much may be lost is Chapter 6's question; how one engine fails over is PostgreSQL Deep Dive's.

What Lag Breaks

Lag shows up as three behaviours a user notices, each with the name of the guarantee it breaks; Chapter 4 has the models in full. The first is read-your-writes. A user renames a document, and the next page, served from a replica, shows the old name.

The second is monotonic reads. Two refreshes reach replicas with different lag, and a new comment appears, then vanishes. The third is the costly one: stock, a balance or a uniqueness check read from a replica lets a write act on a past that no longer holds, and the last item is sold twice.

Routing That Restores Them

Each fix is a routing rule, and each rule has a cost. For read-your-writes, send a user's reads to the primary for a window after their own write, a window longer than the lag at which a replica is taken out of rotation. It costs those reads on the primary, and for a reader in western Europe, the 85-millisecond round trip to it. The other way is to carry the write's position in the replication log in the session, and let a replica answer only once it has applied that position; PostgreSQL Deep Dive shows one engine's form.

For monotonic reads, pin each user to one replica by a hash of the user ID. When that replica is lost its users move, and they may see one step back. A read that decides a write goes to the primary, every time. And long reports get a replica of their own, at the price of one more full copy.

Where each read goes
It decides a write: stock, a balance, a uniqueness check→The primary
It follows the user's own recent write→The primary for the window, or a replica past the log position
Browsing→Any replica, pinned per user
A long report→A replica of its own

Replicas and the Cache Together

Put the cache and the replicas together, and the read path has a failure neither part has alone. A write commits and deletes the cached key. A read misses inside the lag, and fills the cache from a replica that has not applied the write yet. The old value now lives in the cache for its full expiry time, so the staleness is the expiry time, not the lag.

The stale fill, in four steps
Writecommits, deletes the key
→
Readmisses inside the lag
→
Fillfrom a replica still behind
→
Stalethe old value, for the full expiry

There are two fixes. Fill misses on keys written within the lag window from the primary, at the cost of those reads landing there, or delete the key a second time once the window has passed. Either way, take a replica out of rotation when its lag passes the window, because every fill from it is a stale entry waiting to happen.

How Interviewers Probe This

The answers here name the read, its route and what that route costs. The rule fits in one sentence, and it is worth having ready. You might say: "Reads that decide a write go to the primary; the rest can be a few seconds behind, and a user's own reads go to the primary right after they write."

The first probe is "A user changes their display name and the page still shows the old one. Why, and what do you do?" A good answer names the replica's lag, or a stale cache fill from a replica, picks a routing fix with its cost, and gives the window and what happens when the lag exceeds it.

The second is "During a nightly batch, one replica falls thirty seconds behind. What breaks?" A good answer sorts the reads that tolerate thirty seconds from those that do not, takes the replica out of rotation once it passes the window, and names the cache fills from it as the hidden cost.

The third is "Reads keep growing. Why not add replicas forever?" A good answer says that each replica applies every write and holds every byte, so writes and storage stop it. Repeated reads belong in the cache, and size and writes belong to partitioning, which is Chapter 3.

Misconceptions
  • "Replicas scale the database." They scale reads. Every write still lands on the primary and is applied again on every replica.
  • "Lag is a few milliseconds." Usually, and without bound under a burst or a long query. The routing is built for the worst case, not the median.
  • "Sending the user to the primary after a write fixes lag." It fixes their own writes. Other users' reads, and monotonic reads, still see the lag.
  • "A replica is a backup." It applies a mistaken delete within its lag. A backup is a point in time you can go back to.
  • "Synchronous replication removes the problem." Every write then waits for a replica, so a slow or lost replica slows or stops the writes. And the wait is usually for the replica to store the write, not to apply it, so a read there can still be behind.
Why It Matters
  • Send every read that decides a write, such as stock, a balance or a uniqueness check, to the primary.
  • Give read-your-writes a named mechanism: the primary for a window after the user's write, or a log position the replica must have applied.
  • Take a replica out of rotation when its lag passes the routing's window, and alert on that number.
  • Fill the cache for a just-written key from the primary, or delete it again after the lag window, so the lag does not stretch to a full expiry.
RelatedPostgreSQL Deep Dive lag, routing and failover in one engineCaching at Scale the first read-path toolConsistency Models That Come Up the guarantees lag breaks

Knowledge Check

A database takes 200 writes a second at peak, and three read replicas are added. What happens to the write load?

  • The primary still takes all 200, and each replica applies all 200
  • The writes split three ways, about 70 a second on each of the replicas
  • The primary takes the writes, and each replica applies a third of them
  • The writes move to the replicas, and the primary is left with the reads

Which of these reads must go to the primary rather than to a replica?

  • The stock check made just before an order takes the last item
  • A product page that a visitor opens from the results of a search
  • The monthly report on orders that finance runs on a Monday
  • The list of comments on a post that a reader scrolls back through

After a user's own write, their reads go to the primary for a window. What does that cost?

  • Their reads load the primary, and a distant user pays its round trip
  • Every other user's reads move to the primary for the same window
  • The write must wait for every replica to apply it before it returns
  • The user is pinned to one load balancer for as long as the window lasts

A write deletes a cached key. A read misses inside the lag and refills the key from a replica. What follows?

  • The old value stays cached for its full expiry, not just for the lag
  • The replica refuses that read until it has applied the newest write
  • The cached value corrects itself once the replica has caught up
  • The read fails, and the client retries it later against the primary

The primary is in US east and one replica is in western Europe. What is the least lag that replica can have?

  • About 40 milliseconds, half of the 85-millisecond round trip
  • About 85 milliseconds, the full round trip between the regions
  • Under a millisecond, as with any replica that is asynchronous
  • About 2 milliseconds, the same as for a replica in another zone

You got correct