Reliable HTTP cron and delayed-job scheduling with automatic retries and full run logs — delay.run
"The workers are running" is not the same as "the work is on time". A queue can be accepting jobs, a process can be up, and the oldest unprocessed job can be 45 minutes past its run_at. If you only alert on process liveness or on a 5xx from the web app, you will learn about that 45 minutes from a customer.
Depth (how many jobs are waiting) and age (how late the oldest due job already is) are the two numbers that catch this. They are cheap to read if you measure them the same way the worker does, and expensive if you SELECT FOR UPDATE the live queue to do it.
What to measure
Two figures, per queue, on a short interval (30–60 seconds is plenty):
- Depth: how many jobs are ready to run right now (due, not reserved, not done, not in a dead-letter).
-
Age: now minus the time the oldest of those jobs became runnable (
run_atorenqueued_at, depending on the system). Age of zero with depth of zero is healthy. Age of 20 minutes with depth of 4 is a stuck or under-provisioned worker. Depth of 80,000 with age of 30 seconds is a burst that may still be fine.
Alert on age first, then on depth. A deep queue that is draining on time is a scaling question. A shallow queue that is not draining is an incident.
Do not include jobs scheduled for the future in "depth", and do not let them set "age". A reminder queued for next Tuesday is not late. A third number — "scheduled ahead" — is useful, but it is not the page.
Postgres: a query that does not fight the workers
Assume a table workers already use, with a partial index on the due work (the same index you want for FOR UPDATE SKIP LOCKED):
CREATE INDEX IF NOT EXISTS jobs_due_idx
ON jobs (run_at)
WHERE status = 'queued';
The monitor query only reads:
SELECT
count(*) AS depth,
EXTRACT(EPOCH FROM (now() - min(run_at))) AS oldest_age_seconds
FROM jobs
WHERE status = 'queued'
AND run_at <= now();
That should be an index-only scan, or close to one. Do not wrap it in FOR UPDATE. Do not open a transaction and hold it. Do not compute this with SELECT * FROM jobs and a script. If now() and run_at do not share a time zone (a timestamp without time zone stored in "whatever the app had"), age will be wrong; use timestamptz.
A stale auto-vacuum or a table that has never been indexed will make this query a sequential scan the first time the table is large. Run EXPLAIN once on production-sized data. If you partition by date, make sure the query can prune.
import os
import psycopg
SQL = """
SELECT count(*) AS depth,
COALESCE(EXTRACT(EPOCH FROM (now() - min(run_at))), 0) AS age
FROM jobs
WHERE status = 'queued' AND run_at <= now()
"""
with psycopg.connect(os.environ["DATABASE_URL"]) as conn:
conn.execute("SET statement_timeout = '2s'")
depth, age = conn.execute(SQL).fetchone()
print(f"depth={depth} oldest_age_seconds={int(age)}")
A statement timeout keeps a bloated table from turning the monitor into a problem. If this query starts hitting the timeout, that is itself a signal.
Sidekiq: depth is LLEN, latency is the tail
Sidekiq LPUSHes jobs and BRPOPs them, so the next job to run is at index -1, not 0. Depth is the list length. Latency is now minus the enqueued_at of that tail job (Sidekiq's own Queue#latency).
# depth of the default queue
redis-cli LLEN queue:default
# the next job that will be popped (JSON), then read enqueued_at from it
redis-cli LINDEX queue:default -1
Or, from Ruby, Sidekiq::Queue.new("default").size and .latency. Also look at retry and dead (sorted sets): ZCARD retry and ZCARD dead. Those are not "depth of due work", but a retry set that is growing while latency stays small means the work is failing, not that the worker is slow.
Watch the queue name you actually use. A worker that only listens to critical will let default grow in silence if you only measure critical.
BullMQ: lists, delayed zsets, and the score
BullMQ keeps waiting jobs in a list (bull:<name>:wait, sometimes plus paused and prioritized) and delayed jobs in a sorted set (bull:<name>:delayed) whose score is a timestamp in milliseconds. Depth of due work is the wait list, plus any delayed job whose score is already in the past (it should have been promoted and has not been yet).
redis-cli LLEN bull:email:wait
redis-cli ZCARD bull:email:delayed
# earliest delayed score (ms since epoch)
redis-cli ZRANGE bull:email:delayed 0 0 WITHSCORES
import os, time, redis
r = redis.from_url(os.environ["REDIS_URL"])
name = "email"
depth = r.llen(f"bull:{name}:wait") + r.llen(f"bull:{name}:paused")
# delayed jobs whose score is already due
due_delayed = r.zcount(f"bull:{name}:delayed", 0, int(time.time() * 1000))
depth += due_delayed
oldest = r.lindex(f"bull:{name}:wait", -1)
print(f"depth={depth} wait_tail={oldest is not None}")
Prefix and queue name vary (bull: is the default; a cluster may add more). Read one job from your own Redis and copy the keys it actually uses rather than guessing from a blog post (this one included).
A worker process that is up can still be an hour behind if nobody is measuring the oldest due job. delay.run keeps a run log for each scheduled HTTP job, so a run that did not start on time is visible as a missed or late execution, not only as a process that still answers ping.
How to alert without paging on every burst
Start with: age over 5 minutes for a "must be on time" queue (password resets, payment captures), age over 30–60 minutes for batch work, and a depth threshold you have actually seen during a normal peak, not a guess. If a deploy briefly pauses workers, age will climb; either extend the threshold for that window, or drain before you pause so the page does not become background noise.
Export the two numbers as metrics (job_queue_depth, job_queue_oldest_age_seconds) labelled by queue. A dashboard is nice. A page on age is the part that earns its keep.
If you cannot add a metric today, a cron that runs the query and exits non-zero when age is over the threshold is already better than a liveness probe on the worker.
Related reading
- How to detect when a scheduled job starts taking longer than its own interval (overlapping runs) and stop it safely
- Case study (hypothetical): a unique constraint on the job queue stalled every nightly email for three days, and only the web app was monitored
- 6 myths about calling rate-limited APIs from background jobs
- When the scheduler comes back after an outage, should it run every missed tick, or skip to the next one? Let's argue about it
What do you alert on today — worker process up, queue depth, or the age of the oldest job? Which one has actually caught an incident for you?
Top comments (0)