Build a Reliable Recurring Task Scheduler with Recovery
System DesignModel answerLast updated
Design a service that fires recurring tasks on time-zone-aware schedules, survives crashes, handles missed runs, and avoids duplicate logical runs.
Design a service that lets users register recurring tasks and guarantees they are triggered according to a calendar-style schedule (for example "every weekday at 09:00 in Europe/Berlin"). The service must remain correct when machines crash, restart, or are briefly unreachable.
Your answer should explain:
- Schedule interpretation: how a schedule is stored and how the next fire time is computed.
- Dispatch: how due runs are discovered and handed to workers.
- Worker execution: how a worker takes ownership of a run, reports progress, and finishes.
- Failure recovery: what happens when a scheduler node or worker dies mid-way.
- Missed runs: what the system does if it was down or backlogged when a run was due.
Things to settle explicitly in your design:
- State your assumptions about scale (number of schedules, peak fires per second, acceptable lateness) and about delivery guarantees.
- Separate a logical occurrence (the run that was supposed to happen at a given time) from an attempt (one try at executing it).
- Every schedule carries its own time zone. Explain how daylight-saving gaps and overlaps are handled, and what happens when a schedule is edited or disabled.
- Do not claim exactly-once side effects in external systems just because your own database rows are unique.
Useful clarifying questions: Should missed runs be skipped, merged into one, or replayed one by one? May two runs of the same task overlap? Are the tasks idempotent? How are retries and permanent failures surfaced to users?
Hints
Hint 1
Model two entities: a schedule (rule, time zone, version, next fire time) and an occurrence (schedule id + scheduled instant, unique together). Attempts hang off occurrences.
Hint 2
Make 'create the due occurrence' and 'advance the schedule's next fire time' a single transaction, protected by a unique key, so multiple scheduler replicas cannot produce duplicates.
Hint 3
Workers should claim an occurrence with a lease that expires unless renewed by heartbeat; a reaper returns expired claims to the queue. Because a worker may die after the side effect but before reporting, pass a stable idempotency key to the task.
Hint 4
Decide up front on a misfire policy (skip, run once, replay all up to a cap) and on DST rules (gap: run at the next valid time; overlap: run once, on the first occurrence).
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Assumptions
- Around 1M schedules, peak of a few thousand fires per second (many schedules share round times like :00), acceptable start lateness of about 1–5 seconds.
- Delivery is at-least-once for execution attempts, with exactly one logical occurrence per schedule per fire time. Effective exactly-once for side effects is only possible if the task is idempotent or accepts an idempotency key.
Data model
- schedules:
id, owner, cron_expr, tz (IANA name), payload, enabled, version, next_fire_at (UTC), misfire_policy, overlap_policy, max_catchup. - occurrences:
id, schedule_id, scheduled_for (UTC instant), schedule_version, state (PENDING, RUNNING, SUCCEEDED, FAILED, SKIPPED), attempt_count, lease_owner, lease_expires_at. Unique constraint on(schedule_id, scheduled_for). - attempts:
occurrence_id, attempt_no, worker, started_at, finished_at, result, error.
Store the rule and the IANA zone, not a precomputed list of instants. Store next_fire_at in UTC and index it.
Schedule interpretation
Compute the next fire time by evaluating the expression in the schedule's local zone, then converting to UTC.
- DST gap (a local time that does not exist, e.g. 02:30 on spring-forward day): run at the first valid instant after the gap, once.
- DST overlap (a local time that occurs twice): run once, at the first occurrence.
- Always compute "next after the previous scheduled instant", never "now + interval", so drift does not accumulate.
- Use a vetted library and a current tz database; test around transitions.
Dispatch
A set of stateless scheduler replicas loop frequently (e.g. every second):
- In a transaction, select due schedules:
WHERE enabled AND next_fire_at <= now() ORDER BY next_fire_at LIMIT N FOR UPDATE SKIP LOCKED. - For each, insert an occurrence (the unique key makes this idempotent), compute the next fire time, and update
next_fire_atandversionin the same transaction. - Commit, then publish the occurrence to a work queue (or let workers poll the table).
If a replica crashes before commit, nothing happened and another picks it up. If it crashes after commit but before publishing, a sweeper republishes PENDING occurrences that have no live claim. Because rows are locked with SKIP LOCKED, replicas share load without leader election. For larger scale, shard schedules by hash of id so each shard has its own range scan.
Worker execution
- A worker claims an occurrence atomically:
UPDATE ... SET state='RUNNING', lease_owner=?, lease_expires_at=now()+30s WHERE id=? AND (state='PENDING' OR lease_expires_at < now()). Only one update wins. - It heartbeats to extend the lease while running, and uses a fencing token (attempt number) when writing results so a stale worker cannot overwrite a newer one.
- On finish, it records the attempt and sets the state. On failure, retry with exponential backoff and jitter up to a limit, then mark FAILED and alert the owner.
- Pass
occurrence_idas an idempotency key to downstream calls. This is what actually protects external side effects. A worker can crash after the side effect but before acknowledging, so the retry must be safe.
Failure recovery
- Worker dies: the lease expires, a reaper (or the next claimer) returns the occurrence to PENDING and a new attempt starts.
- Scheduler dies: no state is lost, since all state is in the database. Another replica continues.
- Database failover: use synchronous replication or a consensus-backed store so committed occurrences are not lost.
- Long-running tasks: lease heartbeats with a hard maximum runtime; beyond it the attempt is declared timed out.
Missed runs
When a scheduler finds next_fire_at far in the past, apply the schedule's policy:
- Skip: record SKIPPED occurrences (or none) and jump to the next future time. Good for "refresh cache".
- Coalesce / run once: create a single occurrence for the latest missed time. Good for reports.
- Replay all: create each missed occurrence, capped by
max_catchupand rate-limited so a long outage does not cause a stampede.
Also define an overlap policy: allow, skip if previous still running, or queue. Use a per-schedule concurrency check at claim time.
Edits and disabling
Increment version on edit and recompute next_fire_at from the edit time. Already-created PENDING occurrences either run (default, with their old payload version) or are cancelled, per a documented rule. Disabling stops new occurrences; in-flight ones finish unless the user chooses to cancel.
Operations
- Metrics: scheduling lag (
now - scheduled_forat start), queue depth, lease expirations, retry rate, failures per schedule. - Backpressure: per-tenant quotas, per-queue concurrency limits, jitter for popular times like midnight.
- Retention: archive old occurrences and attempts; keep indexes on
next_fire_atand(state, lease_expires_at). - Audit trail and a manual "run now" that creates an occurrence with a distinct key.
Trade-offs
- A relational database with SKIP LOCKED is simple and sufficient to roughly tens of thousands of operations per second; beyond that, shard it or move the timing wheel into memory, with the database as the source of truth.
- Polling is simple but adds latency up to the poll interval; a timing wheel or priority queue loaded with the next minute of work reduces that.
Common mistakes
- Computing the next run as "now + interval" and drifting.
- Using a single leader without fencing, causing double dispatch after a pause.
- Claiming exactly-once execution without idempotent tasks.
- Ignoring DST and storing local times without the zone.
- Replaying thousands of missed runs at once after an outage.
- Not distinguishing occurrence from attempt, which makes retries look like duplicate runs.