MonitoringPublished

Heartbeat monitoring for the cron jobs your VPN servers need

Heartbeat monitoring catches scheduled jobs that stop running or start failing: each job calls a unique URL when it finishes, and if the call doesn't arrive within the expected period plus a grace period, you get an alert. On a VPN fleet, give one to every job that fails silently: certificate renewal, geoip and geosite updates, key rotation, subscription generation and backups. Call the URL only after the job succeeds, or report its exit code, use curl with retries, and set the grace longer than the job's normal run time plus any random delay in its schedule.

Tahir Mehmood12 min read

Four cron jobs with their schedules: three checked in, the hourly backup is 90 seconds late.
On this page
  1. What is heartbeat monitoring, and how is it different from an uptime check?
  2. Which cron jobs on a VPN server need a heartbeat?
  3. How do I wire a cron job to a heartbeat URL?
  4. How do I add a heartbeat to certbot and acme.sh renewals?
  5. How do I monitor geoip and geosite updates for Xray?
  6. How do I put a heartbeat on key rotation, subscriptions and backups?
  7. How do I choose the period and grace for a heartbeat?
  8. What are the common mistakes with heartbeat checks?

The jobs in this post have one thing in common: when they stop, nothing breaks right away. A renewal job that died in March shows up as an expired certificate in May. A backup job that stopped writing files shows up on the day you need a restore. Handshake monitoring sees the result in the end, but late. A heartbeat sees the job itself.

What is heartbeat monitoring, and how is it different from an uptime check?

A heartbeat check alerts when an expected signal does not arrive. An uptime check alerts when a request to your server fails. The uptime monitor asks your server a question on a schedule. The heartbeat waits for your job to call in, and treats silence as the failure. This is the dead man's switch pattern: the job has to keep proving it is alive.

That makes heartbeats the right tool for anything that runs on a timer and has no port to probe: cron jobs, systemd timers, scripts on a panel host. It also means a heartbeat proves only what you report. It knows the job finished. It doesn't know whether the job did the right thing, so for the important jobs I pair it with a check of the result from outside.

Which cron jobs on a VPN server need a heartbeat?

Every job whose failure stays invisible for days. On the VPN servers I've seen, that is this list:

Job What happens when it silently stops Check the result with
Certificate renewal (certbot, acme.sh) Trojan, VLESS or VMess over TLS, OpenConnect and Hysteria2 fail when the certificate expires A certificate expiry check from outside
Reload after renewal The new certificate is on disk, but the service still serves the old one The same outside expiry check
geoip and geosite updates Routing rules use old lists. Nothing fails, traffic just goes the wrong way The file dates, or a routing test
Key, UUID or REALITY short ID rotation Old credentials stay valid longer than you meant, or some servers rotate and others don't Handshake checks with the new credentials
Subscription generation Users keep getting a list with dead or removed servers A content check on the subscription URL
OpenVPN CRL regeneration easy-rsa CRLs are valid for 180 days by default. When the CRL expires, OpenVPN rejects every client openssl crl -nextupdate
Backups of panel databases You find out on the day you need to restore A test restore now and then

The CRL row catches people because the job may run only twice a year in their heads. I went through what an expired CRL looks like in OpenVPN certificate has expired.

How do I wire a cron job to a heartbeat URL?

Call the heartbeat URL at the end of the job, only when the job succeeds, with a timeout and retries:

0 3 * * * /usr/local/bin/backup.sh && curl -fsS -m 10 --retry 5 -o /dev/null "$HB_BACKUP"

Each flag has a reason:

  • -f makes curl fail on an HTTP error, so a wrong URL shows up as an error instead of looking like a successful call.
  • -sS hides the progress bar but still prints errors, which cron then mails or logs.
  • -m 10 stops a hung network from holding the job open. With --retry, the 10-second limit starts again for each attempt.
  • --retry 5 retries on what the curl docs call transient errors: timeouts and HTTP 408, 429, 500, 502, 503, 504, 522 and 524. It waits one second, then doubles the wait each time. A refused connection is not retried unless you add --retry-connrefused.

&& is the important part. With ; instead, the call goes out even when the backup failed, and the heartbeat stays green while you have no backups.

You can set HB_BACKUP=https://... on its own line at the top of the crontab, which keeps long URLs out of the command lines. Two cron details to remember: a % in a crontab command means a new line, so put anything with % (such as date +%F) in a script, and cron's PATH is short, so use full paths in scripts.

A missed call only tells you about a failure after the grace period. If your heartbeat service accepts a failure signal, report the exit code instead and you hear about a failure at once. This small wrapper runs any command, prints its output, and sends the exit code and the last part of the output:

