Learning center

Stale reads from a Cloud SQL read replica during a large write

When a Cloud Run service reads from a Cloud SQL read replica and returns data that is minutes old, check the replica's lag before the service. Cloud SQL applies the primary's changes to a replica asynchronously, so a large write on the primary can leave the replica behind. Reads that must see a write the same user just made belong on the primary; reads that tolerate the lag you measured can stay on the replica.

How it shows up#

A customer places an order, and the confirmation page says the order does not exist. A refresh a minute later shows it. The service logs no error. Meanwhile a backfill or a batch import runs against the primary, and if the replica sits in another region, the delay is longer.

Cloud SQL read replicas use PostgreSQL streaming replication: the primary writes changes to its write-ahead log (WAL), sends it to the replica, and the replica applies it. Changes are replicated and applied asynchronously, and a replica is read-only. Lag comes from three places: the primary cannot send fast enough, the replica cannot receive fast enough, or the replica cannot apply fast enough. Cross-region replication adds network latency. Read replicas · Replication lag

None of the four connection stages fails: the connection and the query succeed, and the answer is old.

Check 1: which reads go to the replica#

Start with the revision, since the replica is a second Cloud SQL instance with its own connection. The revision's run.googleapis.com/cloudsql-instances annotation lists both instances when it connects to both through Cloud Run's built-in connection; a separate host variable names the replica when it connects by IP. Connect from Cloud Run

gcloud run revisions describe REVISION \
  --project shop-prod --region europe-west1 \
  --format='yaml(metadata.annotations, spec.containers[0].env)'

gcloud sql instances describe orders-db \
  --project shop-prod --format='value(replicaNames)'

gcloud sql instances describe REPLICA \
  --project shop-prod \
  --format='value(region, masterInstanceName, instanceType, connectionName)'

replicaNames lists the primary's replicas, and on each replica masterInstanceName names its primary and region its location. Instance resource fields

The configuration tells you the service can read from the replica. Which code paths do depends on the application, so list the read paths that the symptom touches and check each one's data source in the code.

Check 2: read the lag in seconds and bytes#

Cloud SQL publishes three replica metrics that answer different questions:

MetricWhat it measures
cloudsql.googleapis.com/database/replication/replica_lagSeconds the replica is behind, computed as now() - pg_last_xact_replay_timestamp() on the replica. A negative value means replication is inactive
cloudsql.googleapis.com/database/replication/network_lagSeconds from commit on the primary to the replica's WAL receiver. Capped at 25 seconds
cloudsql.googleapis.com/database/postgresql/replication/replica_byte_lagBytes behind, reported from the primary per replica, with a replica_lag_type label that separates sent, written, flushed and replayed WAL

High replica_lag with low network_lag means the replica applies changes too slowly; high network_lag means the WAL is slow to arrive. Each metric is sampled every 60 seconds and can take up to 165 seconds to become visible, so the chart lags the incident by a few minutes. Monitor replication lag · Cloud SQL metrics

For the current value, ask the replica itself:

SELECT now() - pg_last_xact_replay_timestamp() AS replay_delay;
SELECT status, last_msg_receipt_time FROM pg_stat_wal_receiver;

pg_last_xact_replay_timestamp() returns when the last transaction the replica applied was committed on the primary. pg_stat_wal_receiver shows streaming and a recent receipt time while replication works, and no row when it does not. Recovery information functions · Verify replication

Replica reportsReading
streaming, delay of seconds, and a large write running on the primaryThe replica applies the write's WAL more slowly than the primary produces it. The lag ends some time after the write ends
streaming, delay growing while the primary is quietNothing new to replay: the timestamp is the last commit, so the delay grows with the clock. Compare byte lag before you act
No row, or a negative replica_lagReplication has stopped. The replica serves data from the moment it stopped. This is not lag, and waiting will not fix it

A query running on the replica can also hold replay back, because the replica waits before applying changes that remove rows the query still reads. The backfill lab measured that effect and the hot_standby_feedback trade-off: backfill replica lag comes from replay conflicts too.

Decide: which reads move to the primary#

The lag you measured during the large write is the staleness the replica's readers saw. Compare each read path with it:

Read pathTolerates the measured lag?Where it reads
Shows a user what they just wrote: confirmation pages, a profile after savingNo: any lag longer than the time between the write and the read shows the old statePrimary
Reads a value and writes based on it: stock checks, balance updatesNo: it writes from stale inputPrimary, in the same transaction as the write
Lists, search pages and reports that refresh anywayWhen the worst lag you measured is acceptable to their readersReplica
Anything during a planned backfill or importDepends on the lag that write producesRehearse the write and measure, or read from the primary for its duration

Moving reads to the primary changes the primary's load and connection count. Measure the connections that path opens before you move it.

A worked fixture: one stale page, two causes#

The fixture is illustrative. orders-api-00018 in europe-west1 writes to shop-prod:europe-west1:orders-db and reads order pages from orders-db-replica, a cross-region replica in europe-west4. A Cloud Run job starts a backfill of orders.state at 09:00 UTC.

Incident A. From 09:06, customers report missing orders on the confirmation page. At 09:12 the replica query returns replay_delay of 00:01:34 and streaming. The chart of replica_lag reaches 95 s at 09:10 and network_lag stays at 1 s, so the replica applies too slowly; replica_byte_lag for replay_location grows with each backfill batch. The confirmation page reads an order the same request created a second earlier, so with 94 seconds of lag it cannot find it. The team routes the confirmation and the order-detail reads to the primary in orders-api-00019, leaves the order list on the replica, and pauses the backfill between batches while byte lag exceeds a set limit. After the backfill ends at 09:41, replica_lag returns to 0 by 09:43.

Incident B. Same symptom, at 15:20. The replica query returns no row from pg_stat_wal_receiver, and replica_lag has been negative since 14:58. Replication has stopped, and gcloud sql operations list for both instances is the next read, for a restart or an update in the window. Waiting does not help the order list either, because the replica does not catch up while replication is stopped. Every read path goes to the primary until replication works again. Cloud SQL operation types

Where the checks mislead#

replica_lag is an approximation by Cloud SQL's own description. On a primary that commits nothing, the last replayed commit stays the same, so the computed delay grows although the replica is current; byte lag shows whether anything is outstanding.

The metric's 60-second sampling hides short spikes. A burst of 20 seconds can be invisible on the chart and still return stale pages during it.

A replica that keeps up today can fall behind during the next backfill, the next VACUUM on a large table, or the next long report on the replica. The decision table depends on the lag of the worst write you run, not the usual one.

Questions#

Why does my Cloud Run service show old data right after a write?

If it reads from a Cloud SQL read replica, the replica applies the primary's changes asynchronously. A read sent to the replica right after a write on the primary can come back before the replica has applied that write, and large writes widen that gap.

What does a negative replica_lag mean?

Cloud SQL's metric reference says a negative value means replication is inactive. Check pg_stat_wal_receiver on the replica: no row means it is not receiving WAL, and its data stays at the point where replication stopped.

Does a cross-region replica lag more than one in the same region?

Cross-region replication adds network latency, which shows up in network_lag. Whether it adds noticeable lag depends on how much WAL the primary writes; measure both metrics during your largest regular write.

One month of free code review.

New organizations get one calendar month of hosted code review for private and public GitHub repositories. No card or cloud connection required. Eligibility and fair-use terms.

Start free with GitHub

Related reading