Scrivio Interview library
DebuggingIntermediate6 min read · updated 13 November 2026

An alert on a PostgreSQL replica fired at 03:00 with replication lag of 25 minutes, measured as now() - pg_last_xact_replay_timestamp(), yet nothing was behind. On another night a MySQL replica reported Seconds_Behind_Source = 0 while reads from it were clearly minutes old.

Explain both false readings and how you would measure replication lag reliably.

Both readings are artefacts of what the metric measures. pg_last_xact_replay_timestamp() is the commit time of the last replayed transaction, so when the primary is idle at 03:00 it stops advancing and now() minus it grows with the clock while the replica is fully caught up. Seconds_Behind_Source is computed from the events the applier has executed, so when the receiver is slow or stalled the applier has nothing queued and can report 0 while the data is minutes old. The reliable method is a heartbeat row written on the primary every second and compared on the replica, plus log position comparisons, with synchronised clocks and alerts on lag in both bytes and seconds.

Why this question is asked

Replication lag drives real decisions: whether to send reads to a replica, whether a failover is safe, whether to page someone at three in the morning. A lag metric that cries wolf at night and stays silent during a real outage is worse than none. Interviewers ask about these two false readings because both come from popular, built-in metrics, and explaining them shows we know what those metrics actually compute. In this answer, we will explain each false reading, then build a reliable measurement with heartbeats and log positions, and finish with the alerting rules.

1The PostgreSQL False Alarm

pg_last_xact_replay_timestamp() returns the commit timestamp, as recorded on the primary, of the last transaction the replica has replayed. During the day, transactions arrive constantly, so now() minus that value is a good estimate of lag. But at 03:00 the primary may commit nothing for 25 minutes. The replica has replayed everything there is, so the last replayed commit is 25 minutes old, and the formula reports 25 minutes of lag. Nothing is behind; there is simply nothing new.

Notice the general lesson: this metric measures how old the newest replayed transaction is, which equals lag only when the primary is busy.

2The MySQL Silent Reading

Seconds_Behind_Source, shown by SHOW REPLICA STATUS, is calculated by the applier (SQL) thread as the difference between the replica's clock and the original timestamp of the event it is executing, corrected for clock difference. It only knows about events that have reached the relay log. If the receiver (I/O) thread is slow, for example because the network link is saturated, or the connection has silently stalled and the receiver still thinks it is connected until replica_net_timeout expires, the applier finishes everything in its relay log and becomes idle. An idle applier reports 0, even though the source has minutes of transactions the replica never received.

So a 0 means the applier is caught up with what it has, not that the replica is caught up with the source. When the receiver is not running at all, the field shows NULL, which is at least visible. The full status also lists Replica_IO_Running and the last received transaction, which reveal the stall.

What popular lag metrics actually measure
MetricWhat it measuresMisleads when
now() - pg_last_xact_replay_timestamp()age of the last replayed commitprimary is idle: grows though caught up
pg_stat_replication.replay_lagdelay of recent WAL to replayno WAL flows: value goes stale
Seconds_Behind_Sourceage of the event the applier runsreceiver slow or stalled: shows 0
Byte lag (LSN or GTID positions)how much log is not yet appliednever false, but not in seconds
Heartbeat row agetime since a known write became visibleclocks unsynchronised

3A Reliable Measurement: The Heartbeat Row

The fix for both problems is to make sure there is always something recent to measure. A small job on the primary updates a heartbeat row every second with the current time. That update replicates like any other change. On the replica, lag is now minus the replicated timestamp. If the primary is idle, the heartbeat still flows, so the value stays near zero. If replication stalls anywhere, in the network, in the receiver or in the applier, the heartbeat stops arriving and the value grows by one second every second, exactly as it should. pt-heartbeat implements this for MySQL, and the same idea works for PostgreSQL.

SQL
-- on the primary, every second (a cron-like job or a background worker)
INSERT INTO ops.heartbeat (id, ts) VALUES (1, now())
ON CONFLICT (id) DO UPDATE SET ts = excluded.ts;
-- on the replica
SELECT extract(epoch FROM now() - ts) AS lag_seconds FROM ops.heartbeat WHERE id = 1;
-- 0.4 at 03:00 with an idle primary
-- 187.0 when the replica has received nothing for three minutes

