Learning pathsPricingChecking sign-in…
GUIDED PRACTICE

Job Scheduler

Design a service that runs delayed and recurring jobs with retries, cancellation, and multiple worker regions.

Clarify this prompt before choosing components

Ask the highest-impact questions first, agree on priorities, and record the interviewer’s answers. If a detail is unspecified, state an assumption and explain which decision depends on it. The numbers in this worked lesson are exercise assumptions, not company facts.

Ask the interviewerWhy the answer changes the design
One-off, recurring, delayed or dependency jobs?Calendar semantics and recurrence identities differ.
At-most-once attempts or retries with idempotent effects?A lease cannot by itself stop a paused worker.
Scheduling precision, time zones and missed-run policy?Define DST, catch-up limits and clock assumptions.

Use the Interview Playbook for the shared 45-minute sequence and fresher, intermediate, senior and staff evidence. Start with one complete operation. Extend the answer with the failure/recovery traces below, then defend a workload-specific alternative and a measurable rollout. Scope and evidence matter more than a large component list.

Job Scheduler: Understand the building blocks

Choose a mechanism because it satisfies a requirement. These explanations describe the exercise design, not undisclosed implementation choices at the named company.

Job Scheduler: Quick vocabulary

TermMeaning and role in this exercise
API: Application Programming InterfaceThe contract for requests, responses and errors between components. An API route does not itself enforce every business invariant.
SSRF: Server-Side Request ForgeryUntrusted input induces a forbidden server-side fetch; resolved targets and redirects need an enforcing outbound policy.
PK: Primary KeyThe declared row identity in a database schema; it does not automatically enforce every cross-row business rule.
DST: Daylight Saving TimeA local-clock adjustment that can create skipped or repeated wall-clock times. The scheduler must declare which occurrence to create.

Job Scheduler: Calendar schedule, time zone and occurrence identity

What it means: A calendar schedule uses a declared local/time-zone rule; an occurrence identity names one intended firing separately from its retries.

Why this problem needs it: One scheduled firing and its worker attempts need different identities.

How to use it: Resolve daylight-saving ambiguity explicitly, derive the occurrence ID once, and execute attempts under versioned schedule/cancellation policy.

Example in this design: Occurrence o7 retries as attempts 9 and 10 without becoming a second occurrence.

When it fits: Useful for recurring user-local tasks rather than merely waiting a fixed number of seconds.

Alternative and limits: A fixed UTC interval is simpler when that is the intended meaning. Retrying one occurrence must not create a new business occurrence.

Job Scheduler: Durable work queue and backpressure

What it means: A queue separates accepted work from execution. Backpressure limits admission or consumption when downstream capacity is finite.

Why this problem needs it: Due jobs need bounded execution separate from scheduling.

How to use it: Persist a stable job identity, consume with bounded concurrency, acknowledge after the required durable transition, and cap retries/backlog according to policy.

Example in this design: Enqueue o7 under a durable identity and cap workers by downstream capacity.

When it fits: Useful for asynchronous work that must survive worker failure or absorb a finite burst.

Alternative and limits: A synchronous call is simpler for short bounded work. A queue does not create capacity, strict global ordering or exactly-once external effects.

Job Scheduler: Lease, ownership epoch and fencing

What it means: A lease grants temporary work ownership. A fencing token or epoch identifies a newer owner so stale owners can be rejected at the mutation boundary.

Why this problem needs it: An expired worker can resume after reassignment.

How to use it: Claim a job under an atomic authority, increment its attempt/epoch, and require that value on result publication. The protected resource must enforce the check.

Example in this design: Attempt 9 is fenced once attempt 10 owns publication.

When it fits: Useful when workers can pause, restart or overlap after a timeout.

Alternative and limits: A non-expiring lock risks blocking forever. Lease expiry alone cannot stop an old process that resumes; external effects need their own supported idempotency/reconciliation.

Job Scheduler: Dead-Letter Queue (DLQ)

What it means: A DLQ isolates jobs that cannot complete under the configured retry policy so they do not block healthy work indefinitely.

Why this problem needs it: Poison jobs need inspection instead of infinite retries.

How to use it: Store the original job identity, failure reason and retry history; alert and inspect before a deliberate replay that preserves effect identity.

Example in this design: Record a terminal failure with o7 and its attempts before any deliberate replay.

When it fits: Useful for poison inputs or persistent provider errors.

Alternative and limits: A finite retry with a terminal recorded failure can fit small systems. A DLQ is not recovery by itself, and blindly replaying everything can repeat effects.

Interview scope and guarantees

Create one-time or recurring jobs, pause schedules, trigger due occurrences, inspect outcomes and retry failed work. Define timezone and daylight-saving semantics. A schedule is not an execution: each occurrence has its own stable identity.

Capacity worksheet

Assume 10 million schedules with 1 million due per hour: 278/s average. If 100,000 are due at midnight, a one-minute dispatch target requires 1,667/s before execution cost. Partition by due-time bucket and tenant so one synchronized tenant cannot monopolize the fleet.

