CronNudge

Published October 21, 2026

How to Monitor Database Backup Cron Jobs

A nightly dump can look fine for weeks. Cron fired, the shell exited 0, and a file is sitting in /var/backups. The file is a truncated gzip, a header with no rows, or last month's dump that nothing replaced. You find out when you need the restore.

This page is those silent failures, then a bash script that tells CronNudge the run started, sends the dump size on the success ping, and calls /fail when the dump command exits non-zero. The size is a metric the check can reject. CronNudge does not open the file.

The shell and database behavior below is from the Bash Reference Manual, the PostgreSQL 18 pg_dump and backup documentation, the MySQL 8.0 mysqldump reference, and restic's backup exit statuses, as of October 2026. The ping URLs are CronNudge's. A job that never starts at all is how to monitor cron jobs. A crontab that does not fire is crontab not running.

What still exits 0

What you see What actually happened
pg_dump | gzip exits 0 Without pipefail, the status is gzip's. pg_dump can have died mid-stream.
A file exists A > redirect is created by the shell before pg_dump runs, so a failed dump can leave an empty or partial file. --file and mysqldump --result-file create the target themselves. Publish the name only after the command returns 0.
The file is tiny --schema-only, the wrong database, or a dump of an empty database. Those can exit 0. A rejected password exits non-zero, and it stays quiet only when nothing records that status.
Disk full The process that sees the write error exits non-zero. In a pipeline, that process might not be the one whose status you checked.
Two dumps at once pg_dump does not take an exclusive lock. Both can write the same path, or fill the disk together.
The archive lists pg_restore --list reads the table of contents. It does not insert the rows.

PostgreSQL's pg_dump page says the tool makes a consistent export while other sessions read and write, and that it does not block those sessions. The same page says that, except in simple cases, pg_dump is generally not the right choice for regular backups of production databases, and it points at the backup chapter. Continuous archiving is the other path in that chapter. The wrapper below is still the thing that notices a cron dump that did not produce a file you can trust. The same start, size, and fail pings wrap mysqldump and a restic-style snapshot.

The pipeline status is the last command

The Bash Reference Manual defines a pipeline's exit status as the status of the last command, unless pipefail is enabled. With pipefail, the status is the rightmost command that exited non-zero, or zero when every command exited zero. set -e does not save you on its own: a failing command that is not the last stage of a pipeline does not exit the shell when pipefail is off.

PostgreSQL's backup chapter shows this compressed dump:

pg_dump dbname | gzip > filename.gz

That line is a pipeline. gzip can finish the short stream it was given and exit 0 after pg_dump has already failed. The shell then reports success. PIPESTATUS is a bash array of each stage's status. dash does not have pipefail or PIPESTATUS. On Debian and Ubuntu, /bin/sh is dash, and cron runs the crontab line with /bin/sh unless the crontab sets SHELL. Put the dump in a file whose shebang is bash. Do not depend on an inline pipeline in the crontab.

# Status is gzip's. A failed pg_dump can still look successful.
pg_dump "$DATABASE_URL" | gzip > /var/backups/db.sql.gz

# bash: the pipeline fails if either command exits non-zero.
set -o pipefail
pg_dump "$DATABASE_URL" | gzip > /var/backups/db.sql.gz

The script further down does not use that pipeline. Custom format is already compressed. pg_dump --format=custom writes the archive itself, and the default compression for that format is gzip. Piping it through gzip again is a second compression, and it reintroduces the pipeline.

Ping start, then the size, then fail

The check's ping URL is https://cronnudge.com/ping/<check-id>. GET, POST, and HEAD all count. The response is text/plain ok with Cache-Control: no-store. Store that URL in CRONNUDGE_URL with no query string and no /start suffix. /start and /fail are the same id with that path. A non-zero ?exit= on the success URL is stored as a failure. curl -fsS does not print the URL. -o /dev/null drops the body. A curl failure is swallowed on purpose: a monitoring blip must not fail a dump that succeeded, and a missed ping alerts after grace.

flock -n takes the lock or exits without waiting. The lock is on the open file descriptor, so it drops when the script exits, including a crash. A leftover lock file is not a leftover lock. Take it before /start. A second copy that cannot get the lock exits without pinging. Calling /fail from that second copy would close the run the first copy still has open.

