How to Design a Distributed Job Scheduler: Architecture, Retries & Failure Recovery

Colorful six-step visual story of a scheduled report, queue, worker crash, retry and completion
Follow Ananya’s report from schedule creation through crash recovery. Completion may occur after 9 AM when retries are needed.

System Design Daily · Intermediate to Advanced · Approx. 18-minute read

A reminder email must arrive tomorrow at 9 AM. A billing report must run every night. A video-processing task must retry after a worker crashes. These sound like simple cron jobs—until the scheduler, database, network or worker fails halfway through. This guide designs a durable distributed job scheduler from first principles, with concrete SQL, APIs, failure timelines and architectural trade-offs.

The central design rule: separate deciding when a job should run from executing what it does—and assume a job may be delivered more than once.

A real-world story: Ananya’s 9 AM sales report

Ananya, an engineer at a fictional e-commerce company, schedules a sales report for 9 AM. The schedule is saved durably. At 9 AM, a dispatcher places a run into the queue. Worker A starts generating the report but crashes. Its lease expires; Worker B retries and publishes the report. A stable run ID and an idempotent publication step protect against duplicate final reports. This is a realistic illustrative scenario, not a documented deployment at a named company.

Engineering lesson: at-least-once execution means the same run may be attempted multiple times. Do not promise exactly-once external side effects without downstream idempotency. A 9 AM trigger also does not guarantee the report finishes at 9 AM; plan capacity and deadlines accordingly.

1. Define the problem and requirements

We are building a service that accepts one-off delayed jobs and recurring schedules, persists them durably, dispatches due occurrences to a worker fleet and exposes execution history. Example workloads: email delivery, reports, data cleanup, webhooks and image processing. This design is for independent background tasks, not a full DAG workflow engine.

Functional requirementsNon-functional requirements
Create, update, pause and cancel schedulesDurable state; no silent loss of accepted jobs
Run at a specific time or on a cron schedulePredictable scheduling lag and measurable latency
Retries, backoff and dead-letter handlingSurvive a scheduler or worker crash
Inspect runs, failures and attemptsHorizontal worker scaling; tenant fairness
Support time zones and missed-run policiesSecure payloads, quotas and observability

Visual guide: traditional cron versus distributed scheduling

Colorful comparison of single-server cron and distributed scheduler with durable queue and worker recovery
Conceptual comparison: cron works well for simple host-local tasks; durable distributed scheduling adds persistence, failover and scalable workers.

Single-server cron is simple and useful, not automatically bad. It becomes fragile when one host owns all schedule state and execution. Distributed scheduling adds persistent occurrences, durable dispatch, retries and monitoring—but also introduces more operational complexity. The infographic illustrates a common architecture rather than a universal requirement to use any particular queue technology.

2. Capacity planning: explicit assumptions

Assume 1 million registered schedules, of which 200,000 fire each day. The average dispatch rate is 200,000 / 86,400 ≈ 2.3 executions/second, but a synchronized top-of-hour burst might be 2,000 executions/second. If average execution takes 5 seconds, Little’s Law suggests roughly 10,000 concurrent worker slots at that burst rate if it persists; in practice, buffer the burst and choose an acceptable queueing delay rather than provision for indefinite peak concurrency.

Assume each run record plus indexed metadata averages 1 KB: 200,000 runs/day is roughly 200 MB/day, or 73 GB/year before replication, indexes, retention and logs. These are illustrative planning assumptions, not production measurements. Measure actual payload size, burst distributions and worker duration before sizing infrastructure.

3. High-level architecture

Distributed job scheduler architecture with API, scheduler fleet, queue, workers, PostgreSQL and recovery service
Original reference architecture: the control plane persists and selects due runs; the execution plane processes them asynchronously.

API service: validates schedules, tenant permissions and idempotency keys. PostgreSQL: stores schedule definitions, run occurrences, ownership and execution history. Scheduler fleet: materializes due occurrences and dispatches them. Durable queue: absorbs spikes and redelivers unacknowledged work. Workers: perform side effects safely. Recovery service: detects expired leases, retries and terminal failures.

The queue is not the source of truth for future recurring schedules: the database is. For small systems, a PostgreSQL-backed queue can eliminate the separate broker. At higher throughput, use a durable broker such as SQS or RabbitMQ and coordinate database-to-queue delivery with an outbox.

4. API contracts

POST /v1/schedules
Idempotency-Key: customer-42-monthly-report
{
  "type": "cron",
  "expression": "0 9 * * *",
  "timezone": "Asia/Kolkata",
  "task_type": "send_report",
  "payload_ref": "s3://private-bucket/report-config/42",
  "misfire_policy": "latest",
  "max_attempts": 5
}