Concrete API contract

Contract / pseudocode
POST /schedules {expression,timeZone,payload,target}
PATCH /schedules/{id} {expectedVersion,enabled,expression}
GET /runs/{id}
POST /runs/{id}/retry

Data model and access paths

Contract / pseudocode
schedules(id PK,tenant_id,expression,time_zone,version,enabled,next_run_at,misfire_policy)
occurrences(schedule_id,schedule_version,scheduled_time,run_id); UNIQUE(schedule_id,schedule_version,scheduled_time)
runs(id PK,state,generation,next_eligible_at,lease_until); INDEX(state,next_eligible_at)
attempts(run_id,generation,worker_id,started_at,finished_at,outcome); PK(run_id,generation)
outbox(event_id PK,run_id,published_at)

Evolve a solution and explain each change

Three architecture decisions for Job Scheduler, including the pressure each introduces.
Three architecture decisions for Job Scheduler, including the pressure each introduces.
Read the diagram

Persist due work / Store job definitions and next eligible execution time. / A timer in one process disappears on restart.; Lease executions / Claim due runs atomically with attempts, deadlines, and retry policy. / Expired workers can finish after a replacement starts.; Fence effects and calendars / Separate scheduled runs from attempts; define timezone, missed-run, and overlap rules. / A successful task side effect can precede an ambiguous acknowledgement.

Open original
Job Scheduler · architecture decisions
Three architecture decisions for Job Scheduler, including the pressure each introduces.

Three architecture decisions for Job Scheduler, including the pressure each introduces.

Step 1: Persist due work

Store job definitions and next eligible execution time. A timer in one process disappears on restart.

Step 2: Lease executions

Claim due runs atomically with attempts, deadlines, and retry policy. Expired workers can finish after a replacement starts.

Step 3: Fence effects and calendars

Separate scheduled runs from attempts; define timezone, missed-run, and overlap rules. A successful task side effect can precede an ambiguous acknowledgement.

Responsibility overview

Connected responsibilities for Job Scheduler. Trace the authoritative and derived paths separately.
Connected responsibilities for Job Scheduler. Trace the authoritative and derived paths separately.
Read the diagram

Job owner to Schedule API: define schedule; Schedule API to Run DB: persist logical runs; Run DB to Due queue: due execution intent; Due queue to Executor: lease attempt token; Executor to Task target: invoke run identity; Executor to Run DB: fenced outcome

Open original
Job Scheduler · connected architecture
Connected responsibilities for Job Scheduler. Trace the authoritative and derived paths separately.

Connected responsibilities for Job Scheduler. Trace the authoritative and derived paths separately.

Worked end-to-end scenario

A daily job has run identity (job J, scheduled time T). Worker W1 leases attempt 1 and calls an external service. Its acknowledgement is lost and the lease expires. W2 retries attempt 2 using the same run-level idempotency identity for the external effect. W1’s later status update is fenced by its old attempt token. Scheduling tomorrow is distinct from retrying today’s run. For a daylight-saving transition, the schedule must say whether a repeated local time yields one run or two and how a nonexistent local time is handled. On a prolonged outage, choose skip, coalesce, or bounded catch-up explicitly.

Why these access paths matter

Index runnable executions by next eligible time and state. A unique job-plus-scheduled-time key prevents duplicate logical runs. Store attempts separately from run outcome and maintain a current fencing token. Partition due work into bounded claim batches; a lease is ownership of an attempt, not proof that the external task has never executed.

Build the baseline first

Job Scheduler: baseline request paths.
Job Scheduler · working baseline
Read the diagram

Schedule API → durable rule → due-time index; Due scanner → unique occurrence and outbox; Queue → leased worker → durable outcome

Open original
Job Scheduler · working baseline
Job Scheduler: baseline request paths.

Job Scheduler · working baseline

  1. Schedule API → durable rule → due-time index.
  2. Due scanner → unique occurrence and outbox.
  3. Queue → leased worker → durable outcome.

Evolve the design under load

Job Scheduler: additional scaling and recovery paths.
Job Scheduler · scale and recovery paths
Read the diagram

Time buckets → sharded scanners → fair queues; Worker pools → per-target concurrency budgets; Overdue scanner → reconciliation → missed occurrences

Open original
Job Scheduler · scale and recovery paths
Job Scheduler: additional scaling and recovery paths.

Job Scheduler · scale and recovery paths

  1. Time buckets → sharded scanners → fair queues.
  2. Worker pools → per-target concurrency budgets.
  3. Overdue scanner → reconciliation → missed occurrences.

Defend the hardest decision

Define misfire behavior: skip missed times, run the latest once, or catch up every occurrence within a cap. A recurring rule in a local timezone can encounter a missing or repeated wall-clock time; document the chosen behavior and persist computed UTC occurrence instants. Editing a schedule increments its version so queued old occurrences can be rejected or honored according to policy.

Failure and recovery analysis

