All posts
System Design Mastermind · Part 19
  • System design
  • Distributed systems
  • Interview prep
  • Platform

Distributed job scheduler system design: on time, at least once, never lost

How to design a distributed job scheduler (cron at scale) in real interview order: the numbers and the top-of-the-hour peak, the job and run API with time zones, sharded schedulers with leases, one run end to end, the claim query with a unique run key, a lab on the top-of-the-hour herd, a lab on leases, heartbeats and retries, and what happens when each part fails.

23 Oct 2026 · 32 min read · interactive

Share

The 1-minute answer

Split it in two: scheduling decides when, a queue decides who. Jobs live in a sharded relational store with a precomputed next_run_at (UTC, from the cron expression and IANA time zone) and an index on it. Each scheduler instance owns some shards through a lease and, every second, claims due jobs in one transaction: insert a run whose id is job_id + scheduled time (a unique key, so nothing can create it twice), and advance next_run_at. Runs go onto a durable queue with a deliver-at time, enqueued a little early so polling never makes them late. Workers pull a run, hold a lease extended by heartbeats, call the target with the run id as an idempotency key, record the result, then ack. A dead worker's lease expires and the run is retried with exponential backoff and jitter; after the last attempt it goes to a dead-letter queue. That's at-least-once, made safe by idempotency. The top of the hour is the real load: spread it with jitter where jobs allow, stage it ahead where they don't, and keep tenants from starving each other.

How this page follows the interview

Each phase is a section below, in the order you'd present it. Click a phase for what to say, what to write, and the trap.

✅ Seen: a company or official doc said so (cited)🔶 Inferred❓ Unknown: state it as an assumption🧭 Interview choice

Requirements and numbers

Agree what a job is, how on time it must be and what "once" means, then size it. Change any input: each number comes with the decision it forces, and those decisions come back in the design and deep-dive sections.

Functional

  • Create one-off ("run at 15:00") and recurring (cron) jobs, with a time zone
  • Run each job's target when due: an HTTP call, a queue message, a container
  • Retries with backoff; a dead-letter queue for runs that keep failing
  • Pause, trigger now, backfill; see every run's status and error
  • Per-job policies: what to do on overlap and after missed fires

Non-functional

  • On time: 95% of runs start within 5 s of their due time
  • Never lose an accepted job; every due fire runs at least once
  • No run created twice; repeats of execution rare and harmless
  • Scales to ~10,000 runs/s and survives the top-of-the-hour peak
  • One tenant can't make another late

Out of scope (say it)

Workflows with dependencies (Airflow DAGs, Temporal workflows), the job's own code, and placing containers on machines (that's Kubernetes' pod scheduler, a different problem).

Capacity calculator

Every input is an assumption 🔶: say it out loud. For scale: Dropbox's ATF was built for 10,000 tasks/s and ran 9,000; Slack's job queue peaked at 33,000 jobs/s. ✅ Dropbox 2020 · Slack

Three rules for this estimate
  1. A day is 86,400 seconds. Runs per day ÷ 86,400 = the average rate.
  2. The average lies. People pick round times; the second at :00 can be hundreds of times busier than an average second.
  3. Little's law for workers. Runs in flight = runs per second × seconds per run.
They'll push on thisAnswer out loud, then open.

Core entities and the API

A job is a schedule plus a target; a run is one fire of it. What they listen for: time zones, an Idempotency-Key on create, run history, and the worker's claim / heartbeat / finish protocol.

EntityKey fieldsNote
Request
Response

Missed fires and overlaps: what actually runs?

Two fields on every job decide behaviour nobody thinks about until it bites: what to do with fires missed during an outage (catch-up), and what to do when a run is still going at the next fire (overlap). Change the numbers and the policies.

Catch-up
Overlap

Where these policies come from

  • Overlap: Kubernetes CronJob has Allow (the default), Forbid and Replace. Temporal has Skip (its default), BufferOne, BufferAll, CancelOther, TerminateOther and AllowAll. ✅ K8s · Temporal docs
  • Catch-up: Kubernetes won't start a CronJob after more than 100 missed schedules, and startingDeadlineSeconds limits how late a start may be. Temporal's catch-up window defaults to one year. ✅ K8s · Temporal docs
  • Defaults I'd pick: overlap = skip, catch-up = latest. Billing-like jobs opt in to "all". 🧭

Replace with a run longer than the interval is a trap: every run is cancelled before it finishes.

They'll push on thisAnswer out loud, then open.

High-level design

Build it in passes and say why each box exists. Click any box to see what it does, what it owns, what's inside it and what you'd watch.

They'll push on thisAnswer out loud, then open.

Walk one run, box by box

From creating a job, through a claim, a lease and a success, to a dead worker, a failing target and a frozen scheduler. Each step lights up the path and shows what goes over the wire, what's stored and how long it takes.

