In short
A distributed job scheduler stores each schedule with its next run time, has one or more schedulers turn due schedules into run records keyed by job and scheduled time, and lets workers claim those runs from a queue under a lease. The unique run key stops a slot from being enqueued twice, the lease and a fencing token stop two workers from finishing the same run, and idempotent jobs absorb the retries that at-least-once delivery still allows. Around that core sit a policy for runs missed during downtime, schedule math done in the job's own time zone, retries with a dead-letter state, and alerts on anything overdue.
Key points
- Give every run a key made of the job ID and the scheduled time, enforced by a unique index. Duplicate enqueues then become no-ops.
- Workers claim runs under a lease that expires, and every claim bumps a fencing token, so a worker that stalled cannot finish a run someone else took over.
- Delivery is at least once. Make each job idempotent rather than trying to reach exactly once.
- Decide per job what happens to runs missed during downtime: catch up, run once, or skip after a deadline.
- Compute wall-clock schedules in the job's IANA time zone and store run times in UTC. Decide what a run in a skipped or repeated hour means.
- Alert on lateness and on silence: runs that are overdue, schedulers that stopped advancing, and jobs with no recent success.
Requirements
A single server running cron is fine until the server reboots during the nightly job, someone adds a second server and every job runs twice, or a customer in Sydney asks why their report arrived at 3 a.m. A distributed scheduler is the same idea, made to survive many machines and failures. Start with what it has to do:
- Run jobs on recurring schedules (cron expressions or fixed intervals) and once at a specific time ("send this reminder at 9:00 tomorrow, the user's time").
- Deliver each scheduled run at least once. Jobs are written to be idempotent, so a repeat is harmless.
- Never start two copies of the same scheduled run at once, even with several schedulers and workers running.
- Retry failed runs with backoff, up to a limit, then park them where a person will see them.
- Apply a stated policy to runs missed while the system was down: catch up, run once, or skip.
- Interpret schedules in a time zone, including the days when clocks change for daylight saving time.
- Show what is going on: next run, last run, history, failures, and anything overdue. Let an operator pause a job or trigger it by hand.
Non-functional needs shape the rest: a lot of schedules, bursts at the top of every hour when many of them are due together, and start-time precision measured in seconds, not milliseconds. If you need sub-second timers, you need an in-memory timer service, covered below; most business schedulers do not.
Cron expression basics
The POSIX specification for crontab defines five time fields, separated by spaces, followed by the command. Each field is an asterisk for every value, a number, a range written as two numbers with a hyphen, or a comma-separated list of those.
| Field | Allowed values (POSIX) | Example | Meaning |
|---|---|---|---|
| Minute | 0 to 59 | 30 | At minute 30 |
| Hour | 0 to 23 | 4 | At 4 a.m. |
| Day of month | 1 to 31 | 1,15 | On the 1st and the 15th |
| Month | 1 to 12 | * | Every month |
| Day of week | 0 to 6, 0 is Sunday | 1 | And on Mondays |
Read together, 30 4 1,15 * 1 runs at 04:30 on the 1st, the 15th and every Monday. That "and every Monday" surprises people: the specification says that when both day-of-month and day-of-week are restricted, a day matching either one counts. The cronie manual gives the same kind of example.
Most implementations add to POSIX. Cronie accepts step values such as */2 (every second hour, in the hour field), and three-letter month and day names. Other libraries add a seconds field, a year field, or shortcuts such as @daily, so check which dialect yours parses and validate expressions when they are saved, not when they first fire. One practical habit: do not put every job at minute 0. Spread start times, or add a little random jitter, so a thousand schedules do not land on the queue in the same second.
Architecture: schedule store, schedulers, queue and workers
- Schedule store: one row per job with its cron expression or run-at time, IANA time zone, missed-run policy, retry limits, enabled flag and the precomputed
next_run_at, kept in UTC and indexed. - Schedulers: find schedules whose
next_run_athas passed, write a run record for that slot, and advancenext_run_atto the following slot, in one transaction. - Queue: the run records themselves, or a message broker fed from them. Either way, the run record is the source of truth for status.
- Workers: claim a run, execute the job, and mark it done or failed. They know nothing about schedules.
- History and control: run records double as history; an API or admin screen reads them and toggles
enabled.
Splitting "decide what is due" from "do the work" is the important choice. The scheduler stays small and fast because it only writes rows; slow jobs never delay the next tick. Workers scale on their own, and the queue between them is an ordinary job queue with all the usual rules about acknowledgments, visibility timeouts and idempotent handlers; see idempotency and job queues.
There are three common ways to run more than one scheduler without double work:
- A single leader. Schedulers compete for a lease in a coordination service or a database lock, and only the holder ticks. Simple, but a failover leaves a gap while the old lease expires, and a leader that paused may still tick, so the run key below must still hold.
- Partitions. Hash each job ID to one of N partitions and give each scheduler a set of partitions to own. This spreads load across schedulers, at the cost of rebalancing when one joins or leaves.
- Shared rows with row locks. Every scheduler runs the same query with
FOR UPDATE SKIP LOCKED, so each due row is taken by one of them. PostgreSQL's documentation describesSKIP LOCKEDas a way to avoid lock contention with multiple consumers of a queue-like table.
If the leader lock is a PostgreSQL session advisory lock, check your connection pooler: PgBouncer's transaction mode gives up session features, including session advisory locks and LISTEN. Postgres connection pooling explains why, and how many connections a fleet of polling workers really needs.
Preventing duplicate runs: run keys, leases and fencing
Duplicates come from two places: the same slot enqueued twice (two schedulers, a retry after a timeout, a leader that did not know it had lost its lease), and the same run executed twice (a worker that stalled past its lease while another took over). Each needs its own guard.
For enqueueing, give every run a natural key: the job ID plus the scheduled time of the slot it belongs to, in UTC. A unique index on that pair turns a duplicate insert into a no-op, whoever sends it. In PostgreSQL, `INSERT ... ON CONFLICT DO NOTHING skips conflicting rows, and RETURNING` reports only rows actually inserted, so the scheduler learns which slots were new.
CREATE TABLE schedules (
job_id text PRIMARY KEY,
cron text,
tz text DEFAULT 'Etc/UTC', -- an IANA zone name, never an offset
next_run_at timestamptz, -- computed in app code, stored in UTC
enabled boolean DEFAULT true
);
CREATE TABLE job_runs (
job_id text REFERENCES schedules,
scheduled_for timestamptz, -- the slot this run belongs to
status text DEFAULT 'queued',
attempts int DEFAULT 0, fence bigint DEFAULT 0, -- fence: +1 per claim
lease_until timestamptz DEFAULT '-infinity',
PRIMARY KEY (job_id, scheduled_for) -- the unique run key
);
-- One scheduler tick, in one transaction. Two schedulers racing is harmless.
WITH due AS (
SELECT job_id, next_run_at FROM schedules
WHERE enabled AND next_run_at <= now()
FOR UPDATE SKIP LOCKED
)
INSERT INTO job_runs (job_id, scheduled_for)
SELECT job_id, next_run_at FROM due
ON CONFLICT (job_id, scheduled_for) DO NOTHING
RETURNING job_id, scheduled_for;After the insert, still in the same transaction, the scheduler sets next_run_at for every due row from its cron expression and time zone, then commits. Tested against a local PostgreSQL 14: the first tick for a due schedule inserted one row, and a second identical tick returned zero rows. The primary key also means neither column can ever be left empty, so every run has a slot.
For execution, workers claim runs under a lease, and each claim increments a fencing token. A worker that stalls past its lease loses the run to the next claimer, and its late "done" no longer matches the current token:
-- A worker claims the oldest runnable slot under a lease
UPDATE job_runs r
SET status = 'running', attempts = r.attempts + 1, fence = r.fence + 1,
lease_until = now() + interval '300 seconds'
FROM (
SELECT job_id, scheduled_for FROM job_runs
WHERE status = 'queued' OR (status = 'running' AND lease_until < now())
ORDER BY scheduled_for
LIMIT 1
FOR UPDATE SKIP LOCKED
) c
WHERE r.job_id = c.job_id AND r.scheduled_for = c.scheduled_for
RETURNING r.job_id, r.scheduled_for, r.fence;
-- Finishing only counts if nobody re-claimed the run meanwhile
UPDATE job_runs SET status = 'done'
WHERE job_id = 'nightly-report' AND scheduled_for = '2026-11-12 07:00+00'
AND fence = 1 AND status = 'running';In the same local test, the claim returned fence 1, the finish with fence 1 updated one row, and a finish carrying the stale fence 0 updated none. The fence protects the run record. To protect what the job writes elsewhere, pass the fence along and have that system reject writes with an older one, or make the job's effects idempotent; distributed locks explains why a lease alone cannot stop a paused holder. For jobs that must never overlap across slots, such as a sync that takes longer than its interval, add a check that skips or delays a new run while an earlier run of the same job is still running.
Finding due jobs: polling vs timing wheels
The simplest scheduler polls: every second or so, query the schedules whose next_run_at has passed, using an index on that column. It is stateless, survives restarts for free, and its cost depends on how many rows are due, not on how many exist. Its precision is the polling interval, and each tick is a database round trip whether or not anything is due.
At larger volume, or when you need finer precision, keep the near future in memory. In their 1987 SOSP paper, Varghese and Lauck note that conventional timer algorithms take time proportional to the number of outstanding timers to start or maintain one. Their timing wheel is a circular array of slots, one per tick, each holding a list of timers due in that tick; a pointer advances one slot per tick and fires what it finds. Within the wheel's range, starting, stopping and maintaining a timer all take constant time.
For intervals longer than the wheel, the paper describes two extensions: hash the expiry time into a slot and keep the remaining rounds with the timer, or use a hierarchy of wheels at different granularities. Its example uses four arrays, for days, hours, minutes and seconds; a timer sits in the coarsest wheel that fits and moves to finer wheels as its time approaches, much like a clock's hands.
| Approach | How it finds due work | Strengths | Weaknesses |
|---|---|---|---|
| Poll the store | Indexed query on the next run time, every tick | Stateless, restart-safe, simple | Precision limited to the tick; a query per tick |
| Priority queue in memory | Heap ordered by next run time | Exact ordering; cheap to peek at the earliest | Insert and remove grow with the number of timers; lost on restart |
| Hashed or hierarchical timing wheel | Advance one slot per tick and fire its list | Constant-time start, stop and tick | Memory per slot; lost on restart; needs a loader |
A common hybrid keeps the database as the source of truth and loads the next window of due runs into a wheel, re-reading on a timer and after a restart. The wheel decides when to fire; the run key still decides whether a run exists.
Missed runs after downtime: catch up or skip
When the scheduler comes back after an outage, some next_run_at values are in the past, sometimes by many slots. Whether to run them all is a product decision per job, not a global setting:
| Policy | Behavior | Fits |
|---|---|---|
| Catch up | Enqueue every missed slot, oldest first | Jobs whose slots each mean something: hourly billing aggregates, per-period exports |
| Run once | Enqueue only the latest missed slot and move on | Jobs that sync current state: cache refreshes, report rebuilds |
| Skip after a deadline | Run a missed slot only if it is less than N seconds late | Time-sensitive jobs: reminders, "good morning" messages |
Kubernetes CronJob is a well-documented reference. startingDeadlineSeconds sets how late a Job may still be created; the documentation's example of 200 allows a Job to start up to 200 seconds after its scheduled time, and a run that misses the deadline is skipped and counted as failed. When there are more than 100 missed schedules, the controller records a TooManyMissedTimes warning and starts a Job only for the most recent one. concurrencyPolicy covers overlap: Allow (the default) lets runs overlap, Forbid skips a new run while the previous one is still going, and Replace stops the running one and starts the new one.
The same page is candid about its limits: a CronJob creates a Job approximately once per execution time, and in some circumstances two Jobs might be created, or none, so the documentation tells you to make Jobs idempotent. That is the honest contract for any scheduler, and the reason the run key and idempotent jobs both exist. In the design above, the policy lives in the code that advances next_run_at: catch-up moves it one slot past the slot just enqueued, run-once moves it past now, and skip drops slots older than the deadline and records them as missed.
Time zones and daylight saving time
A schedule like "every day at 09:00" means 09:00 for someone, somewhere. Store the IANA zone name with the schedule, such as America/New_York, never a fixed UTC offset, compute the next local time in that zone, and convert it to UTC for next_run_at. Fixed intervals such as "every 6 hours" are different: compute them in UTC, so a clock change does not stretch or shrink them.
Twice a year, wall-clock schedules hit an edge. When clocks spring forward, a local time such as 02:30 does not exist that day; when they fall back, 01:30 happens twice. The cronie manual is explicit about its behavior: times that do not exist never match, so jobs scheduled in the missing hour do not run, and times that occur twice cause matching jobs to run twice. A distributed scheduler should pick a policy on purpose. Python's zoneinfo (Python 3.9 and later) supports the fold attribute from PEP 495, which tells you about both cases:
from datetime import date, datetime, time, timedelta, timezone
from zoneinfo import ZoneInfo
def daily_runs(at, tz, start, days):
# "Every day at `at`, local time in tz", yielded as UTC instants
for i in range(days):
wall = datetime.combine(start + timedelta(days=i), at)
first = wall.replace(tzinfo=tz, fold=0).astimezone(timezone.utc)
second = wall.replace(tzinfo=tz, fold=1).astimezone(timezone.utc)
note = ''
if first.astimezone(tz).replace(tzinfo=None) != wall:
note = 'gap: shifted forward' # fold=0 moves it by the gap's length
elif first != second:
note = 'overlap: first only' # skip the repeat at `second`
yield first, note
ny = ZoneInfo('America/New_York')
for start, at in [(date(2026, 3, 7), time(2, 30)), (date(2026, 10, 31), time(1, 30))]:
for utc, note in daily_runs(at, ny, start, 3):
print(utc.strftime('%m-%d %H:%M UTC'), utc.astimezone(ny).strftime('%H:%M %Z'), note)
# 03-07 07:30 UTC 02:30 EST
# 03-08 07:30 UTC 03:30 EDT gap: shifted forward
# 03-09 06:30 UTC 02:30 EDT
# 10-31 05:30 UTC 01:30 EDT
# 11-01 05:30 UTC 01:30 EDT overlap: first only
# 11-02 06:30 UTC 01:30 ESTThe output above is from running the code. On 8 March 2026, the day daylight saving time starts in New York, the 02:30 run moves to 03:30 EDT instead of disappearing; on 1 November, when 01:30 happens twice, it runs once, at the first 01:30. The UTC times change across each switch while the local time stays put, which is the point. Other reasonable policies are to run at the first valid minute after a gap, or to skip it as cronie does; what matters is that you choose one and that the run key is computed from the resulting UTC instant. Notification system design applies the same zone rules to quiet hours.
Kubernetes CronJob has the same split: without .spec.timeZone, the controller reads schedules in its own local time zone, and with it, in the named zone. Time zone rules change, too: governments move or abolish daylight saving time. Keep the time zone database on your servers updated, and recompute stored next_run_at values for affected zones after an update.
Retries, timeouts and dead letters
- Retry the run, not the schedule. A failed run keeps its run key and goes back to queued with a later visible-at time; the next scheduled slot is a different run and is not affected.
- Back off exponentially with jitter, and cap attempts per job. A job that calls a rate-limited API needs a longer back-off than one that only touches your database.
- A timeout is a lease. Set it from the job's normal duration with headroom, let long jobs extend their lease while they make progress, and treat an expired lease as a failed attempt.
- After the last attempt, move the run to a dead-letter state with its error and attempt count, and alert. Do not delete it, and do not let it block the next slot.
- Decide whether a newer slot makes an old failed one pointless. For "rebuild the report", the next successful run supersedes the failure; for "charge this period", it does not.
Pausing a job is a flag check before enqueueing and again before executing, so a paused job already in the queue does not run. Treat it like a kill switch in a feature flag system: fast to flip, audited, and safe when the flag store is unreachable.
Monitoring overdue jobs
A scheduler fails quietly: a job that stopped running produces no errors. Watch for lateness and silence, not only for failures.
- Scheduling lag: how long after
scheduled_forthe run was enqueued. A rising lag means the scheduler is slow or stopped. - Start lag: how long a queued run waited for a worker. A rising lag means too few workers or a stuck queue.
- Overdue runs: queued or running rows whose slot is older than a per-job threshold, and schedules whose
next_run_atis in the past by more than one tick. - Time since last success, per job. This is the dead man's switch that catches a job deleted by mistake or disabled and forgotten.
- Failure and dead-letter counts, and run duration against the job's own history, which catches a job that suddenly takes far longer.
Run records make most of this a query, and an admin screen with next run, last run, status and a "run now" button removes many support questions. Alert from a process separate from the scheduler, so a dead scheduler cannot also silence its own alarm.
If you want a scheduler like this built into your product, see our web app development service: the code lives in your GitHub from day one, the IP is assigned to you, and AI-assisted work is reviewed by an engineer.
Sources
Checked when this post was written.
- The Open Group Base Specifications Issue 7 (POSIX.1-2017): crontab
- crontab(5), cronie project manual page (man7.org)
- Varghese and Lauck, Hashed and Hierarchical Timing Wheels: Data Structures for the Efficient Implementation of a Timer Facility (SOSP 1987, ACM)
- Kubernetes documentation: CronJob
- Python documentation: zoneinfo, IANA time zone support
- PEP 495: Local Time Disambiguation
- PostgreSQL documentation: INSERT (ON CONFLICT)
- PostgreSQL documentation: SELECT (the locking clause and SKIP LOCKED)