Skip to content
For alerts on automated tasks, watch for silent failures first

For alerts on automated tasks, watch for silent failures first

At two in the morning I opened my phone and saw an alert for a backup job: it had been failing for 11 days straight.

It wasn’t that the alerting had failed—there had never been any alerting. I’d put that job on crontab six months earlier. The day it broke I was in a meeting, and nobody mentioned it afterward. Digging through the logs, I found out: the disk was full, the backup script couldn’t find the source files, and it just exited 1. It died quietly for eleven days and I never noticed once.

After that I spent a weekend going through all ten-odd automation jobs I had: scheduled backups, scraping into the database, periodic summaries. None were complicated, but not one of them could reliably wake me up while I was asleep. What follows is written in the order I actually hit these problems, not as a best-practices checklist.

Guard against “didn’t run” first, then “ran and failed”

Most people’s first instinct when adding alerting is: send a message when the script errors out. That approach doesn’t cover the most dangerous class of failure—the job never getting started at all.

A cron entry gets deleted by accident, a service doesn’t come back up after a reboot, an upstream API change leaves the process stuck waiting, a container gets OOM-killed—in all these cases not a single line of error handling in the script runs, because it never got to that line. What these failures share is that they’re quiet: no logs, no exit code, nothing that notifies you.

Some will say cron has MAILTO built in, and systemd timers have OnFailure—that’s good enough. It works, but with a precondition: the machine is still alive, mail can get out, and you still check that mailbox. My criterion is that the alerting channel must not share a failure domain with the system being monitored. The machine dying or the disk filling up is exactly when you most need an alert—and that’s usually when the local-email path goes down with it.

My solution is reverse confirmation: after each job finishes, it actively reports outward “I’m alive”; if the external service doesn’t receive a report within the expected window, it’s judged a failure. This is what’s commonly called a heartbeat, or a dead man’s switch. I use healthchecks.io; the free tier is enough for my ten-odd jobs (I don’t remember the exact quota); self-hosting isn’t hard either—a job_state table plus a cron that scans once a minute is enough.

Before that, my crontab had a dozen different styles, logs were scattered across several directories, some with dates and some without, and the first thing to do when something broke was figure out where the logs were. Later I consolidated all jobs into a single wrapper script, and crontab only calls it:

BASH15 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/usr/bin/env bash
set -uo pipefail

JOB="$1"; shift
START=$(date +%s)
LOG="/var/log/jobs/$JOB.log"

if "$@" >>"$LOG" 2>&1; then
curl -fsS -m 10 --retry 3 'https://hc-ping.com/<uuid>' >/dev/null || true
echo "ok $JOB $(($(date +%s) - START))s"
else
code=$?
curl -fsS -m 10 --data-binary @"$LOG" 'https://hc-ping.com/<uuid>/fail' >/dev/null || true
exit "$code"
fi

Two things I only learned by stepping on them. The reporting curl must use || true: a network blip makes the report fail, which turns an otherwise successful job into a non-zero return and manufactures a false alert out of thin air. The other thing is that the timeout window should be set to about 1.5× the job’s usual runtime, not some arbitrary 24 hours. The backup job normally runs 8 minutes, so I set the window to 15; the scraping job fluctuates a lot, usually 3 to 10 minutes, so I set 30. Set it too loose and it’s as good as no alerting; set it too tight and you get false alarms every day—and then you stop looking.

This wrapper only suits stateless batch jobs that run and exit. If you need retries inside the script or to fan out to multiple workers concurrently, the wrapper layer can’t manage that fine-grained; that’s better handed to scheduling frameworks like Airflow or Dagster. My scale doesn’t warrant it—an extra scheduling layer just adds another maintenance cost.

Also, the heartbeat service itself is a single point: if it goes down, I get neither alerts nor recoveries. The common fallback is to keep another line locally: if there’s been no report for some number of consecutive hours, mention it in the morning digest. Even a human glance is better than silence.

Split into three tiers by “who should respond within how long”

At first I sent all alerts into the same IM group, and two weeks later I’d learned to ignore that group. All alerts at one level is the same as no levels.

Now I use three tiers, with a single criterion: can this wait until tomorrow morning?

P0 goes by SMS plus phone call—it has to be able to drag me out of bed. Currently only one qualifies: the reconciliation job. Its failure means the books don’t match actual receipts, and a night’s delay doubles the cost of handling it. I once wanted to promote backups to P0 too, but then thought it through: a night of backup failure doesn’t cause immediate harm, so it’s P1.

P1 goes by IM with an @ to me, to be looked at within two hours during working time. Things like scraping into the database and data sync.

P2 goes into the daily morning digest, looked at together at nine. Clearing temp files, rebuilding indexes, generating weekly reports—half a day late has no impact.

The easy mistake when setting tiers is to sort by “job importance” rather than “cost of delay.” Importance is a feeling; cost of delay can be calculated: if not handled for a night, how much manual work piles up, will it cause irreversible data damage. My default now is that new jobs start at P2, and only get promoted after they’ve actually caused a problem once. Giving everything the top tier from the start just means everyone starts ignoring the top tier.