The heartbeat measures what we actually care about: how old is the newest data a reader on this replica can see. Its one requirement is that the primary's and the replica's clocks agree, because the timestamp is written on one machine and compared on the other. With NTP or chrony keeping them within a few milliseconds, the error is negligible.

4Comparing Log Positions

Positions are a second, independent signal. In PostgreSQL, the primary's current WAL position is pg_current_wal_lsn(), and the replica's replay position is pg_last_wal_replay_lsn(). The difference, computed with pg_wal_lsn_diff(), is the lag in bytes: how much log the replica has yet to apply. The primary's pg_stat_replication view also shows sent, written, flushed and replayed positions per replica, and replay_lag, an estimate in time. Be aware that replay_lag is only updated while WAL flows, so on an idle primary it shows the last measured value rather than zero.

In MySQL, comparing the source's executed GTID set with the replica's received and executed sets gives the equivalent. Recent versions also expose the original commit timestamp of the last applied transaction in the performance_schema replication tables, which helps; check your version for the exact columns. Byte lag never gives a false alarm on an idle primary, because no new bytes means zero bytes behind.

5Alerting on Lag

We alert on two values. Lag in seconds, from the heartbeat, answers the user question: how stale can a read be? Lag in bytes answers the operational question: how much work does the replica have to catch up, and how long will that take at its replay rate? A replica can be seconds behind but gigabytes behind after a bulk load, and that matters for failover.

Thresholds come from how the replica is used. A replica serving user reads might alert at 5 seconds sustained for a minute; a reporting replica at 10 minutes. Alerting on a sustained value avoids paging for a single slow transaction, and alerting when the heartbeat is missing entirely, not just old, catches a broken heartbeat job before it hides a real outage.

6Follow-up questions

Why not just fix the PostgreSQL query with a check for an idle primary?

A common workaround returns 0 when the replica's received and replayed positions are equal. That handles idleness on the replica side but cannot tell whether the replica is still receiving from the primary at all; a heartbeat covers both cases with one measurement.

Can the heartbeat itself cause load?

One single-row update per second is negligible for the primary and the replicas. It does generate a small steady stream of WAL or binlog, which also keeps byte-based metrics such as replay_lag fresh.

What if the clocks drift?

The heartbeat lag is off by the clock difference, and can even go negative. Keep clocks synchronised with NTP or chrony, and alert on clock offset on database hosts, since several other database features also assume sane clocks.

7Conclusion

In this answer, we saw that both false readings come from what the metrics compute. pg_last_xact_replay_timestamp() measures the age of the last replayed commit, so it grows on an idle primary, and Seconds_Behind_Source only sees events already in the relay log, so it shows 0 when the receiver is slow or stalled. A heartbeat row written every second on the primary and read on the replica measures real staleness, log position comparisons give lag in bytes, clocks must be synchronised, and alerts should cover both seconds and bytes.

What to say in the interviewAbout 100 seconds aloud

Open with

Both readings are measuring something other than lag. In PostgreSQL, now minus pg_last_xact_replay_timestamp is the age of the last transaction the replica replayed. During the day transactions keep coming, so it tracks lag, but at three in the morning the primary was idle for 25 minutes, so the last commit was 25 minutes old even though the replica had everything.

Then, if they want more

In MySQL, Seconds_Behind_Source comes from the applier thread comparing its clock to the timestamp of the event it is running. It only knows about events that reached the relay log. If the receiver is slow or the connection has silently stalled, the applier finishes its queue, goes idle and reports zero while the replica is minutes behind the source.

So I would check the receiver status and the received GTID set too. To measure reliably, I write a heartbeat row on the primary every second with the current time, which replicates like any change, and on the replica compute now minus that timestamp.

On an idle primary it stays near zero, and if replication breaks anywhere it grows second by second; pt-heartbeat does this. I would add byte lag from positions: pg_current_wal_lsn on the primary against pg_last_wal_replay_lsn on the replica, and replay_lag in pg_stat_replication, keeping in mind it only updates while WAL flows.

The heartbeat compares times from two machines, so clocks must be synced with NTP or chrony. Then I alert on seconds and bytes, sustained for a minute, and on a missing heartbeat.

About this answer

Last updated
13 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Explain both false readings and how you would measure replication lag reliably.": https://scrivio-interview-library.netlify.app/architecture/partitioning-and-replication/85357853b0/