research/heartbeat-checks-for-scheduled-jobs

Heartbeat Checks for Scheduled Jobs: Alerting When a Job Did Not Run

Engineering Note · November 18, 2026 · 10 minute read · Monitoring · Node.js · Scheduled Jobs · Reliability

A heartbeat check alerts when a scheduled job has not reported success recently enough, instead of waiting for the job to report a failure. The job writes the time of each success; a separate watcher compares that time with now and alerts when the gap is longer than the schedule plus a grace period. We tested it with a stand-in nightly job in Node.js. The watcher alerted on a job that failed, one that hung, one killed partway through and one that never started. Only the first of those could have reported its own failure. Along the way, a single shared heartbeat file lost updates when two jobs wrote at once, and the fix was one file per job.

Everything below was run with Node.js 22.23.5 and GNU bash 5.2.21 on Linux, using only Node’s standard library. The outputs are the real ones from these runs. This note goes with today’s article, Knowing Your Website Is Broken Before a Customer Tells You.

Why is a failure alert not enough?

A failure alert depends on the job getting far enough to send it. These cases never get there:

  • The job hangs. It waits forever on a network call or a lock, never exits and never reports.
  • The job is killed. The operating system or a supervisor sends SIGKILL, which a program cannot catch.
  • The job never starts. The schedule was disabled, the server was off, a deploy removed the cron entry, or the scheduler itself is down.

From the outside, all three look like a quiet, successful night.

What does the heartbeat code look like?

The first version kept every job’s last success in one JSON file. That version had a concurrency bug, covered below. This is the fixed version, with one small file per job:

// heartbeat.mjs: a job records success; a separate watcher checks the age.
import fs from 'node:fs';
import path from 'node:path';
const DIR = process.env.HEARTBEAT_DIR ?? './heartbeats';
const now = () => Number(process.env.NOW_MS ?? Date.now());

export function beat(job) {
  fs.mkdirSync(DIR, { recursive: true });
  const file = path.join(DIR, job);
  const tmp = `${file}.${process.pid}.tmp`; // one temp name per process
  fs.writeFileSync(tmp, String(now()));      // epoch ms: no time zone, no daylight saving
  fs.renameSync(tmp, file);                  // readers see the old value or the new one
}

export function status(job, everyMinutes, graceMinutes) {
  let last;
  try { last = Number(fs.readFileSync(path.join(DIR, job), 'utf8')); } catch {}
  if (!last) return { ok: false, why: 'has never reported' };
  const ageMin = Math.round((now() - last) / 60000);
  const limit = everyMinutes + graceMinutes;
  return ageMin <= limit
    ? { ok: true, why: `last success ${ageMin} min ago` }
    : { ok: false, why: `last success ${ageMin} min ago, limit ${limit}` };
}

Three choices matter:

  • Epoch milliseconds, not a local time string. The age is a subtraction, with no time zone or daylight saving rules involved. Our daylight saving note shows what local times can do to a schedule.
  • Write to a temporary file, then rename. On a local Linux file system a rename replaces the target in one step, so the watcher should never read a half-written file. We did not test concurrent reads; see Limitations.
  • A missing file is an alert. It catches a job that was set up but never ran.

NOW_MS lets the test move the clock forward; in production it is unset.

The job calls beat() only after its work succeeds. Here is a stand-in nightly export with a mode for each failure:

// job.mjs <mode>: a stand-in for a nightly export. Beats only after the work succeeds.
import { beat } from './heartbeat.mjs';
const mode = process.argv[2];
if (mode === 'fail') { console.error('export failed: upstream returned 503'); process.exit(1); }
if (mode === 'hang') { await new Promise(() => setInterval(() => {}, 1e9)); }
if (mode === 'crash-before-beat') { process.kill(process.pid, 'SIGKILL'); }
beat('nightly-export');
console.log('export ok');

The watcher runs on its own schedule. For a nightly job we allow 24 hours plus 60 minutes:

// watch.mjs: run on a different schedule (and ideally a different machine) from the job.
import { status } from './heartbeat.mjs';
const s = status('nightly-export', 24 * 60, 60);
console.log(`${s.ok ? 'OK   ' : 'ALERT'} nightly-export ${s.why}`);
process.exit(s.ok ? 0 : 1);

