Interview Prep/Shell Scripting/Scenarios: health checks, monitoring and alerts

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
  1. -X ignores ~/.psqlrc, -tA gives a bare value.
  2. On a quiet primary, replay timestamps stop advancing even with zero lag; compare pg_last_wal_receive_lsn() and pg_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.

All Shell Scripting questions Roadmap: Shell scripting (Bash)

More on Scenarios: health checks, monitoring and alerts