201 Created
{
  "schedule_id": "sch_8d21",
  "next_run_at": "2026-11-24T03:30:00Z",
  "status": "active"
}

GET /v1/schedules/sch_8d21/runs
POST /v1/schedules/sch_8d21/pause
POST /v1/runs/run_20261124/retry

Validate the cron expression, IANA time zone, allowed task type, maximum frequency and payload size. Return stable identifiers. An API idempotency key prevents duplicate schedule creation after client retries; it is distinct from a per-occurrence execution idempotency key.

5. Data model and indexes

CREATE TABLE schedules (
  id UUID PRIMARY KEY,
  tenant_id UUID NOT NULL,
  cron_expr TEXT,
  timezone TEXT NOT NULL,
  next_run_at TIMESTAMPTZ NOT NULL,
  status TEXT NOT NULL,
  misfire_policy TEXT NOT NULL,
  version BIGINT NOT NULL DEFAULT 1
);
CREATE INDEX schedules_due_idx
  ON schedules(next_run_at) WHERE status = 'active';

CREATE TABLE job_runs (
  id UUID PRIMARY KEY,
  schedule_id UUID NOT NULL REFERENCES schedules(id),
  scheduled_for TIMESTAMPTZ NOT NULL,
  status TEXT NOT NULL,
  attempt INT NOT NULL DEFAULT 0,
  lease_owner TEXT,
  lease_until TIMESTAMPTZ,
  fencing_token BIGINT NOT NULL DEFAULT 0,
  UNIQUE(schedule_id, scheduled_for)
);

The unique constraint on (schedule_id, scheduled_for) makes one logical occurrence durable even if two scheduler instances race. If schedule definitions can change, define whether the occurrence identity also includes a schedule version. Store sensitive payloads by reference, encrypted and access-controlled, instead of copying secrets into logs and queue messages.

6. How the scheduler claims due work

Each scheduler polls an indexed due-time range. Inside a short transaction, claim a bounded batch with row locking and SKIP LOCKED; materialize unique run rows; advance each schedule’s next occurrence using its configured time zone and misfire policy; then commit. Do not hold a database transaction while running user code.

BEGIN;
SELECT id, next_run_at
FROM schedules
WHERE status = 'active' AND next_run_at <= now()
ORDER BY next_run_at
FOR UPDATE SKIP LOCKED
LIMIT 100;

-- For each claimed schedule, INSERT a deterministic run occurrence.
-- ON CONFLICT(schedule_id, scheduled_for) DO NOTHING.
-- Compute and persist the next_run_at before COMMIT.
COMMIT;

This is an illustrative transaction skeleton, not a complete implementation. The full code must handle recurrence calculation, schedule updates, backfills and pagination correctly. For database-backed execution, workers may claim run rows directly. For an external broker, write an outbox event in the same transaction and have a relay publish it. Otherwise a crash after committing the run but before publishing the message can strand work.

7. Worker leases, retries and crash recovery

Worker failure recovery sequence with lease expiry, new worker, idempotency key and fencing token
Original failure-recovery timeline: the old worker can resume after its lease expires, so downstream effects need protection.

A worker claims a run atomically and receives a lease and monotonically increasing fencing token. It renews its lease while active. A recovery process finds expired leases and makes the run eligible for another attempt. Every completion update checks the current owner and token; stale workers cannot overwrite the newer execution state.

Crucial caveat: fencing a database status update does not undo an external email or payment already sent. Use a stable idempotency key at the side-effect boundary, such as schedule_id + scheduled_for + operation. When the external system supports idempotency keys, reuse the same key across retries. When it does not, maintain a transactional deduplication ledger where possible and explicitly accept or mitigate residual duplicate risk.

FailureExpected behavior
Scheduler dies before committingAnother scheduler claims the still-due schedule
Scheduler commits but queue publish failsOutbox relay publishes after recovery
Worker dies before side effectLease expires; another worker retries
Worker completes side effect, then diesRetry may occur; idempotency prevents duplicate business effect where supported
Worker A resumes after Worker B takes overFencing prevents stale state writes; downstream fencing where available
Dependency remains unavailableBackoff with jitter; eventually dead-letter for inspection

8. Retry policy and dead-letter queue

Retry only failures likely to recover: timeouts, 429 responses, and selected 5xx errors. Do not repeatedly retry invalid payloads, authorization failures or non-retryable business-rule violations. A practical delay formula is random(0, min(cap, base × 2^attempt)) (full jitter), with a bounded attempt count and a separate maximum execution age.