What happened in each case?

The test script, run.sh, runs the job in each mode and then the watcher, with the clock moved forward from the first success:

rm -rf heartbeats
echo "== before the first run"; node watch.mjs; echo "exit $?"
echo "== job succeeds"; node job.mjs ok; echo "exit $?"; node watch.mjs; echo "exit $?"
T=$(cat heartbeats/nightly-export)
at() { NOW_MS=$((T + $1)) "${@:2}"; }
H=3600000; M=60000
echo "== 24 h later: job fails"; at $((24*H)) node job.mjs fail; echo "exit $?"; at $((24*H)) node watch.mjs; echo "exit $?"
echo "== 25 h later: watcher"; at $((25*H)) node watch.mjs; echo "exit $?"
echo "== 25 h 1 min later: watcher"; at $((25*H+M)) node watch.mjs; echo "exit $?"
echo "== job hangs, killed after 5 s"; at $((48*H)) timeout 5 node job.mjs hang; echo "exit $?"; at $((48*H)) node watch.mjs; echo "exit $?"
echo "== job killed before it can beat"; at $((72*H)) node job.mjs crash-before-beat; echo "exit $?"; at $((72*H)) node watch.mjs; echo "exit $?"
echo "== job never started (cron disabled): only the watcher runs"; at $((96*H)) node watch.mjs; echo "exit $?"
$ bash run.sh
== before the first run
ALERT nightly-export has never reported
exit 1
== job succeeds
export ok
exit 0
OK    nightly-export last success 0 min ago
exit 0
== 24 h later: job fails
export failed: upstream returned 503
exit 1
OK    nightly-export last success 1440 min ago
exit 0
== 25 h later: watcher
OK    nightly-export last success 1500 min ago
exit 0
== 25 h 1 min later: watcher
ALERT nightly-export last success 1501 min ago, limit 1500
exit 1
== job hangs, killed after 5 s
exit 124
ALERT nightly-export last success 2880 min ago, limit 1500
exit 1
== job killed before it can beat
run.sh: line 5:  2826 Killed                  NOW_MS=$((T + $1)) "${@:2}"
exit 137
ALERT nightly-export last success 4320 min ago, limit 1500
exit 1
== job never started (cron disabled): only the watcher runs
ALERT nightly-export last success 5760 min ago, limit 1500
exit 1

Read the failed run carefully. At 24 hours the job failed with exit 1, and the watcher still said OK, because the previous success was exactly one interval old. The alert came at 25 hours and 1 minute, when the grace ran out. That delay is the cost of a heartbeat: it tells you a job is late, not the moment it fails. If an hour matters, keep the job’s own failure alert as well and use the heartbeat as the net underneath it.

FailureCould the job report it?Heartbeat alert
Job exits with an errorYes, before exitingYes, after the grace period
Job hangs (stopped by timeout here)NoYes
Job killed with SIGKILLNoYes
Job never startsNoYes
Heartbeat never written at allNoYes (“has never reported”)

In the hang case, timeout returned 124 and in the kill case the shell reported 137 (128 + signal 9). A wrapper could alert on those, but nothing can alert from inside a job that never started.

What went wrong with one shared file?

The first version stored every job in one heartbeats.json: read the file, set this job’s time, write heartbeats.json.tmp, rename it over the original. That works for one job. We then ran two jobs, backup and invoices, each recording 300 successes as fast as it could, at the same moment:

// race.mjs <module> <job>: record 300 successes in a row under one job name.
const { beat } = await import(process.argv[2]);
let errors = 0;
for (let i = 0; i < 300; i++) { try { beat(process.argv[3]); } catch { errors++; } }
if (errors) console.log(`${process.argv[3]}: ${errors} of 300 beats threw`);
$ node race.mjs ./heartbeat-shared.mjs backup & node race.mjs ./heartbeat-shared.mjs invoices & wait
invoices: 59 of 300 beats threw
backup: 107 of 300 beats threw

The error, caught separately:

ENOENT: no such file or directory, rename './heartbeats.json.tmp' -> './heartbeats.json'

