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

Tags:

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.

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 requirementsCreate, update, pause and cancel schedulesDurable state; no silent loss of accepted jobsRun at a specific time or on a cron schedulePredictable scheduling lag and measurable latencyRetries, backoff and dead-letter handlingSurvive a scheduler or worker crashInspect runs, failures and attemptsHorizontal worker scaling; tenant fairnessSupport time zones and missed-run policiesSecure payloads, quotas and observability

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

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

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 behaviorScheduler dies before committingAnother scheduler claims the still-due scheduleScheduler commits but queue publish failsOutbox relay publishes after recoveryWorker dies before side effectLease expires; another worker retriesWorker completes side effect, then diesRetry may occur; idempotency prevents duplicate business effect where supportedWorker A resumes after Worker B takes overFencing prevents stale state writes; downstream fencing where availableDependency 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-offPostgreSQL queue + SKIP LOCKEDSimple systems and moderate throughputDatabase load and hot indexesPostgreSQL + transactional outbox + brokerHigher bursts and independent workersMore moving parts and eventual dispatchSingle scheduler leaderSmall deployments and simple orderingLeadership bottleneck and failoverSharded scheduler fleetMany schedules and higher throughputShard ownership, rebalancing and fencingDurable 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.

Further reading and verified references

Temporal architecture documentation — durable execution, histories and retry semantics.Temporal: build a durable job queue — retries and idempotent execution.PostgreSQL SELECT documentation — row locking and SKIP LOCKED.Amazon SQS visibility timeout — redelivery and visibility semantics.Stripe idempotent requests — safe retry patterns for external effects.Kubernetes CronJob documentation — scheduling caveats and job creation.

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

Categories

No Responses

Leave a Reply

Your email address will not be published. Required fields are marked *