Scheduler Design Where Each Run Starts At Most Once
System DesignModel answerLast updated
Design a distributed job scheduler for one-time and recurring jobs where a scheduled run must never start twice, covering crash ambiguity, deadlines, logs, cancellation and notifications.
Design a distributed service that runs background jobs on a schedule. It must support:
- One-time jobs and recurring jobs (for example, cron-style schedules).
- An execution deadline (SLA) for each run.
- Log capture for every run.
- Cancellation of pending or upcoming runs.
- Notifications to subscribers about run outcomes.
The core guarantee is at-most-once execution per scheduled run: for any single scheduled occurrence, the job's code must never begin more than once.
What to cover
- The public API (create, status, cancel, history) and the identifiers you use for jobs and for individual runs.
- How a worker durably claims a run before starting it.
- What happens when a worker, queue, or database node crashes at different moments, especially when you cannot tell whether the run actually started.
- Why the guarantee limits availability and completion, and how you present that trade-off.
- How you report missed deadlines.
- Where logs live and how they are retrieved.
- How subscribers get notified without losing events.
- Whether your chosen queue (for example Redis) is durable enough, or whether you need something else.
Points to clarify with the interviewer
- Does "execution" mean the application code starts, or that an external side effect commits?
- Is it acceptable for a run to end up lost or in an unknown state?
- May a retry be modeled as a new scheduled run?
- Does the SLA measure start time or completion time?
- Must subscribers be able to recover notifications they missed?
Hints
Hint 1
Separate the identity of a job (the definition) from the identity of a run (one occurrence, for example job_id plus scheduled time). Make the run ID deterministic so that creating it twice is idempotent.
Hint 2
Treat the claim as a conditional write in a strongly consistent store, moving the run from PENDING to STARTING with a fencing token. Ask what a new owner can safely conclude when the old owner vanished after STARTING.
Hint 3
Pick a rule for ambiguous runs: mark them UNKNOWN or FAILED for human or policy review rather than silently re-running them. Then discuss the alternative of at-least-once delivery plus idempotent effects.
Hint 4
For notifications, write the event to an outbox table in the same transaction as the state change, and let a relay publish it. Do not rely on a cache-style queue as the source of truth.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify the guarantee first
"At-most-once" can mean two things, and the design depends on which:
- At-most-once start: the job's code is never launched twice for one occurrence. This is what the prompt asks for, and it is achievable.
- Exactly-once effect: the external result happens once. This cannot be guaranteed by a scheduler alone. It needs idempotency keys in the downstream system.
I would state the choice plainly: we guarantee at-most-once start, we accept that some runs may end in an UNKNOWN state, and we expose a run ID that jobs can use as an idempotency key for those who want effect deduplication.
2. Data model and identities
- Job:
job_id, owner, schedule (one-time timestamp or cron expression), payload, SLA (start-by and/or finish-by), status (active, paused, cancelled), version. - Run:
run_id = hash(job_id, scheduled_time). It is deterministic, so a planner that restarts and recreates the same occurrence hits a unique-key conflict instead of creating a duplicate. - Run states:
PENDING -> CLAIMED -> STARTED -> SUCCEEDED | FAILED, plusCANCELLED,MISSEDandUNKNOWN. - Attempt record:
run_id,worker_id,fencing_token,claimed_at,lease_expiry.
3. API
POST /jobs(with an idempotency key) creates a job.GET /jobs/{id}returns the definition and next fire time.GET /jobs/{id}/runsreturns paginated history.GET /runs/{run_id}returns state, timestamps and a log link.POST /jobs/{id}/cancelandPOST /runs/{run_id}/cancel.POST /jobs/{id}/subscriptionsregisters webhook or email subscribers.
4. Architecture
- Planner: scans due schedules and inserts the next Run rows (
INSERT ... ON CONFLICT DO NOTHING). It is sharded byjob_idhash, with leadership per shard. - Metadata store: a strongly consistent database (a sharded relational DB, or a consensus-backed store). This is the source of truth for run state.
- Dispatcher: moves due runs to workers. A queue is only a hint for waking workers. It is not authoritative.
- Workers: claim, start and report on runs.
- Log store: object storage with an index, fed by streaming from workers.
- Outbox relay: publishes notifications.
5. The claim protocol (the heart of the answer)
A worker that receives a run ID does a conditional update:
UPDATE runs
SET state='CLAIMED', owner=:w, token=token+1, lease_expiry=now()+:ttl
WHERE run_id=:id AND state='PENDING';
Only one worker sees one affected row. The worker then does a second conditional write, CLAIMED -> STARTED, before launching the code. Only after that commit does it execute.
This ordering means: if the record says PENDING, the code never started, so it is safe to re-dispatch. If the record says CLAIMED or STARTED and the worker has died, we cannot know whether the code began.
6. Crash analysis
| Crash point | State seen | Action |
|---|---|---|
| Before claim | PENDING | Re-dispatch safely. |
| After claim, before STARTED write | CLAIMED | Code provably never ran, because launch happens only after the STARTED commit. Lease expiry can return it to PENDING. |
| After STARTED write, before or during execution | STARTED, lease expired | Ambiguous. Mark UNKNOWN, alert, never auto-retry. |
| After finish, before reporting | STARTED | Same as above. Optionally let the job emit a heartbeat or completion marker to resolve it. |
| Queue loses the message | PENDING | A sweeper re-enqueues runs that are due and still pending. |
| Dispatcher duplicates a message | PENDING then claimed | The conditional update rejects the second claimant. |
Use the fencing token on every write from a worker, so a paused worker that wakes after its lease expired cannot overwrite newer state.
7. Trade-off to state explicitly
Strict at-most-once means a crash in the ambiguous window costs completion: that run may never finish. Availability of starting is kept (other runs continue), but completion for the affected run is sacrificed. If the business needs completion, offer one of:
- Retry as a new run with a new
run_id(linked viaretry_of), and require the job to be idempotent. - At-least-once with idempotency keys, which is the more common production choice.
Make this a per-job policy: at_most_once (default for non-idempotent work) or at_least_once.
8. SLA and deadline reporting
Define the SLA as a start-by time, and optionally a finish-by time. A deadline monitor queries for runs with scheduled_time + sla < now() and state not in terminal or started states. It marks them MISSED and emits an event. Track metrics such as dispatch lag p50/p99 and the missed-run rate. Capacity planning: for 10k runs per second at peak, shard the run table by job_id and keep the claim path to a single-row write, which sits comfortably within a sharded SQL cluster.
9. Cancellation
Cancellation is a conditional update PENDING -> CANCELLED. If the run is already STARTED, cancellation becomes a best-effort signal to the worker, and the run reports CANCEL_REQUESTED. Cancelling a recurring job also stops the planner from creating future runs.
10. Logs
Workers stream log chunks to object storage keyed by run_id/seq, with a small index row per run. Apply retention and size caps. Logs are append-only, so a crashed run still has partial logs for diagnosing an UNKNOWN state.
11. Notifications
Write the event to an outbox table in the same transaction as the state transition. A relay reads the outbox, publishes to subscribers, and marks entries sent. Delivery is at-least-once, and each event carries an event ID so subscribers can deduplicate. Subscribers that missed events can replay with GET /jobs/{id}/events?after=cursor.
12. Is Redis enough?
Redis is fine as a wake-up queue or delay structure, but it is not a safe system of record. Replication is asynchronous, so a failover can lose acknowledged writes, and a lock based on a single Redis instance can be held by two clients after failover or a long pause. So: keep state and claims in the consistent database, and treat Redis (or SQS, Kafka) purely as an accelerator that the sweeper can rebuild from the database.
13. Common mistakes
- Claiming "exactly once" without defining it.
- Re-running a run after lease expiry and still calling it at-most-once.
- Using a distributed lock without fencing tokens.
- Treating the queue as the source of truth.
- Publishing notifications outside the state-change transaction, so events are lost or phantom.
- Ignoring clock skew: use the database clock for lease and deadline comparisons.