Distributed Job Scheduler
A worker resumes after its lease expires, just as a replacement starts the same execution.
Topic tools
Layout updated
Problem statement
Design a scheduler for one-time and recurring jobs. Users can submit jobs, and the system runs each scheduled occurrence and tracks its outcome even when workers fail.
Functional requirements
- Create, edit and cancel one-off or recurring jobs.
- Run due executions and expose status, attempts and logs.
- Retry transient failures with backoff and park work that needs review.
Non-functional requirements
- Measure punctuality from scheduled time to actual start. Set a separate budget for overload and delayed starts.
- Preserve one current dispatch generation and one current worker per execution.
- Recover from cache, process and broker failures without losing committed execution intent.
- State the external effect guarantees, retry budget and regional recovery objectives.
Back-of-the-envelope estimates
| Illustrative estimate |
|---|
| 10 million executions/day is about 116/s on average. At 100 KB each, payloads add about 1 TB/day. |
| 10 million jobs due in five seconds require 2 million starts/s. At 50,000/s, starts take at least 200 seconds. |
| Five minutes of lookahead at the 116/s average holds about 35,000 IDs. |
Entities
| Entity / logical owner |
|---|
| JobDefinition(jobId, schedule, payloadRef, version, status, materializationCursor) |
| Execution(executionId, jobId, scheduledAt, version, state, dispatchGeneration, nextAttemptAt) |
| Attempt(executionId, workerEpoch, leaseExpiresAt, heartbeatAt, result) |
| (eventId, executionId, dispatchGeneration, publishStatus) |
| ShardOwnership(shardId, schedulerEpoch) |
| ExecutionLog(executionId, workerEpoch, timestamp, message) |
API design
| Operation / input | Response and retry contract |
|---|---|
POST/jobs {requestId, schedule, payloadRef} | 201 after committing the job. The same request ID and payload return the original job. |
PATCH/jobs/{id} {expectedVersion, schedule?, status?} | 200 on eligible change and 409 on a stale version. Cancellation of running work is cooperative. |
GET/jobs/{id}/executions?cursor=... | 200 with scheduled time, current state, attempts and cursor. |
POST/internal/executions/{id}/heartbeat {workerEpoch} | 200 if the matching still has an unexpired . A stale worker must stop. |
POST/internal/executions/{id}/complete {workerEpoch, result} | 200 for the committed result or a repeat of the same completion. Reject a stale owner. |
High-level design
How to draw this design
- Register jobsJob Management and PostgreSQL schedules
- Find due workPrefetch, Redis sorted sets, and dispatcher
- Claim and deliverPostgreSQL transaction, relay, and queue
- Execute and recoverWorkers, external target, and scanner
Find a due execution in Redis or PostgreSQL, commit its claim and , then deliver it to a worker.
- State ownership
- PostgreSQL owns schedules, execution claims, and leases. Redis holds a rebuildable due index.
- Scale
- Partition due work and cap fallback queries and worker concurrency.
- Correctness
- The scheduler guards dispatch. The worker guards a single execution.
- Failure and recovery
- After expiry, reconcile uncertain effects before trying the same execution again.
Scheduler architecture and recovery paths
Read down from the client to PostgreSQL, then follow the due-time branch on the left and the delivery branch on the right. The dispatcher claims the execution and records its event in one transaction. Recovery writes back to PostgreSQL before any retry can be published.
- Edge
- Compute
- State
- Messaging
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 15 flow steps
Execution and failure recovery
Follow the normal execution path down the left. A retry returns to SCHEDULED so it receives a fresh claim and record. Cancellation can also close a claimed, queued, or retrying execution before a worker starts. A running execution can only become CANCELLED after a safe stop.
━━ Synchronous┄┄ Asynchronous···· Recovery / control▧ Fault
Each arrow is one interaction. Request, background and recovery branches are not one linear transaction.
Read the 9 flow steps
High-level design component walkthrough
Client
Create, edit, cancel or inspect a scheduled job.
Why, tradeoff and connected operations
Reuse a stable request key for an ambiguous create.
Tradeoff: Retries must keep the same key and payload.
Connected operations: Manage jobs
Job Management API
Validate requests and commit job definitions with a one-off execution or recurring materialization cursor.
Why, tradeoff and connected operations
A version check protects against concurrent schedule edits.
Tradeoff: A durable create can return before any execution begins.
Connected operations: Manage jobs; Commit schedule
PostgreSQL: Jobs, Executions and Outbox
Own job definitions, execution state, worker leases and the . Atomically claim an eligible execution and insert its event on the same .
Why, tradeoff and connected operations
PostgreSQL keeps jobs, execution ownership and intent in one transaction. Conditional updates and unique keys stop two schedulers from claiming the same execution. makes this correctness boundary clearer than coordinating separate key-value records.
Tradeoff: Bound due scans to preserve capacity for writes and leases. RabbitMQ publication happens after commit and can be retried.
Connected operations: Commit schedule; Upcoming executions; claim and ; Committed dispatch events; , heartbeat, result; fallback; Recover leases and retries
Relay / Prefetch
Read near-term executions and materialize recurring occurrences from a durable cursor.
Why, tradeoff and connected operations
An overlapping window and stable IDs repair gaps without creating duplicate occurrences.
Tradeoff: Refilling Redis uses bounded database reads.
Connected operations: Upcoming executions; Index next 5 minutes
Redis Sorted Sets
Index execution IDs with due time as the score.
Why, tradeoff and connected operations
Redis sorted sets efficiently find execution IDs by due time. The scheduler avoids repeatedly scanning all jobs. Redis is a rebuildable scheduling index; PostgreSQL still decides whether a job may run.
Tradeoff: Eviction, a missed fill or an outage can increase start delay.
Connected operations: Index next 5 minutes; Due execution IDs
Scheduler / Dispatcher
Find candidates and try claims under the current scheduler .
Why, tradeoff and connected operations
Multiple dispatchers can nominate the same execution. PostgreSQL commits only one eligible claim.
Tradeoff: Per- limits may delay work in a burst.
Connected operations: Due execution IDs; claim and ; fallback
Outbox Relay
Publish committed records and record broker confirms.
Why, tradeoff and connected operations
A crash after broker acceptance can cause the relay to resend the same event ID.
Tradeoff: Track oldest unpublished age and retry with backoff.
Connected operations: Committed dispatch events; Publish with confirm
RabbitMQ (or SQS)
Deliver and redeliver job messages.
Why, tradeoff and connected operations
Use durable queues, publisher confirms and manual acknowledgements. SQS Standard with visibility timeouts is a managed alternative.
Tradeoff: Queue acknowledgement and visibility do not grant ownership.
Connected operations: Publish with confirm; Deliver execution
Execution Workers
Acquire a , heartbeat, renew and conditionally finish the current execution.
Why, tradeoff and connected operations
Check execution ID and dispatch generation on delivery. Guard writes using the current worker and an unexpired .
Tradeoff: An expired cannot stop a paused process.
Connected operations: Deliver execution; , heartbeat, result; Idempotent execution; Write attempt logs; Report execution metrics
External Execution Target
Apply one logical effect using a stable key.
Why, tradeoff and connected operations
A target that supports also validates the current worker at the effect boundary.
Tradeoff: cannot tell whether an earlier attempt already applied its effect. Reconcile ambiguous outcomes when the target cannot deduplicate.
Connected operations: Idempotent execution
Recovery Scanner
Find expired leases, due retries and stuck claims in bounded PostgreSQL batches.
Why, tradeoff and connected operations
Retire expired attempts conditionally and re-drive the existing record for an unpublished claim.
Tradeoff: Backoff, and a retry cap prevent a recovery storm.
Connected operations: Recover leases and retries
Cassandra Execution Logs
Keep attempt logs keyed by execution and worker .
Why, tradeoff and connected operations
Cassandra stores append-heavy execution logs by execution and time bucket. Predictable keys spread the write load and keep debugging reads separate from scheduling. Unlike the execution store, this log store does not need cross-record business transactions.
Tradeoff: Logs can lag. PostgreSQL remains authoritative for status.
Connected operations: Write attempt logs
Monitoring and Alerts
Track start delay, age, queue lag, expired leases and dead letters.
Why, tradeoff and connected operations
Correlate metrics with attempt logs. Aggregate metrics by and tenant tier.
Tradeoff: Keep execution IDs in logs and traces to control metric cardinality.
Connected operations: Report execution metrics
SCHEDULED
A durable occurrence is waiting for its due time.
Why, tradeoff and connected operations
Its stable identity survives discovery failures.
Tradeoff: Bound indexed scans.
Connected operations: Due time, claim and ; Cancel before claim; Backoff elapsed
CLAIMED
A dispatcher committed its generation and row.
Why, tradeoff and connected operations
An row keeps intent durable through a crash.
Tradeoff: Broker publication is a later operation.
Connected operations: Due time, claim and ; Broker accepts
QUEUED
The broker accepted the current dispatch generation.
Why, tradeoff and connected operations
A broker confirm or matching received delivery proves acceptance.
Tradeoff: The worker may observe acceptance before the relay records it.
Connected operations: Broker accepts; Acquire worker
RUNNING
One worker holds an unexpired execution .
Why, tradeoff and connected operations
A conditional write grants the and worker .
Tradeoff: An expired owner may still be executing code.
Connected operations: Acquire worker ; Commit success; Failure or expiry
COMPLETED
The current worker committed its successful result.
Why, tradeoff and connected operations
A duplicate delivery can safely acknowledge a terminal record.
Tradeoff: Uncertain external effects may need before recording success.
Connected operations: Commit success
FAILED
The attempt failed or recovery found an expired .
Why, tradeoff and connected operations
The record distinguishes known failure from unknown external outcome.
Tradeoff: Permanent failures can remain FAILED.
Connected operations: Failure or expiry; Safe to retry; Park for review
RETRY_PENDING
Retry is allowed after nextAttemptAt.
Why, tradeoff and connected operations
Backoff preserves the same execution and effect identity.
Tradeoff: The next attempt needs a new dispatch generation and worker .
Connected operations: Safe to retry; Backoff elapsed
CANCELLED
A pending execution was cancelled or a worker stopped safely.
Why, tradeoff and connected operations
Cancellation competes with claim or start on the same authoritative record.
Tradeoff: An effect already applied may be too late to cancel.
Connected operations: Cancel before claim
DLQ
Work is parked after retry exhaustion or an unsafe unknown outcome.
Why, tradeoff and connected operations
Record the terminal reason and publish a dead-letter event through the .
Tradeoff: Manual replay must preserve effect identity when repeating the same intended effect.
Connected operations: Park for review
Engineering control room
Deep dives — decisions, failures and recovery
Open a deep dive to follow the steps, try an example and see how recovery works.
Tradeoffs and alternatives
| Decision | Tradeoff / alternative and recovery implication |
|---|---|
| Use Redis for discovery and PostgreSQL for claims | Redis reduces normal polling. A due-time index and bounded fallback maintain progress at lower throughput. |
| Fence scheduler ownership and worker execution separately | A fence must be enforced where the protected state changes. External effects still need or . |
| Plan for synchronized bursts and retries | , admission control and tenant quotas can delay low-priority work or reject new schedules. |
| Publish reliably and deduplicate at the worker | Worker adds a database round trip. The broker can still deliver duplicates. |
| Retry safely after a failure or timeout | Retries recover transient failures but add load. Park a job when the effect is uncertain and cannot be deduplicated or verified. |
| Recover a after database or regional failover | Asynchronous copies reduce write latency and can lose acknowledged changes in regional loss. Synchronous remote durability costs a WAN round trip and can block writes during a partition. |
Production scars & failure modes
A worker resumes after its lease expires, just as a replacement starts the same execution.
Look for: Compare dispatch generation, worker , expiry and external effect key for both attempts.
Recovery and invariant: Reject stale epochs at protected writes. Reconcile uncertain effects before allowing the replacement to repeat them.
| Component / failure | Impact | Recovery mechanism | Alternative / tradeoff |
|---|---|---|---|
| Scheduler crashes | A pre-commit crash leaves an eligible execution. A post-commit crash may leave an unpublished event. | Redis or a due scan finds the first case. The relay resumes the second with the same event ID. | Measure due lag and oldest unpublished age. |
| Redis is unavailable or missing entries | The fast due index cannot find every execution. | Switch to indexed PostgreSQL scans with per- page limits and concurrency budgets. Refill sorted sets from the database. | Reserve capacity for writes and renewals. Expect higher start lag. |
| Worker crashes or loses its | The effect may already have happened. | Retire the expired attempt conditionally and retry under a new only if the effect is known safe or can be deduplicated. | Track expired leases and unresolved effects. |
| Duplicate queue delivery | Two messages carry the same execution and dispatch generation. | One database acquisition wins. Acknowledge terminal and stale messages. An already-running delivery can be acknowledged when durable recovery can re-drive it. | Broker redelivery is expected. |
| Stale worker resumes | An expired worker may still try to renew, finish or call the target. | Reject stale epochs in PostgreSQL. The target must validate its own fence and preserve effect . | A database fence cannot revoke a request already in flight. |
| External effect is uncertain | A timeout can hide a successful effect. | Check status by the stable effect key, or retry the same key under the provider contract. Otherwise reconcile or park for review. | Track unresolved effects and compare provider records. |
| PostgreSQL primary fails | Workers can no longer establish or renew authority. | Promote a fenced primary under the durability policy. Stop granting work while PostgreSQL is unavailable. Reconcile effects if commits may have been lost. | Verify the old primary cannot still accept writes. |
| Queue is unavailable | Unpublished records accumulate. | Retry with backoff and stop admitting claims at the budget. Resume confirmed publication when the broker recovers. | Measure oldest age and drain rate. |
| Cancellation races with dispatch or start | Redis or RabbitMQ may still hold a cancelled generation. | Serialize cancellation against claim or acquisition. Recheck state and generation on delivery. For running work request a safe stop or report too late. | Track requested cancellation separately from terminal cancellation. |
| Home region fails | The standby may lack recent claims, records or results. | Fence the old owner and database writer. Restore through a known replication position and reconcile in-flight effects before replay. | State and and reserve regional catch-up capacity. |
90-second interview summary
I would persist job definitions and unique scheduled executions in PostgreSQL. A prefetch service fills Redis sorted sets for a short lookahead window. If Redis fails or misses entries, bounded due-time scans find those executions and rebuild the index.
A dispatcher checks the owner, job version, due time and execution state. It claims the execution and writes an row together. The relay publishes to RabbitMQ. If it crashes after publishing but before recording the confirm, the same message can appear twice. Workers must acquire a for the matching generation.
Workers heartbeat, renew leases and finish through conditional PostgreSQL updates. The scheduler guards dispatch and the worker guards one execution. Recovery retires an expired owner and gives a replacement a newer fence. External effects use a stable key and a path for unclear outcomes.
I would measure scheduled time to actual start, bound queue recovery and reserve capacity for updates. Regional promotion fences the old writer and restores execution and state before authorizing replay. The main tradeoff is cheap, approximate discovery with a durable ownership decision and explicit start-delay and recovery objectives.
Explain it without looking
Explain use redis for discovery and postgresql for claims
Reveal answer
Look up due IDs cheaply, then claim the eligible execution in PostgreSQL.
Cache entries can disappear, repeat or outlive a cancellation.
Redis reduces normal polling. A due-time index and bounded fallback maintain progress at lower throughput.
Explain fence scheduler ownership and worker execution separately
Reveal answer
Check the scheduler at dispatch and the worker at heartbeat, completion and protected effects.
Scheduler failover changes who can claim for a . Worker failover changes who can run one execution.
A fence must be enforced where the protected state changes. External effects still need or .
Explain plan for synchronized bursts and retries
Reveal answer
Measure scheduled time to actual start and limit normal and recovery traffic.
A full queue can meet its publish target while jobs miss their promised start.
, admission control and tenant quotas can delay low-priority work or reject new schedules.
Explain publish reliably and deduplicate at the worker
Reveal answer
Commit the claim and together, then publish a stable event ID.
RabbitMQ can accept a message before the relay records the confirmation.
Worker adds a database round trip. The broker can still deliver duplicates.
Explain retry safely after a failure or timeout
Reveal answer
Keep the execution ID and effect key. Allocate a new dispatch generation and worker .
A transient failure before the external call is different from a timeout after the target may have written.
Retries recover transient failures but add load. Park a job when the effect is uncertain and cannot be deduplicated or verified.
Explain recover a after database or regional failover
Reveal answer
Fence the old database writer and scheduler, recover durable state, then reconcile in-flight effects.
A replacement region may lack committed claims, results and events that already caused external effects.
Asynchronous copies reduce write latency and can lose acknowledged changes in regional loss. Synchronous remote durability costs a WAN round trip and can block writes during a partition.
Revision checklist
Revision checklist
- Reconstruct use redis for discovery and postgresql for claims: Look up due IDs cheaply, then claim the eligible execution in PostgreSQL.
- Reconstruct fence scheduler ownership and worker execution separately: Check the scheduler at dispatch and the worker at heartbeat, completion and protected effects.
- Reconstruct plan for synchronized bursts and retries: Measure scheduled time to actual start and limit normal and recovery traffic.
- Reconstruct publish reliably and deduplicate at the worker: Commit the claim and together, then publish a stable event ID.
- Reconstruct retry safely after a failure or timeout: Keep the execution ID and effect key. Allocate a new dispatch generation and worker .
- Reconstruct recover a after database or regional failover: Fence the old database writer and scheduler, recover durable state, then reconcile in-flight effects.
- Name the authoritative state, boundary, retry identity and failure-domain durability guarantee.
- Explain one alternative and exactly which guarantee you would relax.
- Redraw the request and recovery paths without looking; mark what required a hint.
60-minute interview outline
60-minute interview walkthrough
| Time | Focus | What to cover |
|---|---|---|
| 0–5 min | Introductions | Introduce yourself briefly and confirm the interview format. |
| 5–15 min | Scope and scale | Scope one-off and recurring jobs. Estimate peak due jobs and define acceptable delay between the due time and start. |
| 15–30 min | High-level design | Draw durable schedules in PostgreSQL, the Redis due-time index, claim and , queue, and workers. |
| 30–45 min | Deep dives | Explain why Redis supplies candidates and PostgreSQL grants ownership. Distinguish the scheduler from the worker . |
| 45–55 min | Failure and recovery | Walk through a worker expiry after a possible external effect. Fence stale updates and reconcile before retrying. |
| 55–60 min | Wrap-up | Summarize the design and its main tradeoff. Leave time for questions. |
On this page
- Problem statement
- Functional requirements
- Non-functional requirements
- Back-of-the-envelope estimates
- Entities
- API design
- High-level design
- High-level design component walkthrough
- Engineering control room
- Deep dives — decisions, failures and recovery
- Tradeoffs and alternatives
- Production scars & failure modes
- 90-second interview summary
- Explain it without looking
- Revision checklist
- 60-minute interview walkthrough