#!/usr/bin/env bash
set -euo pipefail

url="${CRONNUDGE_URL:?CRONNUDGE_URL is not set}"

ping() {
  curl -fsS -m 10 --retry 3 -o /dev/null "$1" || true
}

exec 9>/tmp/db-backup.lock
if ! flock -n 9; then
  echo "another backup still holds /tmp/db-backup.lock" >&2
  exit 1
fi

on_err() {
  local status=$?
  trap - ERR
  ping "${url}/fail?exit=${status}"
  exit "$status"
}
trap on_err ERR

ping "${url}/start"

tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT

# libpq reads ~/.pgpass or a peer socket. Do not put the password on the command line.
pg_dump --format=custom --file="$tmp" --dbname="${DATABASE_URL:?DATABASE_URL is not set}"
pg_restore --list "$tmp" >/dev/null

bytes=$(wc -c < "$tmp" | tr -d '[:space:]')
mkdir -p /var/backups
final="/var/backups/db-$(date -u +%F).dump"
install -m 600 "$tmp" "${final}.partial"
mv -f "${final}.partial" "$final"

# Whole number. The metric column is a signed 32-bit integer.
ping "${url}?bytes=${bytes}"

pg_restore --list is the documented way to print an archive's table of contents. A non-zero exit means that listing did not succeed, the trap calls /fail, and mv never runs, so yesterday's file stays in place. The listing does not prove the rows will load. That is a later section.

The crontab points at the script. A % in a crontab line starts a newline, which is why date +%F lives in the file and not in the schedule. The other reasons a line never starts are in crontab not running.

SHELL=/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
CRONNUDGE_URL=https://cronnudge.com/ping/YOUR_ID

0 3 * * * /usr/local/bin/db-backup.sh

YOUR_ID is the check's ping id. It is a secret. The badge key is a different id.

If the dump can be larger than 2,147,483,647 bytes, do not send bytes. That value does not fit the integer column, the insert fails, and the success ping is not recorded. Send whole mebibytes and set the metric name to mib instead:

ping "${url}?mib=$(( bytes / 1048576 ))"

Use one of those two lines, and use the same name on the check. A dump under 1 MiB becomes 0 in the mebibyte form, which is the wrong unit for a small database.

What the size assertion actually checks

On the check, open "Assertions, runs, and agent limits."

  • Metric name is the key you send. bytes or mib. The match is exact, so the spelling has to be the same. A name is a letter, then up to 40 letters, digits, or underscores.
  • Minimum is assertionMin. The metric fails when it is lower than that integer. Equal to the minimum passes.
  • Maximum is assertionMax, for a sudden jump if you want one.
  • "Metric must be greater than 0" is assertionPositive. It catches a zero. It does not catch a 200-byte header.
  • Median deviation % is assertionDeviationPct. After at least three earlier successes have a metric, a new value fails when it is more than that percent away from the median of the last 20 values.

Set the metric name. A success ping with no metric fails a configured rule and alerts once. A later success that still fails the rule does not alert again while the check is already down. The next success that passes is the recovery.

Query string and JSON both work. ?bytes=123 and a JSON body {"bytes":123} are the same kind of metric. count, rows, and bytes in the docs are example names, not special fields. These names are not metrics: exit, status, duration, duration_ms, steps, tokens, cost, cost_usd, summary, error, body, metrics.

The value stored on the ping is a PostgreSQL integer, and Minimum is an integer too. The largest value that fits is 2,147,483,647. Send a whole number in one unit and keep the check on that unit.

Free includes assertions and run tracking on 3 checks. Pro removes that cap. Token and dollar limits are a different feature, on Pro, and this backup check does not use them. Check limits stay 10 on Free and 100 on Pro. The numbers are on pricing. The field list is assertions, runs, and agents.

A floor belongs under a normal dump and over a schema-only file. Copy it from a dump you have already restored, not from zero.

Overlap, flock, and max runtime

/start records a start. It is not a success. Turn on "Track start and finish," or set Max runtime (seconds), which turns run tracking on.

