Skip to content

Replicate data and observe lag

11 min reading

Explain primary/replica behavior, acknowledged writes and failover uncertainty

Page details

System Design · Store and find data

11 min reading · 24 min with practice

Sources

Published · Last edited:

Prerequisite: Make queries fast and account for write costs. For basics, use the independent System Design foundations.

More
20px

Hypothetical scenario. A seller changes a promotion price and receives success. The next visitor is routed to another healthy database copy and receives the previous price. Dev checks that both processes are running. Priya asks what the successful write actually promised about that second copy.

Dev: “The replica is available to answer.”

Priya: “Available with which version, and what evidence tells us that?”

Trace one change from the authoritative writer to its read replica. Separate acknowledgement, receipt, replay and visibility before choosing a routing rule. Keep Northwind’s price-age contract beside the trace; a process-health check does not establish that contract.

What did the successful write promise about each copy?

Replication maintains additional copies of data or a sequence of changes. A primary-and-standby arrangement assigns the primary responsibility for accepting changes and sends information needed to reproduce them elsewhere. An asynchronous arrangement can acknowledge the writer before a particular standby has received or applied the change.

That can be a valid design when the service allows the resulting delay and failure exposure. The mistake is allowing a writer’s acknowledgement to imply a visibility guarantee that the selected replica cannot provide. Northwind’s public browsing rule permits a bounded price age, but the seller’s own editing interface may need a different observation contract.

Keep those audiences explicit. A visitor reading an eligible public price and a seller checking a just-submitted change are different actions. A single global rule saying “all reads use replicas” ignores that distinction. The later consistency chapter will compare stronger observation contracts; here we establish the processing boundaries they depend on.

Follow the change through the pipeline

First, the primary accepts and commits the change under its selected durability configuration. It makes replication information available to the standby. The standby receives that information, retains it under its own persistence rules and replays it into state that a query can observe. Received, durable and applied are useful separate labels even when an implementation groups some steps together.

A read sent to a standby that has durably received a change can still miss it if replay has not reached that point. A standby that applied a change is not automatically authorized to accept new writes. Currency, durability and authority answer different questions and should not collapse into one green health indicator.

A change crosses distinct replication boundariesA primary accepts a price change. A standby receives the change, persists it and applies it before a query observes it. The writer acknowledgement covers a configured boundary, while read routing must inspect the visibility needed by the caller.PrimaryCommitStandbyReceiveStandbyPersistStandbyApplyWhich boundary does acknowledgement cover?Which boundary does the reader need?
Acknowledgement and visibility need named boundaries.

Name the replication acknowledgement point

Hypothetical scenario. Call one selected PostgreSQL WAL position L. The primary can flush L locally, a standby can receive it, flush it durably and later replay it. A client acknowledgement belongs to the configured wait condition; those intermediate facts are not interchangeable.

Name the replication acknowledgement point — selected design evidence
Position L factWhat it establishesWhat remains unknown
Primary flushLocal durability at primaryCandidate has L
Standby flushCandidate durable receiptReader has replayed L
Standby replayL applied for reads thereAll replicas / clients observe L
The selected acknowledgement policy determines which standby fact precedes the client reply.The selected acknowledgement policy determines which standby fact precedes the client reply. Client to Primary WAL: 1 · write; Primary WAL to Standby: 2 · send L; Standby to Primary WAL: 3 · configured acknowledgement; Primary WAL to Client: 4 · client reply.ClientPrimary WALStandby1 · write2 · send L3 · configured acknowledgement4 · client reply
The selected acknowledgement policy determines which standby fact precedes the client reply. Enlarge the diagram to inspect its labels; the surrounding records and explanation give the text alternative.

A reader routed to a lagging standby may not observe the acknowledged write. To obtain read-your-writes, route to an authority known to include the session's required position or wait until a selected standby has replayed it. Carrying a position establishes a session requirement; it does not by itself make every reader globally linearizable.

Promotion needs more than a small lag chart. Decide which acknowledged positions the candidate must include and fence the former primary from accepting authoritative writes. A paused old writer can resume after promotion. If both remain writable, a newer hostname does not repair divergent histories. Keep restoration and replication distinct: replaying an erroneous delete faithfully is not recovery of the earlier correct data.

Primary mechanism reference: PostgreSQL replication stages. Use its implementation scope when evaluating this design.

Configure a promise rather than a slogan

PostgreSQL’s standby documentation describes streaming and synchronous replication mechanisms. The important architectural question is what the configured acknowledgement waits for and which standbys participate. “Synchronous” without those details is not a complete application guarantee.

Waiting for another copy can improve the survival property for a selected failure, while adding that copy’s communication and processing to the write path. If a required standby is unavailable, the write may wait or fail under the selected configuration. Decide which trade-off fits the action instead of assuming that stronger waiting is free.

The earlier 400 ms browsing deadline concerned presenting a catalogue read. It is not automatically the seller’s write deadline. The two operations can share infrastructure while having distinct service goals. A design should preserve that distinction before adding remote durability dependencies to every price update.

Derive replay backlog from the selected change stream