A scanner creates a run then crashes before enqueueing it. The outbox repairs publication. A worker loses its lease while still calling the target; fencing protects internal state but cannot retract an external side effect. Require a target idempotency key derived from run ID, or document the remaining duplicate window. A heartbeat is not proof that a task succeeded.

Security and privacy boundary

Authorize target endpoints, validate payload size, and prevent scheduler use as an SSRF or privilege-escalation service.

Interview follow-ups with reasoning

Question: How do you cancel a running job?

Show answer and explanation

Answer: Record cancellation intent and cooperate with workers; external effects may need compensation.

Question: How do you recover a scanner partition?

Show answer and explanation

Answer: Resume due-time scanning and rely on unique occurrence insertion.

Question: Which metrics matter?

Show answer and explanation

Answer: Schedule-to-start lag, oldest due occurrence, lease churn and per-tenant starvation.

Operate and verify the design

Scheduled-to-start lag, oldest overdue occurrence, lease churn and tenant starvation.

Restart the scanner after occurrence commit but before enqueue and verify one durable run identity.

A second scenario to test transfer

A daily 09:00 job is scheduled in a local timezone that changes clocks. Persist the timezone and recurrence intent, then define whether a skipped local time runs at the next valid instant and how an ambiguous repeated time is handled. The next occurrence is calculated according to that documented policy, not a fixed 24-hour timer.

The scheduler publishes a due run and crashes before updating its row. How should recovery behave?

Show answer and explanation

Answer: Recompute or republish using the same occurrence identity. A unique run key prevents a second logical occurrence, and the worker applies the effect idempotently. Mark dispatch only after durable handoff, but assume the handoff may repeat. State whether delayed work is replayed, skipped, or coalesced after a prolonged outage.

Compare alternatives

ChoiceBenefitCost
Pre-materialized runsFast due-time scanHorizon maintenance
On-demand recurrenceLess stored future workMore scheduler computation
Catch-up policyPredictable outage recoveryMay skip or delay promised work
Fencing + idempotencySafe retriesExternal target support

A design-changing exercise

The task sent an email but crashed before marking success. Can exactly-once scheduling prevent a second email?

Show answer and explanation

Answer: Not by itself. The email boundary needs idempotency or reconciliation; the scheduler cannot atomically commit an unrelated provider effect.

Design workshop: materialize occurrences and lease attempts

Core scope is one-time/recurring schedules, bounded dispatch, retry and cancellation. Arbitrary code execution is a separate worker capability. Choose dispatch within one minute for admitted work, at-least-once task delivery and one logical occurrence per schedule/version/time. External exactly-once effects require target support.

Choose a rolling future occurrence horizon plus a due-time database index. next_run_at advances transactionally with unique occurrence creation. A scan claims bounded due batches using row locks/SKIP LOCKED where appropriate; this is queue-style work distribution, not a globally ordered read guarantee. Set runs.next_eligible_at for first dispatch and subsequent retry. Keep attempts(run,generation,worker,start,end,outcome) separate from the logical run.

sql
BEGIN;
SELECT id FROM runs
WHERE state='ready' AND next_eligible_at<=:now
ORDER BY next_eligible_at,id
LIMIT 100 FOR UPDATE SKIP LOCKED;
-- For each selected run: state=leased, generation+=1,
-- lease_until=now+lease; insert attempts and dispatch outbox.
COMMIT;

A worker commits result only if run generation and active lease/owner policy still match. Expired ownership can create duplicate execution, but cannot create a second logical occurrence. Send the stable run ID as the target idempotency key; using attempt generation as the external key would turn a retry into a new side effect. Use capped exponential backoff with jitter, for example min(300s,2^attempt seconds), maximum attempts and a DLQ with run/attempt evidence.

Keep the schedule, logical occurrence, and execution attempt as separate records. The occurrence key is (schedule_id, schedule_version, scheduled_at_utc); an attempt key is (run_id, generation). The scanner inserts the run and dispatch outbox event in one transaction. Workers may receive an outbox event more than once, then claim the run with a bounded lease. The indexed claim query scans only state in (ready,retry_wait) and next_eligible_at <= database_now, ordered by due time and run ID, with FOR UPDATE SKIP LOCKED and a fixed batch limit. The outbox wakes workers; the indexed scan repairs missed notifications.

Choose queue as the default overlap policy: one unfinished occurrence per schedule may execute at once, and later occurrences wait. A schedule can explicitly choose allow for independent work or skip when an occurrence arrives while one is unfinished. Record skipped occurrence identity and reason so catch-up does not silently fabricate a run. On edit, increment the schedule version and cancel unclaimed old-version occurrences; a claimed occurrence gets cooperative cancellation intent and is allowed to report an already accepted external effect. A failed or expired old-version attempt does not retry after cancellation.

Logical run survives scanner and worker crashes. Scanner to Run DB/outbox: Insert occurrence and run R; unique schedule/version/time; Run DB/outbox to Executor: Publish R, possibly more than once; Executor to Run DB/outbox: Claim generation 4 with bounded lease; Executor to Task target: Invoke with stable target idempotency key R; Executor to Run DB/outbox: Lost response -> attempt unknown; reconcile; Executor to Run DB/outbox: Replacement generation 5 fences old internal completion
Logical run survives scanner and worker crashes.
Read the diagram