On the wire

Arrows show who calls whom, and the numbers give the order. Replies go back along the same line.

How "at least once" becomes "effectively once"

No design can promise a job's code runs exactly once: a worker can die after the work and before it reports. What you can promise is that every guard below turns a repeat into a no-op.

    Data and database choices

    "How do you find what's due?" is guaranteed. Jobs need durability, a range query on time and a transaction; runs in flight need leases and speed; history needs to age out.

    DataPickConsideredWhy not those

    The one query to know

    -- every second, for each shard this scheduler owns
    BEGIN;
    -- 1. lock due jobs; skip rows another claimer holds
    SELECT job_id, next_run_at, schedule, timezone
      FROM jobs
     WHERE shard_id = $shard AND enabled
       AND next_run_at <= now() + interval '30 seconds'
     ORDER BY next_run_at
     LIMIT 500
     FOR UPDATE SKIP LOCKED;
    
    -- 2. create each run once (unique key), with our token
    INSERT INTO runs (job_id, scheduled_at, state, fence)
    VALUES ($job_id, $next_run_at, 'scheduled', $fence)
    ON CONFLICT (job_id, scheduled_at) DO NOTHING;
    
    -- 3. advance the job (next fire computed in the app,
    --    in the job's time zone, stored in UTC)
    UPDATE jobs SET next_run_at = $next_fire, last_fence = $fence
     WHERE job_id = $job_id AND last_fence <= $fence;
    COMMIT;
    -- then publish each new run with deliver_at = scheduled_at

    Airflow runs several schedulers on exactly this kind of row locking. ✅ Airflow docs

    Why one transaction

    1. The unique key makes "create the run" idempotent. A handover race, a retried transaction or a catch-up all try the same (job_id, scheduled_at); one row wins. Google's cron puts the launch time in job names for the same reason. ✅ Google SRE
    2. Advance next_run_at in the same commit. A crash between "insert run" and "advance" would otherwise fire the job twice or skip it. 🧭
    3. SKIP LOCKED, not waiting. Two claimers on one shard take different rows instead of blocking. ✅ Airflow docs
    4. Fencing. The update only lands if the job's last token is not newer than ours, so a scheduler whose lease moved on can't advance anything. 🧭

    More database questions

    They'll push on thisAnswer out loud, then open.

    Deep dive: the top-of-the-hour herd

    People pick round times, so a big share of runs come due in the same second. Two things can make them late: dispatch (claiming and enqueueing them) and workers (free slots to start them). The chart shows, over time, how many runs are due, enqueued and started. Pick a preset, then change the numbers.

    Dashed: due. Apricot: enqueued (held until due). Teal: started. A gap between dashed and teal is lateness. Exact for identical slots and equal run times; teaching numbers. 🧭

    Three levers, in order

    1. Enqueue ahead. Claim runs 30–60 s early and let the queue release them on time. Hides the poll and the dispatch. ✅ FOQS deliver_after
    2. Spread what can move. Google's cron added "?" so the system picks a value by hashing the job; EventBridge Scheduler offers a flexible window that "disperses" invocations. ✅ Google SRE · AWS
    3. Headroom for what can't. Scale workers before :00, give strict jobs a priority queue, and keep them short (enqueue the email, don't send it in the job). 🧭

    What real systems say

    Google: thousands of MapReduce workers started at midnight by 30 teams caused large spikes; hashing "?" values spread them, but spikes still happen for jobs tied to external events. ✅ SRE book

    Temporal: actions generally start within 1 second, "unless many Schedules fire simultaneously". ✅ docs

    EventBridge Scheduler: 60-second precision without a flexible window. ✅ docs

    They'll push on thisAnswer out loud, then open.

    Deep dive: leases, retries and duplicates

    A worker that takes a run might crash, stall, or just be slow, and nobody can tell which from outside. The lease decides how fast a crashed run is retried and how often a slow run is duplicated. Retries decide what survives a broken target. Pick a preset, then change the numbers.

    WhatPer day / valueHow

    Run times follow a log-normal fitted to your median and p99. "Interruptions" are crashes, deploys and spot reclaims; half of interrupted runs are assumed to have done their side effect already. Retries ignore jitter in the span. Closed-form teaching numbers. 🧭

    The rules this lab teaches

    1. Short lease + heartbeat beats a long lease. SQS's advice: start short and "implement a heartbeat mechanism to periodically extend" it. ✅ AWS docs
    2. At least three heartbeats per lease, so one late heartbeat doesn't hand the run away. Dropbox ATF's executors stop after three consecutive failed heartbeats. ✅ Dropbox 2020
    3. Retries should outlast a typical outage: exponential backoff with jitter, then a DLQ. 🧭
    4. Crashes always cause some repeats. Only an idempotent job makes them harmless. ✅ Dropbox · SQS

    Real numbers to quote

    SQS: visibility timeout defaults to 30 s and can't go past 12 hours from first receipt; duplicates are still possible. ✅ AWS docs

    EventBridge Scheduler: retry policy up to 185 retries and 24 hours of event age, then a DLQ. ✅ AWS docs

    FOQS: an item not acked or nacked within its lease is redelivered (at-least-once). ✅ Meta 2021

    They'll push on thisAnswer out loud, then open.

    A run's lifecycle

    Every run is a small state machine stored in its row. Click events to move it; ones that can't happen from the current state are disabled. Each event shows what fires across the system.

    NormalSomething went wrongGreyed out: not possible from the current state.

    Edge cases interviewers love

    They'll push on thisAnswer out loud, then open.

    Failure, monitoring and recovery

    A scheduler's failures show up as runs that are late, missing or doubled. Click a box to take it down: red is the failed part, amber is its blast radius. Each answer covers impact, degraded mode, the alert, automatic and manual recovery, and how you'd trace it.

    Tracing it back: a normal run vs a worker lost mid-run

    Every span carries the job id and run id. Times are seconds from the run's due time. In the bad trace the worker disappears at 12 s, nobody notices until the lease runs out, and attempt 2 starts 72 s late with the same idempotency key.

    How one failure becomes three

    What you'd alert on (SLOs)

    SignalTargetAlert

    Incident playbook

      The resilience toolkit

      Name the pattern, then say where it goes in this design.

      They'll push on thisAnswer out loud, then open.

      Making it fast, and who owns what

      The scheduler's own work is milliseconds; waiting is what makes runs late: the poll, the queue behind a burst, and a cold start. Bars are sizing estimates, not measured figures.

      TeamOwnsPaged when…

      Senior follow-ups beyond the happy path

      Interviewers pick from these themes once the design is on the board. Have one concrete answer per theme, tied to this design.

      Practice ladder

      Real interviews go level by level. Answer out loud before opening each one. Levels 6–7 are where Senior becomes Staff.

      Sources

      Company sources date from 2015 to 2021 (Google SRE book, Slack, Dropbox, Meta); product docs (Kubernetes, Temporal, EventBridge Scheduler, SQS, Airflow) were checked in October 2026. Current internals at these companies may differ, and the lab numbers are teaching estimates. In an interview, say so.

      System Design Mastermind · Platform & Infra

      Series home

      All of Platform & Infra

      5 published · 7 comingWhat Senior platform loops lean on.

      19

      Distributed job scheduler system design: on time, at least once, never lost

      Jobs in a sharded store with a precomputed next_run_at → one scheduler per shard (lease + fencing token) claims due jobs every second: insert run (unique job_id + time) and advance next_run_at in one transaction → durable queue with deliver-at, enqueued a little early → workers lease runs, heartbeat, call the target with the run id as idempotency key → backoff, then a DLQ. At-least-once, made safe by idempotency.

      You're reading this Preview
      24

      Metrics and logging system design (Datadog-style): series, roll-ups and alerts you can trust

      Agents add up metrics for 10 s and batch them with logs → intake checks key and quotas, appends to a durable log, then 202 → writers map tags to series ids in an inverted index and store compressed points with roll-ups → logs: index a slice, archive all → monitors evaluate a window that ends in the past, and the whole stack is watched from outside.

      32 min · interactive Preview
      27

      Kafka system design: a distributed log that never loses an acknowledged message

      Topics split into partitions; the producer hashes the key, batches and sends to the partition leader → the leader appends to the page cache, followers in other zones pull, acks=all waits for every in-sync copy (RF 3, min ISR 2) → consumer groups pull from offsets and commit them → KRaft controllers move leaders; tiered storage keeps history.

      33 min · interactive Preview
      30

      Ad click aggregator system design: exactly-once counts, late clicks and hot ads

      Signed click URL → click service appends to Kafka and 302s → Flink dedupes by click id, counts per ad in 1-minute event-time windows, upserts (ad, minute) rows into an OLAP store → a per-click counter paces budgets → a nightly recount from raw clicks is what billing reads.

      32 min · interactive Preview
      33

      Payment system design (Stripe): idempotency, unknown outcomes, the ledger and reconciliation

      Card → vault → token; confirm with an Idempotency-Key → attempt row written before the bank call → gateway with timeouts and breakers → result + outbox in one commit → event log → append-only double-entry ledger and signed webhooks → a timeout is 'unknown', resolved by status check and the next day's settlement file → payouts from balances.

      33 min · interactive Preview
      ··

      Web crawler

      Coming next
      ··

      File sync (Dropbox)

      Coming next

      More posts