#!/bin/sh
# Usage: hb-run <heartbeat-url> <command> [args...]
# Runs the command, prints its output, and reports its exit code to the heartbeat.
url=$1
shift
out=$("$@" 2>&1)
rc=$?
printf '%s\n' "$out"
curl -fsS -m 10 --retry 5 -o /dev/null -G \
  --data-urlencode "msg=$(printf '%s' "$out" | tail -c 300)" "$url/$rc"
exit "$rc"

It calls <url>/0 on success and <url>/<code> on failure, with the output in a msg parameter, so the alert can say "error: rate limited" instead of only "failed". That URL format is what TunnelHQ heartbeats accept. Other services use their own paths for failures, so check their docs and adjust the last curl line. Some services also take a "start" call to measure how long a job runs. TunnelHQ's don't, so this post uses one call at the end of the job.

How do I add a heartbeat to certbot and acme.sh renewals?

Put the heartbeat on the renewal command's exit code, and put the service reload in a deploy hook. Per the certbot documentation, certbot renew exits with 1 only if a renewal attempt failed, and with 0 both when it renewed a certificate and when nothing needed renewing. That is the signal you want: "the job ran, and nothing failed".

For the reload, certbot runs every executable in /etc/letsencrypt/renewal-hooks/deploy/ after each successful renewal, with $RENEWED_LINEAGE set to the certificate's live directory:

#!/bin/sh
# /etc/letsencrypt/renewal-hooks/deploy/restart-vpn.sh
systemctl restart xray

Restart whatever reads the certificate: Xray, sing-box, ocserv, Hysteria, a web server in front of a fallback. A missing reload is the classic version of this failure: renewal works for a year, the heartbeat is green, and users get an expired certificate because the process loaded the old file at startup and never read the new one. Only an outside expiry check catches that, which is why the table above pairs the two (the VPN server monitoring guide shows how to run one).