Insert occurrence and run R; unique schedule/version/time; Publish R, possibly more than once; Claim generation 4 with bounded lease; Invoke with stable target idempotency key R; Lost response -> attempt unknown; reconcile; Replacement generation 5 fences old internal completion

Open original
Logical run survives scanner and worker crashes
Logical run survives scanner and worker crashes. Scanner to Run DB/outbox: Insert occurrence and run R; unique schedule/version/time; Run DB/outbox to Executor: Publish R, possibly more than once; Executor to Run DB/outbox: Claim generation 4 with bounded lease; Executor to Task target: Invoke with stable target idempotency key R; Executor to Run DB/outbox: Lost response -> attempt unknown; reconcile; Executor to Run DB/outbox: Replacement generation 5 fences old internal completion

Logical run survives scanner and worker crashes.

Define calendar behavior explicitly. For America/New_York daily 02:30, this scenario shifts a skipped spring-forward occurrence to the first valid local time after the gap, and runs a repeated fall-back local time once using the earlier offset. A daily 01:30 fall-back occurrence therefore runs once, not twice. Persist timezone database/version and resolved UTC occurrence identity. Different business policies are valid but need different test expectations; adding a fixed 24 hours loses calendar intent.

Occurrence to attempt transitions. No occurrence / Due local time resolved in schedule timezone / Unique schedule/version/UTC run plus outbox; Ready / Due and tenant has capacity / Leased generation N; append attempt N; Leased / Current worker reports success before lease expiry / Succeeded; preserve attempt evidence; Leased / Retryable failure and retry budget remains / Retry_wait at capped exponential delay with jitter; Leased / Lease expires with no final result / Attempt outcome unknown; reconcile target using stable run ID; Retry_wait / Next eligible time and attempt budget remain / Leased generation N+1; same logical run ID; Retry_wait / Maximum attempts exhausted / Dead_letter with terminal reason and attempt history
Occurrence to attempt transitions.
Read the diagram

Current state / Guard or event / Durable next state; No occurrence / Due local time resolved in schedule timezone / Unique schedule/version/UTC run plus outbox; Ready / Due and tenant has capacity / Leased generation N; append attempt N; Leased / Current worker reports success before lease expiry / Succeeded; preserve attempt evidence; Leased / Retryable failure and retry budget remains / Retry_wait at capped exponential delay with jitter; Leased / Lease expires with no final result / Attempt outcome unknown; reconcile target using stable run ID; Retry_wait / Next eligible time and attempt budget remain / Leased generation N+1; same logical run ID; Retry_wait / Maximum attempts exhausted / Dead_letter with terminal reason and attempt history

Open original
Occurrence to attempt transitions
Occurrence to attempt transitions. No occurrence / Due local time resolved in schedule timezone / Unique schedule/version/UTC run plus outbox; Ready / Due and tenant has capacity / Leased generation N; append attempt N; Leased / Current worker reports success before lease expiry / Succeeded; preserve attempt evidence; Leased / Retryable failure and retry budget remains / Retry_wait at capped exponential delay with jitter; Leased / Lease expires with no final result / Attempt outcome unknown; reconcile target using stable run ID; Retry_wait / Next eligible time and attempt budget remain / Leased generation N+1; same logical run ID; Retry_wait / Maximum attempts exhausted / Dead_letter with terminal reason and attempt history

Occurrence to attempt transitions.

The selected calendar rules resolve to concrete instants:

Daylight-saving occurrence examples. Spring gap / 2025-03-09 02:30 America/New_York / Shift to first valid local time, 03:00 EDT / 2025-03-09 07:00 UTC; one run; Fall fold / 2025-11-02 01:30 America/New_York / Choose earlier offset, EDT / 2025-11-02 05:30 UTC; one run, not two; Ordinary day / 2025-02-01 02:30 America/New_York / Use the only valid offset / 2025-02-01 07:30 UTC; one run
Daylight-saving occurrence examples.
Read the diagram

Transition / Local schedule intent / Resolution policy / Resolved occurrence; Spring gap / 2025-03-09 02:30 America/New_York / Shift to first valid local time, 03:00 EDT / 2025-03-09 07:00 UTC; one run; Fall fold / 2025-11-02 01:30 America/New_York / Choose earlier offset, EDT / 2025-11-02 05:30 UTC; one run, not two; Ordinary day / 2025-02-01 02:30 America/New_York / Use the only valid offset / 2025-02-01 07:30 UTC; one run

Open original
Daylight-saving occurrence examples
Daylight-saving occurrence examples. Spring gap / 2025-03-09 02:30 America/New_York / Shift to first valid local time, 03:00 EDT / 2025-03-09 07:00 UTC; one run; Fall fold / 2025-11-02 01:30 America/New_York / Choose earlier offset, EDT / 2025-11-02 05:30 UTC; one run, not two; Ordinary day / 2025-02-01 02:30 America/New_York / Use the only valid offset / 2025-02-01 07:30 UTC; one run