Hypothetical worked example. Continue the selected maintenance workload of two price changes per second from the data-model lesson. Suppose a standby is four seconds behind in applying that uniform stream. The illustrative unapplied count is 2 × 4 = 8 changes. This is an accounting estimate under fixed rates, not a general conversion from a lag dashboard into lost transactions.

Now choose a replay capacity of three changes per second while the primary continues producing two. Net catch-up is 3 − 2 = 1 change per second. Draining the eight-change backlog takes 8 ÷ 1 = 8 seconds under those constant assumptions. Dividing by three would incorrectly ignore the new changes arriving during recovery.

If replay falls to 1.5 changes per second, the gap becomes 2 − 1.5 = 0.5 changes per second in the wrong direction. Over ten seconds, the backlog grows by 0.5 × 10 = 5 changes. A connected replica can therefore fall further behind even when its network transport looks healthy.

Changes may differ greatly in size and replay cost. For an actual deployment, inspect the relevant log positions, processing rates and query effects. The selected count model helps identify a missing catch-up margin; it does not establish a measured production recovery time or a permanent-loss count.

Join replication delay to the price-age rule

The edge lesson showed why storage in a fresh HTTP response does not reset the underlying price-evidence clock. Replication adds another place where that clock can advance. Suppose the selected upstream evidence age is forty-five seconds, replica delay adds four, cache residence adds twenty and delivery/presentation adds one. Total age is 45 + 4 + 20 + 1 = 70 seconds.

That violates Northwind’s selected sixty-second limit despite a healthy replica connection and a cache entry younger than thirty seconds. With those upstream and delivery terms, cache residence has at most 60 − 45 − 4 − 1 = 10 seconds of remaining allowance. This remains a planning calculation; a real policy needs trustworthy age evidence and a definition of what that evidence means.

Route according to the observation the caller needs

A public browsing request can use a replica only if the selected representation remains eligible. A seller checking an acknowledged change might instead read from an authoritative path or carry a version/position requirement that the chosen read target must satisfy. The mechanism depends on the database and application; the architectural requirement is to make the observation contract explicit.

Do not route every slow replica read to the primary without checking capacity and deadlines. Such a fallback changes demand during the failure condition. The primary also handles the change stream, so the fallback can turn an observation problem into an overload problem. Bound the behavior and keep rejected or delayed outcomes visible.

In the wild: standby operation exposes these distinctions

PostgreSQL’s public documentation makes standby operation and replication choices inspectable. It is useful evidence that received information, replay and synchronous waiting need separate consideration. It does not certify Northwind’s selected rates or prove that a particular read observed a particular price change.

Hypothetical failure scenario. Northwind’s health probe checks that the standby accepts a connection. Replay stalls, but the routing layer continues sending price reads there. Responses arrive quickly while their evidence becomes too old. Replacing a shallow connectivity claim with visibility evidence addresses the actual failure condition.

Copies solve a declared failure problem

Replicas can support read placement or survival of selected machine failures. They do not replace retained history and a tested restore procedure. A mistaken deletion can propagate successfully to every current copy. Separate the need for another usable current copy from the need to recover an earlier correct state.

Promotion is also a separate decision. If the primary becomes unreachable, a monitor has evidence of a communication problem, not proof that the old writer stopped. Safe promotion must establish suitable state and exclude obsolete writers. The later failure and consensus lessons develop that authority problem; do not infer it from replica count.

Northwind now has a read-routing requirement tied to visible version and age, plus a catch-up calculation to measure. The next page asks a different scaling question: what if one owner cannot hold or serve the whole dataset? Partitioning will divide responsibility while replication continues to provide copies within each responsibility.

Challenge the proposed mechanism

A primary replies after local flush, then disappears before sending L. May the standby promise no acknowledged-write loss?

Reveal the design reasoning

Not from those facts. Either wait for the required durable replica before acknowledging, keep the unavailable outcome while recovering the original authority, or explicitly accept the documented loss window. Fence the old writer before admitting replacements.

Decision and reconsideration: Record durability, visibility and promotion requirements separately. Test crashes at each acknowledgement boundary before changing replication policy.

Inspect the promised boundary

  1. The standby has received a change. Must a query see it?

    Locate replay visibility

    No. Receipt and application are distinct. The read must reach state that has applied the required change under the selected database’s query semantics.

  2. Why does an eight-change backlog take eight seconds to drain at three changes per second?

    Subtract continuing generation

    The primary still generates two changes per second. Net progress is 3 − 2 = 1 per second, so 8 ÷ 1 = 8 seconds under the fixed-rate model.

  3. Four seconds of replica delay fits a separate operational target. Is the sixty-second price-age goal established?

    Join the full evidence path

    No. Upstream age, replica delay, cache residence and delivery must fit together. The selected example totals seventy seconds even though replica delay alone looks small.

Replicas create additional observation points for the same data. Page 15 divides ownership of different data, then asks why distributing identifiers evenly may still leave one owner overloaded.

Northwind decision log

Name the receive, persistence and visibility boundary covered by each promise.
Route reads using their required observation and full evidence-age budget.
Measure catch-up margin before treating a connected replica as current.

Go deeper: copies and read observations