Write a check for Postgres replication lag on a replica.
IntermediateScenarioScenarios: health checks, monitoring and alerts
Answer
Situation read → On a replica, compare now with the last replayed transaction timestamp.
What I'd do →
lag=$(psql -XtAc "select coalesce(extract(epoch from now() - pg_last_xact_replay_timestamp()), 0)::int" 2>/dev/null) ||
{ echo "CRIT cannot query replica"; exit 2; }
if (( lag > 300 )); then echo "CRIT replication lag ${lag}s"; exit 2
elif (( lag > 60 )); then echo "WARN replication lag ${lag}s"; exit 1
else echo "OK lag ${lag}s"; fi
-Xignores~/.psqlrc,-tAgives a bare value.- On a quiet primary, replay timestamps stop advancing even with zero lag; compare
pg_last_wal_receive_lsn()andpg_last_wal_replay_lsn()too, or write a heartbeat row on the primary every minute.
Why → Reads from a lagging replica return stale data, which breaks business logic silently.
Interview tip → Mention the idle-primary false positive; it shows you have run this in production.
More on Scenarios: health checks, monitoring and alerts
You are asked for a host health-check script covering disk, memory, systemd services and an HTTP endpoint. How do you design it?IntermediateYour disk alert fires and clears every few minutes around 80%, spamming Slack. How do you fix the alerting?AdvancedA server reports `No space left on device` but `df -h` shows 40% free. What would you add to the health checks?BeginnerAlert when any certificate under `/etc/letsencrypt/live` expires within 21 days.IntermediateA developer wrote a Bash loop that restarts the app whenever its process disappears. What do you suggest instead?IntermediateYou suspect a memory leak in a service. How do you collect evidence with a script before involving developers?Advanced