Daylight-saving occurrence examples.

Chosen scheduler calendar and editing policy. Spring gap skips 02:30 / Run at first valid local time after gap / One resolved occurrence for local date; Fall repeats 01:30 / Earlier offset only / One occurrence, not two; Outage misses 10 daily runs / Coalesce under this schedule's policy / One catch-up run with skipped count recorded; Schedule edited / New version applies only to unclaimed future occurrences / Already leased work follows explicit cancellation policy; Cancel races with external call / Revoke generation and request stop / Cannot undo a target effect already accepted
Chosen scheduler calendar and editing policy.
Read the diagram

Event / Rule / Identity/effect; Spring gap skips 02:30 / Run at first valid local time after gap / One resolved occurrence for local date; Fall repeats 01:30 / Earlier offset only / One occurrence, not two; Outage misses 10 daily runs / Coalesce under this schedule's policy / One catch-up run with skipped count recorded; Schedule edited / New version applies only to unclaimed future occurrences / Already leased work follows explicit cancellation policy; Cancel races with external call / Revoke generation and request stop / Cannot undo a target effect already accepted

Open original
Chosen scheduler calendar and editing policy
Chosen scheduler calendar and editing policy. Spring gap skips 02:30 / Run at first valid local time after gap / One resolved occurrence for local date; Fall repeats 01:30 / Earlier offset only / One occurrence, not two; Outage misses 10 daily runs / Coalesce under this schedule's policy / One catch-up run with skipped count recorded; Schedule edited / New version applies only to unclaimed future occurrences / Already leased work follows explicit cancellation policy; Cancel races with external call / Revoke generation and request stop / Cannot undo a target effect already accepted

Chosen scheduler calendar and editing policy.

A tenant fair scheduler rotates eligible tenants and caps each claim batch/concurrency. At 100,000 midnight runs and a 60-second dispatch target, capacity needs about 1,667/s, separate from task duration. Keep per-tenant eligible queues and take one item per tenant per round, carrying the last-served tenant across batches. This prevents a single tenant's backlog from filling every batch while still respecting due-time order within each tenant. A one-hour occurrence horizon is insufficient for a long outage unless materialization catches up under the declared misfire policy. For ten missed daily occurrences, this schedule coalesces to the latest one and records nine skipped instants; catch-up schedules instead dispatch only the newest configured cap and mark the rest skipped.

On lease expiry, preserve unknown attempt evidence and create a replacement only under retry policy. A target without idempotency may run twice; surface that limitation in schedule creation and operations. Monitor due lag, claim contention, attempt unknown age, per-tenant capacity and DLQ growth.

The executable reference model in examples/system-design/job_scheduler.py implements UTC occurrence identity, the selected New York DST gap/fold rule, outbox repair, fair bounded claims, overlap, edits/cancellation, lease expiry, attempt fencing, retry jitter, DLQ, and skip/coalesce/capped-catch-up decisions. Its tests exercise these boundaries; it does not implement a production recurrence parser, durable database, queue, or external task target.

Exercise: Generation 4 sent an email but lost its response. Generation 5 invokes the same run. Does fencing alone prevent a duplicate email?

Show answer and explanation

Answer: No. Fencing protects scheduler state, not an external provider. The stable target key/status reconciliation must resolve the email operation; otherwise the delivery contract includes a duplicate window.

PostgreSQL explicit locks documents the transaction primitive; calendar and target-effect policies are application choices.

Requirement trace and verification

RequirementImplementing design blockVerification link
R1 — Complete the primary user journey within the stated scope.P01–P04; P09–P10.V1 — Exercise the successful journey and the excluded/boundary case stated in the scope.
R2 — Preserve the problem's authoritative data invariant under concurrency.P05–P06; P11–P12; DD1.V2 — Run the race/replay case below and assert the invariant at the durable authority.
R3 — Meet the declared scale and API behavior without unbounded work.P05–P08; P13–P14; relevant overload deep dives.V3 — Exercise the API errors/retry identity and recompute the workload assumption that drives partition or capacity.
R4 — Recover from the named failure without losing or duplicating the user-visible outcome.P15–P16; deep dives; Operations contract.V4 — Crash before dispatch and after an external side effect, edit a due schedule, and cross a DST boundary; duplicates have defined handling.

Operational contract

AreaDecision and signals
SLIsScheduled-to-start lag; overdue occurrence age; lease churn; retry rate; tenant starvation.
Overload limitsCap materialization horizon, due scans, worker concurrency per target/tenant, and retry/dead-letter volume.
RecoveryRebuild due indexes from durable schedules/occurrences; reclaim expired leases with a higher attempt generation.
Access controlsAuthorize schedule creation/cancellation by tenant; scope target credentials and redact job payloads.
Dominant costAlways-on scheduler scans, durable run history, and target invocation volume.

Senior-level interviewer follow-ups

