Reliable HTTP cron and delayed-job scheduling with automatic retries and full run logs — delay.run

A job that is supposed to run every five minutes will, eventually, take six. If the scheduler starts a second copy anyway, you get two processes writing, emailing, or charging at once. If the second copy also overruns, you get four. This is one of the more common ways a quiet cron job turns into an incident, and it often looks, in the logs, like "the job is slow" rather than "the job is stacked".

Here is how to see it, how to refuse a second run, and how to fix the work.

Prove that overlap is happening

You want a record of start and end, not only of "success". A one-line log is enough to start:

import time, logging log = logging.getLogger("job") def run(): t0 = time.monotonic() log.info("start") try: do_the_work() log.info("ok duration_ms=%d", int((time.monotonic() - t0) * 1000)) except Exception: log.exception("fail duration_ms=%d", int((time.monotonic() - t0) * 1000)) raise 

Grep a day's logs for start without a matching ok or fail before the next start. Or, cleaner, keep a row in the database:

CREATE TABLE job_runs ( job_name text NOT NULL, started_at timestamptz NOT NULL DEFAULT now(), ended_at timestamptz, status text ); 

A run is overlapping if, at insert time, another row for the same job_name has ended_at IS NULL. That query is also your lock (see below).

On systems with systemd timers or Kubernetes CronJobs, also look at the platform: CronJobs have a concurrencyPolicy (Allow, Forbid, Replace) that is often left at Allow. kubectl get jobs during a slow period will show more than one still Running.

Refuse a second run

The lock should live where the work lives, not only in the scheduler, because you may have more than one scheduler (a forgotten crontab plus the new one, or two replicas).

import os import psycopg JOB = "reindex-search" def main(): with psycopg.connect(os.environ["DATABASE_URL"]) as conn: with conn.cursor() as cur: cur.execute("SELECT pg_try_advisory_lock(hashtext(%s))", (JOB,)) got = cur.fetchone()[0] if not got: print("skipped: already running") return try: do_the_work() finally: cur.execute("SELECT pg_advisory_unlock(hashtext(%s))", (JOB,)) conn.commit() 

pg_try_advisory_lock is enough for a single database and a job that should never overlap. If the process dies, the lock is released with the connection, which is what you want. If you cannot use Postgres, a INSERT ... unique (job_name) WHERE ended_at IS NULL on job_runs, or a Redis SET lock:reindex NX EX 600, does the same job. Set a TTL so a crashed worker cannot hold the lock all day; log when you skip because the lock is held.

Skipping is the safe default. Queueing a second run to start the moment the first ends can be right for "must keep up with a backlog", and wrong for "this job is already overdue and will just overlap again". Know which you mean.

Then fix the duration

A lock without a fix means the job quietly skips all afternoon. That is better than overlap, and still an outage for whatever the job was supposed to do. Measure where the time goes, then do one or more of:

  • Process less work per run. A "every 5 minutes" job that scans the whole table should instead pick up rows with processed_at IS NULL in batches of a few hundred, and leave the rest for the next run.
  • Move heavy work off the interval. If a Monday-morning spike makes the job 20 minutes long, that spike may belong on a queue, not on the 5-minute tick.
  • Widen the interval only if the work is allowed to be later. A 5-minute job that always takes 4 minutes has no margin; 10 minutes with a 4-minute run is healthier than 5 and 4.
  • Make the work idempotent so a manual rerun, or a deliberate Replace policy, cannot double-apply side effects while you are tightening this.
-- rows this run will consider, a bite at a time SELECT id FROM events WHERE processed_at IS NULL ORDER BY id LIMIT 200 FOR UPDATE SKIP LOCKED; 

If this query returns 200 every time and the table is growing, you are falling behind and no lock will save you. That is a capacity problem: more workers (each taking a slice), or less work, or a faster path.

An overlapping run is a scheduling failure you can see only if every attempt is logged, including the ones you skipped. delay.run runs the HTTP job on the interval you set, retries a failed attempt, and keeps a log, so a run that started late or took longer than the interval is visible instead of stacking silently on the box.

Alert on both overruns and skips

Page or ticket if:

  • a run's duration exceeds some fraction of the interval (I use 80%)
  • the lock causes more than N skips in an hour
  • ended_at IS NULL for longer than the interval plus a margin

The first tells you the work is growing. The second and third tell you the work is not happening. Either one is enough to act on before you have four copies in flight.

A good weekly habit is to plot duration vs interval for every cron job. The ones hugging the line are next week's overlap.

Related reading

Have you caught a job overlapping in production? Did you notice from duplicate side effects, or from a duration graph, and what was the fix — a lock, a batch, or a slower schedule?