Sub topic 14
Heartbeat monitoring: alerting when a job does not run
This chapter assumes you can write a cron entry or a systemd service and timer pair. It also assumes you know how exit codes and set -e work in shell, and that you can read output from journalctl. Earlier chapters covered making jobs fail loudly with exit status. This chapter covers the case where nothing fails loudly because nothing runs.
Why failure alerts are not enough
Most alerting reacts to something that happens: an error is logged, a process exits non-zero, a mail is sent. A job that never starts produces none of these events. Common causes:
- The crontab was overwritten or the user's entry was lost during a rebuild.
- The timer was never enabled, or
daemon-reloadwas skipped after an edit. - The cron daemon or the machine is down.
- The job hangs before it prints anything.
MAILTOpoints at a mailbox nobody reads, or the server has no working mail transport.
In all of these, the absence of a message looks the same as success. A heartbeat check reverses the logic. The job reports in after each successful run. An external service expects that report and raises an alert when it does not arrive on time. This pattern is also called a dead man's switch.
How a heartbeat check works
A heartbeat service such as Healthchecks.io, Cronitor, or a self-hosted equivalent gives each job a unique URL. Your job sends an HTTP request to that URL. The service keeps two numbers for each check:
- Period: how often a ping is expected, for example every 24 hours.
- Grace time: how long to wait after the expected time before alerting.
Alerts are sent when the period plus the grace time has elapsed with no ping. The monitor sits outside your server, so it still alerts when the whole machine is down.
Ping only after success
The most important rule is to ping only when the whole job has worked. A ping at the top of the script proves only that the script started. The backup script from the earlier chapter follows this rule:
#!/usr/bin/env bash
set -euo pipefail
out=/var/backups/db.sql.gz
tmp=$(mktemp "${out}.XXXXXX")
trap 'rm -f "$tmp"' EXIT
pg_dump mydb | gzip > "$tmp"
mv "$tmp" "$out"
# Report success only after everything above worked
curl -fsS -m 10 --retry 3 -o /dev/null https://hc.example.com/ping/your-check-idset -e stops the script on the first error, so the curl line is never reached after a failure. The -fsS flags make curl fail on HTTP errors and stay quiet except for error messages. -m 10 caps the request at ten seconds, and --retry 3 tolerates a brief network problem.
Two details are easy to get wrong:
- If the final ping itself fails,
set -emakes the script exit non-zero even though the backup worked. Decide whether that is acceptable. If it is not, append|| trueto thecurlline. The monitor will still alert you, because the ping did not arrive. - Without
pipefail,pg_dump mydb | gzipwould report gzip's exit status and hide a failed dump. The script above sets it.
Signalling start and failure explicitly
Most services also accept /start and /fail suffixes on the check URL. A /start ping lets the service measure run time and detect jobs that start but never finish. A /fail ping alerts immediately instead of waiting for the grace time to pass.
Rather than adding this to every script, write one wrapper:
#!/usr/bin/env bash
# /usr/local/bin/hc-run: run a command and report to a heartbeat check.
# Usage: HC_URL=https://hc.example.com/ping/your-check-id hc-run COMMAND [ARGS...]
set -uo pipefail
: "${HC_URL:?HC_URL must be set}"
notify() {
curl -fsS -m 10 --retry 3 -o /dev/null "$1" || true
}
notify "$HC_URL/start"
if "$@"; then
notify "$HC_URL"
else
status=$?
notify "$HC_URL/fail"
exit "$status"
fiThe wrapper keeps the original exit status, so cron mail and systemd failure handling still work. It deliberately avoids set -e so it can send the /fail ping. The || true inside notify means a monitoring outage never turns a good job into a failed one.
Wiring it into cron
Cron lets you define variables at the top of the crontab. Put the check URL there and call the wrapper:
# root's crontab
[email protected]
PATH=/usr/local/bin:/usr/bin:/bin
HC_URL=https://hc.example.com/ping/your-check-id
30 2 * * * /usr/local/bin/hc-run /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1Cron does not expand variables inside other variable assignments, so write the full URL as a plain value. Anyone who can read the crontab can read the URL, and anyone with the URL can send fake pings. Treat it as a low-grade secret and keep crontab permissions tight.
Wiring it into a systemd service
For a systemd job you can ping from the unit itself, so the script stays unchanged. For Type=oneshot services, ExecStartPost= runs only after ExecStart= has finished successfully:
# /etc/systemd/system/backup.service
[Unit]
Description=Nightly backup
OnFailure=backup-failed.service
[Service]
Type=oneshot
User=backup
ExecStart=/usr/local/bin/backup.sh
ExecStartPost=-/usr/bin/curl -fsS -m 10 --retry 3 -o /dev/null https://hc.example.com/ping/your-check-id
TimeoutStartSec=1hThe leading - tells systemd to ignore a failure of that command. Without it, a monitoring outage would mark your backup service as failed. The OnFailure= line is optional. It names a second unit that systemd starts when this one fails, and that unit can send the /fail ping or any other alert. The timer from the earlier chapter does not change.
After editing, reload and verify:
sudo systemctl daemon-reload
sudo systemctl start backup.service
systemctl status backup.service
journalctl -u backup.service --since todayThen open the monitoring dashboard and confirm that the check turned green.
Choosing period and grace time
Set the period to match the schedule and the grace time to cover normal variation.
| Job schedule | Period | Grace time | Reason |
|---|---|---|---|
| Every 15 minutes | 15 minutes | 5 to 10 minutes | A slow run or a short delay should not page anyone. |
| Nightly at 02:30 | 1 day | 1 to 2 hours | The timer has `RandomizedDelaySec=5min`, and the job may take up to its timeout. |
| Weekly | 7 days | 6 to 12 hours | Allows for a `Persistent=true` catch-up after downtime. |
If your service supports cron-expression schedules, give it the same expression and time zone as the job. Otherwise a daylight saving change can make the monitor expect a ping an hour earlier or later than the job sends it. A fixed-interval check avoids this problem but is less precise.
Common errors
- One shared check for several jobs. One job's ping hides another's silence. Create one check per job.
- Pinging before the work. The check stays green while the job fails midway.
- Hiding failures with
;or|| trueon the real work.backup.sh; curl ...pings even when the backup fails. Use&&,set -e, or the wrapper. - Alerts going to the same place as the problem. If the alert is an email from the same server, a server outage also silences the alert. Send alerts through the monitoring service's own channels, such as chat or SMS.
- No monitoring of a flaky ping path. If the server cannot reach the monitor because of a firewall or a proxy, every job looks dead. Test the
curlcommand as the job's user, with the job's environment. - Grace time too tight. Constant false alarms train people to ignore the channel.
Exercise
A nightly job's crontab line is 30 2 * * * /usr/local/bin/backup.sh; curl -fsS https://hc.example.com/ping/abc. The backup has been failing for a week, yet the monitoring dashboard shows the check as healthy. Why, and what are two ways to fix it?
Show answer
The semicolon runs curl after backup.sh regardless of its exit status, so the ping is sent even when the backup fails. Fix it by replacing ; with && so the ping is sent only on success. Alternatively, run the job through a wrapper such as hc-run that sends /fail on a non-zero exit, or add the ping as the last line of a script that uses set -euo pipefail.
Exercise
A weekly job runs from a timer with Persistent=true. The server is powered off for a weekend, and the job runs late on Monday morning after boot. Which check setting decides whether this late run raises an alert?
Show answer
The grace time. If the late ping arrives within the period plus the grace time, the check stays up or recovers without alerting. If it arrives later, the check goes Down and sends an alert, followed by a recovery notice when the ping arrives. For a job that is expected to catch up after downtime, set the grace time long enough to cover the usual outage length.