Question: A recurring job falls into a daylight-saving gap or repeats during a clock rollback. Which occurrence runs?

Show answer and explanation

Answer: Persist the schedule's timezone and an explicit gap/fold policy, then materialize occurrences with unique scheduled-time identities so the same local occurrence cannot run twice accidentally.

Question: What happens to thousands of overdue jobs after a regional outage?

Show answer and explanation

Answer: Apply a documented misfire policy, rate-limit catch-up by tenant and queue, and schedule with bounded concurrency. Do not enqueue the entire backlog as an unrestricted burst.

A 60-second design answer

I would persist schedules and materialize due occurrences with unique identities. Workers claim them using leases and generations, and retries use backoff plus a durable attempt history. Timezone, daylight-saving, misfire, cancellation, and target idempotency rules are explicit. I would monitor scheduler lag, overdue work, retry age, lease steals, and catch-up rate by tenant.

Managing Long Running Tasks Temporal

Technical references

Provider idempotency contract example.

PostgreSQL transaction isolation and concurrent updates.

Name schedule, occurrence and attempt separately

Schedule s7 version 3 runs at 12:00. Two dispatchers generate the same occurrence identity (s7,3,12:00); one durable occurrence o7 is created. Attempt a1 may fail and a2 retry o7 without creating a second scheduled occurrence. A schedule edit to version 4 affects applicable future occurrences under its declared boundary, not the fact that o7 already committed.

Contract / pseudocode
schedule: s7 version 3
occurrence: (s7,3,12:00) -> o7, unique
execution: o7 attempt 1 -> retry attempt 2
edit: s7 version 4 -> future policy; o7 preserved
schedule: s7 version 3; occurrence: (s7,3,12:00) -> o7, unique; execution: o7 attempt 1 -> retry attempt 2; edit: s7 version 4 -> future policy; o7 preserved
Name schedule, occurrence and attempt separately
Read the diagram

schedule: s7 version 3; occurrence: (s7,3,12:00) -> o7, unique; execution: o7 attempt 1 -> retry attempt 2; edit: s7 version 4 -> future policy; o7 preserved

Open original
Name schedule, occurrence and attempt separately
schedule: s7 version 3; occurrence: (s7,3,12:00) -> o7, unique; execution: o7 attempt 1 -> retry attempt 2; edit: s7 version 4 -> future policy; o7 preserved

Name schedule, occurrence and attempt separately

Due-time buckets/indexes locate bounded eligible work; leases/epochs fence dispatch and result publication. Recurrence time zones, daylight saving, missed runs and catch-up limits are product decisions. An at-least-once job delivery needs safe business effects; claiming exactly-once execution of arbitrary code is unjustified. Cancellation and due-time races use persisted states and declared precedence.

Show answer and explanation

Answer: A retry is not a new occurrence. An edited cron definition cannot erase an already accepted occurrence or silently recreate it under a fresh business identity.

Decision review: Job Scheduler

Job Scheduler: What it is

A scheduler materializes intended occurrences and assigns bounded execution attempts, including calendar and cancellation semantics.

Job Scheduler: Why it is needed

Due time, execution ownership and external completion are different facts; repeated delivery must not invent a second business occurrence.

Job Scheduler: When to use it

Use durable scheduling for delayed or recurring jobs. Record timezone and policy when local calendar time matters rather than assuming fixed UTC intervals.

Job Scheduler: How to use it

Give schedule revisions, occurrences and attempts separate identities. Generate each intended occurrence once under the rule, lease attempts with a newer epoch and use occurrence-derived effect identities when the destination supports them.

Job Scheduler: Compare an alternative

A periodic scan is simpler but may give coarser due-time precision. Per-occurrence timers can improve responsiveness while adding projection and reconciliation work. Compare the actual lateness and recovery requirements.

Job Scheduler: Worked decision exercise

The following inputs and policies are original exercise assumptions; they are not measurements or undisclosed company behavior.

Schedule revision 4 creates occurrence o7. Attempt 9 pauses and attempt 10 becomes current. A late attempt 9 may still call an external API, so fencing scheduler status alone does not prove the external effect ran once.

Job Scheduler: Schedule revision 4 creates occurrence o7; Attempt 9 pauses; attempt 10 acquires ownership; Status publication enforces epoch 10; External effect reuses o7 identity where supported
Job Scheduler: a concrete state and recovery trace under the exercise assumptions.
Read the diagram

Schedule revision 4 creates occurrence o7; Attempt 9 pauses; attempt 10 acquires ownership; Status publication enforces epoch 10; External effect reuses o7 identity where supported

Open original
Job Scheduler: worked example
Job Scheduler: Schedule revision 4 creates occurrence o7; Attempt 9 pauses; attempt 10 acquires ownership; Status publication enforces epoch 10; External effect reuses o7 identity where supported

Job Scheduler: a concrete state and recovery trace under the exercise assumptions.

What should happen to an occurrence when a schedule is cancelled just after dispatch?

Show answer and explanation