Next, find out how certbot is scheduled on your server. The docs say to look for certbot renew in /etc/crontab and /etc/cron.*/*, or in systemctl list-timers. The cron line the certbot docs give runs twice a day after a random sleep of up to an hour. The docs' install command picks the number once, when it writes the line to /etc/crontab, so the line you find looks like this:

0 0,12 * * * root sleep 1734 && certbot renew -q

Add the heartbeat to that line, with the certificate check in front of it so the heartbeat fails if the certificate on disk is close to expiry anyway:

0 0,12 * * * root sleep 1734 && certbot renew -q && openssl x509 -noout -checkend 1209600 -in /etc/letsencrypt/live/vpn.yourdomain.com/fullchain.pem && curl -fsS -m 10 --retry 5 -o /dev/null https://<your heartbeat URL>

-checkend 1209600 exits non-zero if the certificate expires within 14 days. If certbot runs from a systemd timer instead, check that the service is a oneshot (systemctl cat certbot.service) and add the call with systemctl edit certbot.service:

[Service]
ExecStartPost=/usr/bin/curl -fsS -m 10 --retry 5 -o /dev/null https://<your heartbeat URL>

The systemd docs say that for a oneshot service, ExecStartPost= runs only after the last ExecStart= command exits successfully, so a failed renewal never sends the call.

With acme.sh, the reload belongs in --reloadcmd when you install the certificate (for example --reloadcmd "systemctl restart xray"), and the renewal runs from a cron entry that calls acme.sh --cron. Find that entry with crontab -l and wrap it with the hb-run script above. acme.sh --cron exits non-zero when a renewal fails, so the exit code is meaningful.

How do I monitor geoip and geosite updates for Xray?

Download the files, check them, test them against your config, and only then install them and restart Xray, with a heartbeat on the whole script. The Xray-install script has an update-geodata command that downloads geoip-full.dat and geosite-expand.dat from the XTLS/Xray-rules-dat releases, checks their SHA-256 sums and installs them in /usr/local/share/xray/. It ends with "You may need to restart Xray for the changes to take effect", because Xray reads the files when it starts.

I prefer a short script of my own for cron, so a weekly root job doesn't run code fetched from the internet. It uses the same files and checksums:

#!/bin/sh
# update-geodata.sh: download Xray geo files, test them, install them, restart Xray
set -eu
base=https://github.com/XTLS/Xray-rules-dat/releases/latest/download
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
cd "$tmp"
for f in geoip-full.dat geosite-expand.dat; do
  curl -fsSL --retry 3 -o "$f" "$base/$f"
  curl -fsSL --retry 3 -o "$f.sha256sum" "$base/$f.sha256sum"
  sha256sum -c "$f.sha256sum"
done
mv geoip-full.dat geoip.dat
mv geosite-expand.dat geosite.dat
XRAY_LOCATION_ASSET="$tmp" xray run -test -c /usr/local/etc/xray/config.json
install -m 644 -o xray -g xray geoip.dat geosite.dat /usr/local/share/xray/
systemctl restart xray

The xray run -test line is the useful trick. XRAY_LOCATION_ASSET tells Xray where to find the geo files, and -test loads the config, including every geoip: and geosite: rule, without starting the server. I checked this with Xray 26.10.31: a missing or damaged geoip.dat makes the test fail with an error that names the rule, so a bad download never replaces working files. set -e turns any failed step into a non-zero exit, so hb-run reports it. In crontab:

30 4 * * 1 /usr/local/bin/hb-run "$HB_GEODATA" /usr/local/sbin/update-geodata.sh

The full files are large (about 74 MB and 91 MB when I downloaded them on 1 November), so on a small server give the job time and the heartbeat a generous grace. sing-box needs no cron job for this: remote rule-sets update themselves on their update_interval (one day if you leave it empty), and the old GeoIP and Geosite databases were removed in sing-box 1.12.0.

How do I put a heartbeat on key rotation, subscriptions and backups?

Give each job its own heartbeat, and call it only after the step that proves the job worked. For each kind of job, that step is different.

Key rotation. A heartbeat proves the rotation ran. It can't prove clients can still connect with the new credentials. Rotate in this order: change the server, test a client with the new credentials, publish the new configs, then call the heartbeat. The client test from how to test a VPN config before you ship it fits into the script as the step before the call.

Subscription generation. Call the heartbeat after the new file is in place, then check the published URL from outside, with a keyword check or by decoding it and counting the configs. A generator that runs fine but writes an empty list is a real failure mode, and only the content check sees it.

Backups. Call the heartbeat after the copy to another machine succeeds, not after the local dump, and check that the file is not empty. For a 3x-ui panel, the database is a single SQLite file at /etc/x-ui/x-ui.db, and SQLite's .backup command copies it safely while the panel runs:

#!/bin/sh
# backup-panel.sh
set -eu
f=/var/backups/x-ui-$(date +%F).db
sqlite3 /etc/x-ui/x-ui.db ".backup '$f'"
test -s "$f"
scp -q "$f" backup@backup.yourdomain.com:x-ui/

OpenVPN CRL. Regenerate it on a schedule with easyrsa gen-crl and copy it to the path in your crl-verify line. Running it weekly is harmless, and it gives the heartbeat a period it can watch.

How do I choose the period and grace for a heartbeat?

Set the period to how often the job runs, and the grace to the longest normal run time plus any random delay in the schedule, plus a margin. The heartbeat goes down when no call arrives within the period plus the grace. A grace that is too short gives you false alarms on slow nights. A grace that is too long tells you late.

Job Schedule Period Grace
certbot renew, with the docs' cron line Twice a day, random sleep up to 1 hour 12 hours 2 hours
geodata update Weekly 7 days 6 hours
Subscription generation Every 10 minutes 10 minutes 10 minutes
Panel backup Daily at 03:00 1 day 2 hours
OpenVPN CRL Weekly 7 days 1 day

If a systemd timer runs the job, read RandomizedDelaySec= in the timer (systemctl cat certbot.timer) and add it to the grace. If your heartbeat service caps the period, run monthly jobs weekly instead. For most of these jobs, a run with nothing to do is harmless.

Use one heartbeat per job per server. A shared heartbeat for "certbot on all servers" stays green as long as any one server calls in, which hides exactly the server that stopped. Name each one so the alert says what stopped, such as "certbot renew, vpn-de-1".

What are the common mistakes with heartbeat checks?

Most broken heartbeats call in at the wrong moment or for the wrong exit status. The ones I check for first:

  • Calling at the start of the job. That proves the job started, not that it worked.
  • A pipe before &&. In backup.sh | tee backup.log && curl ..., the exit status is the status of tee, so the call goes out even when the backup fails. Use set -o pipefail in bash, or write the log inside the script.
  • No retries. One network blip at 03:00 becomes a false alarm, and after a few of those people stop reading the alerts.
  • An egress firewall. A server that blocks outbound traffic except for the VPN can block the heartbeat call too. Test the call by hand once from each server.
  • Local time and daylight saving. A daily job at a fixed local hour can move by an hour twice a year. Run servers on UTC, or keep the grace above one hour.
  • Treating the URL as public. Anyone who has the URL can report the job as up or down. Keep it in a root-only file, not in a public repo.

Full disclosure: heartbeats are part of TunnelHQ Uptime, and every plan includes its own Uptime checks, Free too. You set how often a call is expected (from minutes up to 365 days, 1 day by default) and a grace period (0 to 365 days, 1 hour by default). The job calls <your dashboard address>/api/push/<token> with any HTTP method, adds /fail or /<exit code> to report a failure at once, and can attach a msg. When no call arrives within the period plus the grace, the heartbeat goes down and alerts through the same channels as your tunnels, with no extra confirmation, because the grace is the confirmation.