Skip to content
AE DIGITAL
Digital SystemsBy 7 min read

Ecommerce read replicas: replication lag, consistency and read-after-write

A practical model for scaling reads without showing stale orders, profiles or stock: consistency classes, routing, watermarks and release gates.

A luminous data stream propagates from a primary database toward read replicas with different replication delays

Scale reads without misleading customers

A read replica can absorb catalogue, search, reporting and other queries, reducing pressure on the primary database. The benefit has a semantic cost: managed services normally propagate changes asynchronously. There is a window between commit on the primary and replay on the replica during which a query can return the previous state. AWS, Google Cloud, Microsoft and PostgreSQL expose different implementations and measurements, but the application consequence is consistent: a replica provides eventual consistency, not a universal freshness promise.

Ecommerce makes that window visible immediately after an action. A customer changes an address and sees the old one, pays for an order that appears missing, or applies a voucher that is absent from the refreshed summary. Sending every query to the primary defeats read scaling, while accepting every anomaly damages trust. The system needs explicit read classes, context about the latest write and deterministic routing.

Understand where replication lag appears

From WAL to visible query results

With PostgreSQL, the primary records modifications in the write-ahead log and can stream them to a standby. The path has several stages: generation, transmission, receipt, write, flush and replay. A replica may have received bytes that it has not replayed, so a healthy network alone does not prove that a transaction is queryable. Log sequence numbers, or LSNs, describe progress at each stage without turning elapsed time into an absolute guarantee.

Lag changes with write volume, bandwidth, I/O, replay capacity, long queries, maintenance and geographic distance. A low value observed a minute ago does not protect the next request. Provider metrics must also be interpreted according to their definition: they may express seconds, bytes or one stage of the pipeline. A useful dashboard combines lag with WAL throughput, replication errors, process state and machine pressure rather than collapsing everything into one green light.

Define consistency classes by journey

Not every read has the same consequence. Editorial product content, recommendations and popular lists often tolerate a short delay. Order history directly after purchase, a profile immediately after an edit, stock used to confirm checkout and refund status need a stronger relationship with the write. Classify the business impact of stale data rather than applying a rule to a whole table.

A routing matrix gives every endpoint an owner, default source and fallback rule. Useful classes are eventual, session-monotonic and read-after-write. These are design contracts, not automatic driver features. Each class records acceptable staleness, affected entities, preceding actions and the response when no replica meets the requirement.

Implement read-after-write deliberately

Temporary stickiness and watermarks

The simplest mechanism is stickiness: after a successful write, the session reads from the primary for a short window. It is easy to deploy, but a fixed duration is only an approximation. If lag exceeds it, the anomaly returns; if lag is much lower, primary capacity is wasted. Keep the window bounded, observable and scoped to the relevant entity or session instead of the entire site.

A more precise control stores a write watermark, such as a log position or application token. Before selecting a replica, the router verifies that it has reached that point; otherwise it waits within a small budget or reads from the primary. This pattern avoids treating average lag as proof of visibility. It requires database support, appropriate permissions, timeout handling and a token format that survives API, queue and service boundaries.

PostgreSQL also supports synchronous configurations and the remote_apply level, where commit can wait until a chosen synchronous standby has replayed the transaction. This is a selective control, not a setting for every read replica. It adds commit latency and couples write availability to the selected standby, so it belongs only on measured journeys with a clear policy for standby loss.

Build a consistency-aware read router

The router needs at least the consistency class, entity identity and session context. An eventual read may use any healthy replica. A watermark read selects only a replica beyond that point. A read-after-write request without sufficient evidence returns to the primary. Random load balancing across replicas does not provide monotonic reads: the second request can land on a replica farther behind than the first.

Failure handling must preserve semantics. If the freshness check is unavailable, a sensitive endpoint must not pretend that any replica is acceptable. It can use the primary, return a processing state or defer within its latency budget. Checkout often benefits from an explicit controlled response rather than a confident answer based on stale data.

Protect stock, orders and caches

Read replicas do not turn an observation into a reservation. Overselling protection remains on the write path through transactions, constraints or reservation logic against authoritative state. A product page may show indicative availability from a replica, but final confirmation must validate the current state. Likewise, an order missing from a replica is not permission to create another order.

A cache adds a second staleness window. A current replica behind a key that was not invalidated still returns old content; a cache filled from a lagging replica can even reintroduce an older version. Carry versions or watermarks in invalidation events, reject regressive updates and separate editorial TTL decisions from transactional consistency. Cache age and replication lag are different signals.

Monitor the service, not one number

Signals and operational thresholds

Operational views combine replica health, distance from the primary, receive and replay delay, WAL volume, I/O, CPU, errors and restarts. Application measures complete the picture: proportion of reads diverted to the primary, watermark waits, fallback rate, detected monotonicity violations and cases where a newly created order is not visible. Provider-specific metrics are inputs, not the user-facing contract.

Thresholds vary by class. Reporting can continue on a degraded replica while a freshly saved profile moves to the primary. When lag grows, reduce non-essential reads, throttle heavy jobs and protect primary connection capacity. Unlimited fallback can suddenly move the entire workload to the most important node and create a larger incident.

Test delayed replay and recovery

A meaningful test injects lag, stops a replica, slows replay and alternates replicas at different positions. It then executes complete journeys: create an order and open its detail, edit an address and reload the profile, reserve stock and confirm checkout. Assertions cover the returned data, selected source, wait duration and behaviour when the budget expires.

The release gate checks the routing matrix, watermark propagation, absence of regressive reads, fallback limits and alerts connected to a runbook. A read replica is not automatically a high-availability standby: promotion, endpoints, potential loss and operating procedure depend on the service. To design a strategy across databases, caches and checkout, explore our ecommerce systems services. To verify routing and resilience tests on your architecture, contact AE Digital Agency.

Frequently asked questions

Does a read replica always return the latest committed data?

No. Replication is normally asynchronous, so the replica may not have replayed the primary's commit when the query arrives.

How can an application provide read-after-write consistency?

It can temporarily read from the primary or carry a write watermark and use a replica only after that replica reaches it.

Is a replication-lag metric enough to prove freshness?

No. Definitions and measured stages differ, so combine the metric with replay progress and application-level visibility checks.

Should checkout confirm stock from a read replica?

A replica can provide indicative availability, but reservation and final confirmation must validate authoritative state on the write path.

Sources

  1. 26.2. Log-Shipping Standby Servers — PostgreSQL Global Development Group
  2. Working with DB instance read replicas — Amazon Web Services
  3. Monitoring and tuning the replication process — Amazon Web Services
  4. Manage read replicas — Google Cloud
  5. Read replicas in Azure Database for PostgreSQL Flexible Server — Microsoft Learn

Related articles

Tell us what isn't working.

We reply within one business day with a first opinion and, if it makes sense, a quote.

Write to us