Answer: Define the cancellation boundary and inspect the occurrence’s state. Stop work that has not crossed the agreed boundary; reconcile already-submitted effects and report uncertainty honestly. A calendar edit must not silently relabel an old occurrence into the new revision.

Job Scheduler: Check the design

Observe due-to-start delay, oldest unresolved occurrence, lease expiry, missed/duplicate occurrence detection and calendar-policy cases such as skipped or repeated local time.

Screenshot variant: Millions of jobs with bounded lateness

Replace "exactly on time" with an agreed execution-start or dispatch lateness distribution under an admitted workload and stated failures. A due timestamp is a target, not proof of immediate execution or exactly-once external effects. Clarify whether cron uses UTC or a named local timezone, how daylight-saving gaps/repeated times behave, and whether missed occurrences are skipped, coalesced or caught up after downtime.

Separate schedule_id, occurrence_id = (schedule_id, nominal_due_at, schedule_version) and attempt_id. Store a due-time bucket plus a hash sub-shard, claim bounded windows and enqueue occurrence identities durably. A versioned schedule cancellation does not require deleting every old queued message; workers validate current eligibility before executing. Lease generations fence stale completions, and downstream effect keys deduplicate occurrences where supported.

One million jobs due in one minute require at least 16,667 starts/s on average. If each occupies a worker slot for 200 ms, roughly 3,334 concurrent slots are required before retries and headroom, assuming independent work and a steady distribution. If all one million are due at the same instant and dispatch capacity is 20,000/s, draining alone takes at least 50 seconds. Do not present a minute-wide average as proof of a one-second target.

Budget clock error, bucket scan interval, queue wait and worker admission. For a hypothetical p99 lateness target of five seconds, assign and measure a budget at each boundary; overload or dependency outages require rejection, delayed admission or a documented missed-run policy. Use a monotonic clock for elapsed leases and an authoritative wall-clock policy for nominal cron instants.

Example: worker A starts occurrence O with generation 4, pauses and loses its lease. Worker B receives generation 5 and runs O. A cannot commit a terminal result afterward. If A already invoked an external side effect, fencing the scheduler row does not prevent duplication there; O must also be the receiver's deduplication identity or the residual risk must be explicit.

Show answer and explanation

Answer: Measure due-to-enqueue, enqueue-to-start and execution duration separately, including p99.9 and oldest overdue age by tenant. Test an hour of downtime, a midnight burst, DST changes, duplicate dispatch and a paused stale worker. A recovery plan must bound catch-up work so old occurrences do not starve new schedules.

Deep dive: calendar intent becomes durable occurrences

This original scheduler distinguishes a schedule definition, one nominal occurrence and execution attempts. A daily 09:00 local schedule is not necessarily a 24-hour elapsed timer across daylight-saving transitions. Materialize eligible calendar instants with a named IANA timezone and an explicit policy, then assign stable UTC occurrence identities. Do not derive correctness from whichever API server's wall clock happens to scan first.

Contract / pseudocode
schedule(tenant, schedule_id, version, expression, timezone,
         gap_policy, fold_policy, misfire_policy, state, next_nominal_due)
occurrence(tenant, schedule_id, version, nominal_due_utc,
           state, dispatch_deadline, current_attempt_generation)
UNIQUE(tenant, schedule_id, version, nominal_due_utc)
attempt(occurrence_id, generation, owner, lease_deadline, result_evidence)

Resolve DST deliberately

For this exercise, gap_policy=skip and fold_policy=first mean a nonexistent local time generates no occurrence and a repeated local time generates only its first UTC instant. For America/New_York, 2026-03-08 02:30 is nonexistent; 2026-11-01 01:30 occurs twice, at 05:30Z and 06:30Z. The first-fold policy selects 05:30Z. A both-fold policy would create two distinct UTC occurrences. This is our product contract, not a claim that every scheduler has these options.

The resolver must validate a candidate by round-tripping local time through UTC. Simply attaching a timezone object to a nonexistent local time can manufacture a misleading instant. Pin/test timezone data and define how future materialized occurrences change when timezone rules or schedule definitions change. Previously executed occurrences retain their original identity and evidence.

Managed services have their own semantics. Check EventBridge Scheduler schedule types before mapping this exercise to cron/rate expressions. Its calendar handling, target retries and execution precision must not be inferred from this custom policy.

Materialization and publication are separate durable steps

Two scanners can both discover nominal due time D for version 7. In a supported transaction, insert the unique occurrence and its outbox publication record. The loser resolves the existing identity. A crash after insert but before queue send is recovered through the outbox. A duplicate queue delivery refers to the same occurrence, not a newly generated UUID with a new effect identity.

Partition due work by time bucket plus tenant/hash sub-shard. A single current-minute partition can become the hottest key in the system. Scan bounded windows with checkpoints and overlap sufficient for recovery; uniqueness handles rediscovered occurrences. A cursor cannot silently jump past unmaterialized times after an outage.

Make edits and cancellation explicit