Both processes used the same temporary name. One renamed the temporary file into place, and the other’s rename then found nothing to move. The second problem is quieter. Each writer reads the whole file, changes one key and writes the whole file back, so a slow writer can overwrite another job’s newer entry with the old value it read. We ran 20 rounds of the race against each version and counted rounds that ended with a job missing from the record:

# race.sh <module>: two jobs record success at the same moment, 20 rounds.
mod=$1; missing=0
for round in $(seq 1 20); do
  rm -rf heartbeats heartbeats.json*
  node race.mjs $mod backup > out.$round.a & node race.mjs $mod invoices > out.$round.b & wait
  if [ -f heartbeats.json ]; then n=$(node -p "Object.keys(require('./heartbeats.json')).length")
  else n=$(ls heartbeats | grep -vc tmp); fi
  [ "$n" = 2 ] || missing=$((missing+1))
done
echo "$mod: rounds with a job missing: $missing of 20; rounds with errors: $(cat out.* | grep -c . | tr -d ' ')"
rm -f out.*

The error figure counts one line per process that hit errors: 40 means both processes in all 20 rounds.

$ bash race.sh ./heartbeat-shared.mjs; bash race.sh ./heartbeat.mjs
./heartbeat-shared.mjs: rounds with a job missing: 5 of 20; rounds with errors: 40
./heartbeat.mjs: rounds with a job missing: 0 of 20; rounds with errors: 0

With the shared file, a job was missing from the record in 5 of 20 rounds, and both processes hit errors in every round. A missing entry makes the watcher alert about a job that ran fine. With one file per job and a temporary name that includes the process ID, there was nothing to lose and nothing to collide.

Where should the watcher run?

Somewhere the job’s failure cannot reach. If the job and the watcher share a server, turning that server off silences both. Good options:

  • A different machine or a scheduled CI run that reads the heartbeat from shared storage.
  • A monitoring service, if yours offers heartbeat checks: the job makes one HTTP request on success and the service raises the alert. The logic is the same as above.

Run the watcher more often than the grace period: every 15 minutes against 60 minutes of grace.

Limitations

  • The clock was moved with NOW_MS rather than waiting real days. The age calculation is a subtraction, so this tests the same code, but it does not test a real scheduler.
  • Everything ran on one Linux machine with a local file system. Rename in one step is a property of a single file system; network file systems and object storage behave differently and were not tested.
  • A heartbeat says the job finished, not that its output is correct. An export that writes an empty file still records success. Check the output where it matters, for example by having the job beat only when the row count is above zero.
  • The race test is a tight-loop stress test. It shows the bug exists, not how often real jobs would hit it.
  • The watcher itself needs watching. If it stops, no alerts arrive. A monthly test, deliberately letting a harmless job go stale, covers that.

Frequently asked questions

What is a heartbeat check for a cron job?

A heartbeat check watches for a success report that should have arrived and did not. The job records a timestamp each time it finishes its work, and a separate watcher compares that timestamp with the current time. If the gap is longer than the job's interval plus a grace period, the watcher raises an alert.

Why not just alert when a scheduled job fails?

Because many failures never reach the alerting code. A job that hangs, is killed by the operating system, or never starts because its schedule was disabled sends nothing at all. In our test, only one of four failure types produced an error the job could report, while the heartbeat watcher alerted on all four.

How long should the grace period be for a heartbeat check?

Long enough to cover normal variation in start time and run time, and short enough that someone can still act before the delay hurts. For a nightly job we used 24 hours plus 60 minutes. A job that sometimes runs for 40 minutes needs more grace than one that always finishes in 2.

Should the heartbeat watcher run on the same server as the job?

Preferably not. If the server is off, both the job and the watcher stop, and nobody is told. Run the watcher on a different machine or a hosted scheduler, so the failure of one does not silence the other.

Why did two jobs writing one heartbeat file lose updates?

Each job read the whole file, changed its own entry, and wrote the file back, so a slower writer could overwrite a faster one's change. Both jobs also used the same temporary file name, so one renamed the other's file away and the second rename failed with ENOENT. One file per job, with a temporary name that includes the process ID, removed both problems in our test.

More from Research

← All research