For example, with a 2-second base and a 60-second cap, the first few retry ceilings are 2, 4, 8, 16 and 32 seconds; the actual jittered delay is between zero and the ceiling. After exhausting the policy, move the run to a dead-letter state with error classification, last attempt, payload reference and a safe manual replay operation.

9. Time zones, DST and recurring schedules

Persist execution instants in UTC, but retain the original IANA time zone and cron expression for recurring jobs. A daily 9 AM Asia/Kolkata schedule should remain 9 AM local, not a fixed UTC offset for zones that observe daylight saving. For DST gaps and repeated local times, define explicit policies (skip, shift, run once or run twice).

After downtime, apply a documented misfire policy: skip missed occurrences, latest only, or catch up within a bounded window. Also define overlap behavior when a previous run is still active: allow concurrent, skip, queue or replace. These choices depend on the business operation.

10. Scaling and reliability trade-offs

Design choiceGood fitMain trade-off
PostgreSQL queue + SKIP LOCKEDSimple systems and moderate throughputDatabase load and hot indexes
PostgreSQL + transactional outbox + brokerHigher bursts and independent workersMore moving parts and eventual dispatch
Single scheduler leaderSmall deployments and simple orderingLeadership bottleneck and failover
Sharded scheduler fleetMany schedules and higher throughputShard ownership, rebalancing and fencing
Durable workflow engine (e.g., Temporal)Long-running workflows and complex orchestrationOperational complexity and platform coupling

Partition schedules by stable hash or tenant when a single due-time index becomes a bottleneck. Use lease-based shard ownership and fencing for leader changes. Apply per-tenant quotas and worker concurrency limits so one customer cannot starve the fleet. Add admission control for jobs whose deadlines cannot be met during overload.

11. Security and observability

  • Authorize schedule creation, cancellation and replay by tenant; enforce quotas and restrict executable task types.
  • Encrypt payload references and secrets; avoid logging credentials or personal data.
  • Measure due-to-dispatch lag, queue age, execution latency, retry rate, lease expirations, DLQ depth and missed-run count.
  • Trace a logical occurrence across API, scheduler, outbox, broker and worker with stable run IDs.
  • Alert on sustained scheduling lag, stale outbox entries, retry storms and unexpectedly silent schedules.
  • Run fault-injection tests: kill the scheduler between commit and publish, kill workers after side effects, pause the broker, and simulate clock/time-zone edge cases.

12. Interview follow-up questions

  • Why is a distributed lock insufficient to guarantee exactly-once payment processing?
  • How would you guarantee that a committed run is eventually dispatched to a broker?
  • What happens when a lease expires but the original worker is only paused, not dead?
  • How would you support millions of schedules that all fire at midnight?
  • What are the semantics of a recurring job when daylight saving time moves clocks backward?
  • When would you choose a workflow engine over a custom scheduler?

13. Quick knowledge check

Q1: Why do we need a unique run occurrence ID? Answer: To deduplicate schedule materialization during concurrent scheduling and failover.

Q2: Does a visibility timeout make a job execute exactly once? Answer: No. It enables redelivery; the handler must make side effects safe under duplicates.

Q3: Why use a transactional outbox? Answer: To close the database-commit/queue-publish failure gap.

14. Final architecture checklist

  • Durable schedule and run records with unique occurrence identities.
  • Atomic claims, bounded leases and fencing-aware state transitions.
  • Idempotent business effects or clearly documented duplicate risk.
  • Transactional dispatch or a database-backed queue.
  • Retry classification, jitter, dead letters and safe replay.
  • Explicit time-zone, DST, misfire and overlap semantics.
  • Dashboards, alerts, tenant isolation and failure-injection tests.

A production-ready scheduler is not defined by how accurately it starts a job on a good day. It is defined by what happens when every component fails at the worst possible moment.

Frequently asked questions

Does a distributed scheduler guarantee exactly-once execution?

No. Most practical queue-based systems allow at-least-once delivery; use idempotency keys and fencing to make repeated attempts safe.

What if the scheduler is offline at 9 AM?

After recovery it reads durable due schedules and applies the chosen misfire policy: skip, latest-only or bounded catch-up.

When is cron enough?

Use cron for straightforward host-local maintenance when its failure and monitoring characteristics are acceptable. Use durable distributed scheduling for important shared jobs requiring retries, auditing and worker failover.

Further reading and verified references

Related reading: How UPI Works: A Visual Guide to QR Payments, Banks & NPCI — see how another distributed transaction flow coordinates independent systems.

Scroll to Top