An edit increments schedule version. New materialization follows the new version under an effective-time policy. Old unstarted queued occurrences become ineligible if cancellation won the authoritative start decision. Keep a tombstone/version long enough to reject stale messages. An attempt that was already authorized to start may continue according to policy; cancellation cannot recall an irreversible external call already accepted.

Scheduler race: scanner creates occurrence O at version 7; user cancels and version advances to 8; O remains queued; worker checks current eligibility; old unstarted O is suppressed without invoking its target
Cancellation wins only at the documented eligibility/start boundary, not by deleting a queue message optimistically.
Read the diagram

Scanner creates occurrence O at version 7 → Cancellation advances schedule version to 8 → Old occurrence O remains queued → Worker checks authoritative start eligibility → O is suppressed without invoking target

Open original
Job Scheduler: recovery decision
Scheduler race: scanner creates occurrence O at version 7; user cancels and version advances to 8; O remains queued; worker checks current eligibility; old unstarted O is suppressed without invoking its target

Cancellation wins only at the documented eligibility/start boundary, not by deleting a queue message optimistically.

A source schedule row and occurrence row on different stores need an authority protocol for this decision; an eventually consistent version lookup can allow obsolete work. State the allowed cancellation lag or route the start claim through the authoritative boundary. After starting, leases and fencing prevent an obsolete attempt from publishing local completion. Receiver-side idempotency keyed by occurrence handles repeated external effects where supported.

Choose one downtime policy

Assume a minute schedule misses 10:00 through 10:59 while the service is down. At 11:00, this exercise treats 11:00 as fresh work and applies one selected policy to the 60 missed instants:

PolicyRecovery workIdentity and user consequence
SkipNo old executionsRecord skipped occurrences/range under audit policy; start fresh work
CoalesceOne catch-up for 10:59Preserve the chosen nominal occurrence and report what was coalesced
Catch upUp to all 60 old occurrences, bounded by maximum age/countEach original nominal instant retains its own identity

A billing job cannot casually coalesce sixty required postings as if it were a refresh job. Choose by business meaning. Catch-up traffic has its own rate/concurrency share so overdue history cannot starve new schedules. Pausing a schedule must specify whether resume applies skip, coalesce or catch-up, and whether already running attempts are affected.

Budget the synchronized burst

One million simultaneous due occurrences and capacity of 20,000 starts/s imply at least 50 seconds to start them all, even before scanning, queueing or target delay. A one-second start promise is impossible at that capacity. Spreading due instants across a minute changes the workload; it is not evidence that the simultaneous case meets its target.

For an admitted five-second dispatch objective, an illustrative budget might allocate 0.5 s clock/scan allowance, 0.5 s materialization/publication, 2 s queueing/admission, 1 s worker claim and 1 s margin. These are design allocations, not independent percentile values that can simply be added to prove p99. Measure end-to-end distributions and correlated failures. Targets with side effects have their own service deadlines; dispatch success is not business completion.

Track due-to-materialize, materialize-to-enqueue, enqueue-to-start and execution duration separately. Alert on oldest overdue work and lateness by tenant/priority. A failed target retry exhausted into a DLQ must remain visible as failed/repairable; the scheduler cannot label it successfully executed merely because it sent a request once.

Scheduler assessment: define one occurrence precisely

Question: A 01:30 local cron crosses a repeated hour. Does using only local date/time as identity suffice for a both-fold policy?

Show answer and explanation

Answer: No. The two eligible UTC instants must remain distinct. With first-fold policy, select one explicitly. Version and timezone policy belong to the schedule definition.

Question: An hour of minute occurrences was missed. May recovery create one fresh UUID and claim all were executed?

Show answer and explanation

Answer: No. Coalescing must be a declared business policy with evidence of the skipped/coalesced range. Catch-up preserves each original occurrence identity; skip records the chosen non-execution outcome.

Question: Cancellation committed before O's authoritative start claim, but O is already in a queue. Must the target be invoked?

Show answer and explanation

Answer: No under this contract. The start decision checks current eligibility and suppresses the old unstarted occurrence. If the start decision won first, cancellation follows the stated running-work policy instead.

Score one point for DST semantics, unique nominal occurrence, durable materialize/publish boundary, version-aware start/cancel rule and bounded misfire recovery. Then change the prompt to one million simultaneous starts and defend the revised lateness objective or capacity.

Prerequisites: Reliability and Overload Control, Consensus, Leader Election and Fencing and Outbox, Inbox, Sagas and Reconciliation.

Shared foundation: Time, Ordering and Identifiers

Time, Ordering and Identifiers: Choose clock and identity semantics, trace causal ordering and preserve identifier uniqueness across rollback and restart. Work its failure history before extending this design.

26:00Self-guided practice timer
The timer resets when you leave this page. Save your design separately.
Your challenge

The scheduler publishes a due run and crashes before updating its row. How should recovery behave?

Your design draft

Clarify assumptions, explain your approach, and test the difficult cases. Save your draft, then compare it with the study notes.

Read study notes

Self-review checklist

Self-guided practice. Automated AI feedback and code execution are not connected.