After tiering you also need suppression: for the same job and same class of failure, send only once per 30 minutes—otherwise one infinite loop can blow up your phone. I implemented it with the dumbest thing, a file lock, keyed on job name plus exit code, with the lock’s lifetime being the suppression window. The boundary of suppression needs to be clear: what’s suppressed is only the notification, not the failure itself—the count is still recorded, otherwise the next day you’d have no idea how many times it fired overnight.

If a job succeeds on retry after an alert, I send a recovery notice. Only when recovery notices exist will the next alert be taken seriously.

There’s another kind of merging that’s easy to overlook: three jobs fail at once, and all the logs point to the same database connection timeout—that’s really one failure. I do a very crude merge at the alerting layer: alerts with the same error summary within the same minute get combined into one, titled “3 jobs failed for the same reason.” That’s far more useful than three separate alerts—at least it doesn’t make me think three problems have appeared.

It ran, but the result was wrong

A heartbeat only proves the process is alive; it can’t prove it did the job right. The worst one I hit: the scraping job ran, exit code 0, logs perfectly clean, but 0 rows went into the database. The other side had changed their page structure, the parser returned an empty list, and the script considered “didn’t scrape anything new” a normal case.

So for every job with output, I add a result assertion. The assertion goes at the end of the job; if it fails, exit 1, reusing the same alerting channel:

BASH6 lines
1
2
3
4
5
6
rows=$(psql -tAc "select count(*) from articles where fetched_at > now() - interval '1 hour'")
ok=20
if [ "$rows" -lt "$ok" ]; then
echo "fetched $rows rows, expected >= $ok"
exit 1
fi

How to set the threshold is a trade-off. A fixed value is simple, but the business volume itself changes—false alarms every day in peak season, missed alarms in off season. What I do now is take the median of the same period over the past seven days, and alert if it’s below half of that. I’m still watching this rule; it may need tuning.

The value of an assertion depends on its false-positive rate. An assertion that false-alarms every day will, within two weeks, definitely get added to a whitelist—and then nobody looks at it again. So I’d rather set the threshold loose first, run two weeks to see the distribution, then tighten it bit by bit.

Another kind of assertion is easier to write: a lower bound on the size of the output file, the sign of the final amount in a summary job, the ratio of rows in an export job to rows in the source table. If the last one deviates too far from 1, it’s basically a missing filter condition.

Not every job has a countable quantity to assert on. For notification-type jobs, I have them write “how many were sent” into the log and the report payload, then only assert on 0—sending none almost always means the query condition was written wrong. For jobs with truly no output volume, you can at least assert on runtime: a job that normally finishes in 3 minutes running for 40 basically means it’s stuck somewhere, even if it eventually returns 0.

Alerts for this kind of “abnormal result” should be labeled separately from “process failure,” because the troubleshooting paths are completely different: the former is usually not a code problem—the outside world has changed.

Alert text is written for your 3 a.m. self

The alert content I see most often is script failed. Seeing those five words at 3 a.m. is the same as seeing nothing.

When writing an alert, I first imagine a scenario: seeing this message half-asleep, can I tell within thirty seconds whether “I need to get up right now”? If I can’t, the alert needs to be changed.

Now every alert of mine gives five things: task name, last success time, exit code, last line of the error, log link, plus one sentence of “what you can do first.” That last sentence matters most; it doesn’t describe the whole troubleshooting process, only the first step, such as “look at the last twenty lines of the log first to confirm whether it’s safe to rerun,” or “check whether the upstream has changed its format; clear the dirty data before rerunning.”

“Last success time” is something I added later; it explains severity better than the error message. With the same exit code 1, whether the last success was ten minutes ago or eleven days ago makes a huge difference in priority.

If the alert goes to colleagues and not just yourself, that “what to do first” sentence should be more conservative. Writing “confirm the scope of impact first, don’t rush to rerun” is more appropriate than writing a specific command—you don’t necessarily know what permissions the other person has, or whether they’re standing or lying down right now.

Finally, clearing noise. Every so often I go through the alert records, with a crude standard: has this rule actually made me take action in the past period? If not, either widen the threshold or downgrade it straight into the morning digest. I’ve cut a few rules before: some fired frequently whenever disk usage was high, but I never dealt with them; some fired on occasional errors from an external API, and a retry fixed it. After cutting them, the alert volume went from quite a lot to very little, and now when I see an alert I actually open it.

Next week I plan to replace the fixed threshold on the scraping task with a rolling median. I’ll first pull the past thirty days of ingestion volume and run the numbers to see how many false alarms the new rule would produce. If it’s more than two, I won’t switch.

About this Post

This post is written by Lu's Blog, licensed under CC BY-NC 4.0.

#Alerting #Automation #Scheduled Tasks

Comments