With run tracking and no max runtime, an open run is due after the grace period, and that wait is at least 60 seconds. On a nightly schedule the next cron slot is tomorrow, so the open-run deadline is the one that fires. With the default 5-minute grace, a dump that takes 20 minutes is marked down while it is still writing. Set Max runtime to longer than a healthy dump and shorter than the time you are willing to wait. The deadline becomes the start time plus that many seconds. The alert is stuck: the check is still running, and it passed its max runtime without a finish ping. Allowed values are 1 second through 7 days.

A second /start while a run is open alerts overlap and does not erase the first run. The max-runtime clock is then measured from the latest /start. A /fail or a success ping closes the open runs. That is why the script takes flock before /start, and why the copy that loses the lock does not call /fail.

flock is local to one machine. Two hosts dumping the same database both pass their own lock and both call /start. The host, Kubernetes, and retry cases are in prevent overlapping cron jobs. The second start is the overlap alert. On one machine, a kill that skips the trap leaves the run open. Max runtime marks it stuck. The next night's /start can also overlap, because the run stays open until a success or /fail. The success ping is the recovery.

Duration deviation % is separate. After at least three finished runs, it alerts when the new duration is more than that percent away from the median of earlier ones. It does not replace max runtime.

mysqldump

The same wrapper works. Swap the dump command, keep the temp file, and only then mv.

mysqldump --single-transaction --quick --result-file="$tmp" --databases "$MYSQL_DATABASE"
bytes=$(wc -c < "$tmp" | tr -d '[:space:]')

--single-transaction sets the isolation mode to REPEATABLE READ and sends START TRANSACTION before dumping data. The MySQL manual says this is useful for transactional tables such as InnoDB: a consistent snapshot from that moment, without locking those tables for the whole dump. Only InnoDB tables are consistent under that option. MyISAM and MEMORY tables can still change. While the dump runs, other sessions should not ALTER, CREATE, DROP, RENAME, or TRUNCATE the tables being dumped. The manual says a consistent read is not isolated from those statements.

--result-file writes the file in mysqldump, so you are not in a gzip pipeline. The manual also says the result file is created and its previous contents overwritten even if an error occurs while generating the dump. Point it at the temp path. mv onto the published name only after the command returns 0.

Without --force, an SQL error makes mysqldump exit with an error message. With --force, it continues, and it can write a dump that skipped a broken view. Leave --force off when a skipped table should fail the job. The official examples that pipe mysqldump into a redirect have the same last-command status as pg_dump | gzip. pipefail, or no pipe, is the fix.

The exit status is mysqldump's once it is not in a pipeline. The manual does not publish a table of numeric codes for mysqldump. Non-zero is the failure the trap already pings.

restic

restic's backup command documents its own statuses. 0 means the snapshot has the source files. 1 means a fatal error and no snapshot. 3 means some source data could not be read and an incomplete snapshot was still created. 10 means the repository does not exist, since restic 0.17.0. 11 means the repository is already locked, since 0.17.0. 12 means the password is incorrect, since 0.17.1. Treat every non-zero status as a failed backup, except 11, which means another restic still holds the repository.

Keep the lock, the /start, and on_err from the script above. Replace everything after the /start line with this, including the size ping. A restic snapshot is not a file you measured. The ERR trap has to be off while restic runs: bash runs that trap on a non-zero status even after set +e, and the trap would call /fail for the lock as well as for a real failure.

trap - ERR
set +e
restic backup /srv/data
status=$?
set -e
trap on_err ERR
if [ "$status" -eq 11 ]; then
  echo "repository already locked" >&2
  exit "$status"
fi
if [ "$status" -ne 0 ]; then
  ping "${url}/fail?exit=${status}"
  exit "$status"
fi
ping "$url"

Exit 3 has to fail the check. An incomplete snapshot is the silent success people keep. Exit 11 must not call /fail: the first run is the one holding the lock, and /fail would close it. The /start this copy already sent is the overlap alert, and the max-runtime deadline moves to that start. Before 0.17.0 a lock failure is exit 1, the same code as other fatal errors, so this branch cannot see it. The scripting docs say an unknown exit code has to be treated as a command failure.

restic's lock is inside the repository. flock on the host is a different lock. On one machine the flock stops a second cron before /start. Exit 11 is what you get when the repo lock is held by something that flock did not cover, such as a second host.

A table of contents is not a restore

pg_restore -l answers "can this archive's table of contents be read?" It does not answer "will this load?" Schedule a second job that restores into an empty database and pings only if that restore exits 0.

PostgreSQL's notes say to create that empty database from template0 when template1 has local additions, or the restore trips over duplicate objects. For a plain SQL dump, the backup chapter says psql continues after an SQL error unless you set ON_ERROR_STOP. A truncated script can look successful without it.

psql -v ON_ERROR_STOP=1 -d restore_scratch -f /var/backups/db.sql

Custom format uses pg_restore -d restore_scratch --exit-on-error. That is the rehearsal. Run it weekly or on the 1st, on its own check, so a dump that lists and still will not load fails a ping of its own. First of the month is a usual slot. CronNudge still only sees the ping.

Schedule, grace, and the check

0 3 * * * is 03:00 in the check timezone. The page for that expression is daily at 3:00. In the US and in Europe the missing and repeated hours are earlier than 03:00. The per-scheduler rule is in cron jobs and daylight saving time. Put the zone the crontab uses on the check. UTC when the crontab sets CRON_TZ=UTC.

Default grace is 5 minutes. The form offers none, 1 minute, 5 minutes, 15 minutes, and 1 hour. The API accepts any whole number of seconds from 0 through 7 days. Grace is how late the schedule may be. It is the wrong knob for a 40-minute dump if you also ping /start, unless max runtime is set, because the open run is due after grace. Either ping only at the end and set grace longer than the dump, or ping /start and set max runtime. The script above is the second one. A short dump can use the 1 hour grace and skip /start. A dump that sometimes runs past an hour needs max runtime or an API grace longer than the run.

Free is 10 checks, email, and one Slack or Discord channel. The shortest Free interval is 5 minutes. Pro is $12 a month for 100 checks, a 1-minute minimum, signed webhooks, and the API. There is no yearly price.

One check per backup. A shared URL stays up while any other job still pings. Compare the five fields on the cron tool in the zone you set. The next run should be 03:00 in that zone, not 03:00 in a zone the machine does not use.

FAQ

Why does pg_dump | gzip exit 0 when pg_dump failed? Bash reports the last command in the pipeline unless pipefail is on. gzip can exit 0 after compressing the short stream a failed pg_dump already produced. set -e does not catch that earlier stage when pipefail is off. dash, which Debian and Ubuntu use as /bin/sh, has no pipefail. The script needs a bash shebang.

Does a successful exit code mean the dump is restorable? No. Exit 0 means the commands you checked returned 0. The file can still be the wrong database, schema-only, or much smaller than a normal dump. pg_restore --list reads the table of contents. It does not load the rows.

How does a too-small dump raise an alert? Send the size on the success ping, such as ?bytes=123, and set the check's metric name to bytes and Minimum to a whole number under a healthy dump and over a header. A missing metric fails the rule too. The stored metric is a 32-bit integer, so a byte count above 2147483647 has to be sent as mebibytes with the metric name mib.

What do max runtime and overlap mean here? Max runtime is seconds on the check. After /start, if success or /fail does not arrive in time, the check is marked stuck and alerts once. A second /start while a run is open alerts overlap and does not erase the first run. The stuck timer follows the latest /start. /fail closes the open run, so a second copy that lost the lock should exit without calling it.

Does pg_dump lock writers out? No. The documentation says pg_dump makes a consistent export without blocking other readers or writers. Two overlapping dumps can still write one path or fill the disk. The lock is flock in the script.

Does CronNudge open the backup file? No. It stores the ping, an optional exit code, and the numeric metric you send. It does not fetch the dump or run pg_restore. The minimum is the size check. A restore into a scratch database is still a separate job.


The file on disk is not the signal. The ping after a dump that passed the listing, with a size the check accepts, is the signal. Create the check for 0 3 * * *, or read how to monitor cron jobs if the schedule itself never fires. Related: cron expression examples and assertions, runs, and agents.