Skip to content

    System Design

    Case Study: Distributed Job Scheduler

    Design a multi-tenant job scheduler: fires as unique run rows, leases and fencing for workers, missed-fire and concurrency policies, retries, failover and DST.

    By Published 22 min read

    Share

    What you'll learn: By the end of this lesson you will be able to (1) design a scheduler service that fires millions of jobs on time with no single point of failure, (2) turn each scheduled fire into a uniquely keyed run so that duplicate dispatchers cannot cause duplicate work, (3) claim, lease, heartbeat and fence workers, (4) choose missed-fire, concurrency and retry policies per job, and (5) reason about failover time, spikes at round hours and daylight-saving changes.

    A railway timetable says that the 08:15 to the coast departs at 08:15. Two things make the timetable work in practice. Every departure has a number made of the route and the time, and the track controller refuses to release a second train under a number already released. And a driver who falls ill mid-route does not stop the railway: the controller notices the silence, sends a replacement and tells the signals to ignore the first driver if they ever appear again.

    A distributed job scheduler is that controller. It does not run your code. It decides when a run exists, who may execute it, and what happens when anyone goes silent. Background jobs and schedulers covers what one scheduler inside one application can and cannot promise. This lesson scales the same ideas to a shared service with many tenants and many machines.

    This is an educational reference design, not the verified internal architecture of any company. No company is named, and every number is an illustrative assumption. It assumes the case-study template, distributed locks and fencing tokens and consensus and leader election.

    The core idea

    Turn time into data. When a job becomes due, the scheduler does not "call the job". It writes a run row whose key is deterministic: the job id plus the scheduled time. Everything after that is ordinary, restartable work on rows.

    Two consequences carry the design:

    1. Safety comes from the data, liveness from the coordination. Many dispatchers may notice the same due job, and the unique key lets exactly one insert succeed. Leader election or partition ownership only decides who does the scanning, which is a performance and latency choice. If ownership is briefly wrong, nothing breaks.
    2. Exactly-once execution is not on offer; at-least-once with a fence is. A worker can be slow, paused or partitioned while another takes over. The system narrows duplication to a bounded window and gives the job the run id and an attempt number to defend itself.

    Three illustrations run through the lesson:

    • Minimal example: one job on a ten-minute schedule, observed by three dispatchers that all see it as due.
    • Realistic example: ShopStream's nightly stock reconciliation and 15-minute price sync across its stores.
    • Failure example: a worker paused for 40 seconds past its lease, so its replacement and the original both finish the same run.

    Requirements and scope

    Functional:

    • Register a job with a schedule (cron expression and time zone, fixed interval, one-off time or delay), a target (a queue topic or an HTTP callback) and a payload.
    • Fire at the scheduled time, hand the run to a worker, record the outcome.
    • Per-job policies: what to do about missed fires, what to do when the previous run is still active, retry limits and backoff, timeout.
    • Pause, resume, trigger now, and view run history.
    • Multi-tenant: one tenant's burst must not starve another.

    Non-functional (assumptions):

    • Lateness: 99% of runs start within 5 seconds of the scheduled time, and 99.9% within 30 seconds (the SLI is start time minus scheduled time).
    • No silent loss: a fire is either run, or recorded as skipped with a reason.
    • At-least-once delivery to the job, with a run id and attempt number for deduplication and fencing.
    • High availability: losing any one machine, or one zone, delays work by seconds rather than stopping it.

    Out of scope: multi-step workflows with dependencies (a workflow engine, as argued in Temporal vs Spring Batch), placing containers on machines (a different "scheduler"), and the internals of what a job does.

    Back-of-envelope estimate

    All numbers are illustrative assumptions.

    Quantity Assumption Result
    Registered jobs 10 million, averaging one fire per hour 10,000,000 / 3,600 = about 2,778 fires per second
    Round-hour spike 20% of jobs are set for the top of an hour, dispatched over 60 seconds 2,000,000 / 60 = about 33,333 fires per second, 12 times the average
    Run rows 10 million jobs x 24 fires 240 million rows per day
    Row size 300 bytes with keys 72 GB per day; 7 days of history is about 504 GB before indexes
    Concurrent runs Average run lasts 2 seconds about 5,556 on average; about 66,667 during the spike
    Heartbeats 30-second lease, heartbeat every 10 seconds about 556 heartbeats per second at average load
    Dispatch partitions 256 about 39,000 jobs per partition

    The spike is the number that sizes the system, not the average. Round hours are popular because humans pick them, so any scheduler that treats "every job is independent and uniformly spread" as true will fall over at 00:00. The Google SRE chapter on distributed cron names this thundering herd and describes a crontab ? wildcard that lets the system choose a value, by hashing the job configuration over the allowed range, so that launches spread out. We borrow the idea as an optional per-job spread window.

    API design

    POST /v1/jobs
    {
      "tenant": "shopstream",
      "name": "store-stock-reconcile",
      "schedule": { "cron": "0 2 * * *", "timeZone": "Europe/London", "spreadSeconds": 600 },
      "target": { "type": "queue", "topic": "stock.reconcile" },
      "payload": { "storeId": "s_1042" },
      "policy": {
        "misfire": "fire-once",            // fire-once | fire-all | skip
        "maxCatchUp": 5,
        "concurrency": "forbid",           // allow | forbid | replace
        "retry": { "maxAttempts": 5, "baseDelayMs": 5000, "maxDelayMs": 300000 },
        "timeoutMs": 600000
      }
    }
    
    POST /v1/jobs/{id}/pause | /resume | /trigger
    GET  /v1/jobs/{id}/runs?from=...&state=...
    
    # What a target receives for each run
    { "runId": "j_88:2026-12-03T02:00:00Z", "attempt": 2, "scheduledFor": "...", "payload": { ... } }

    The run id is the job id plus the scheduled time, so it is the same on every attempt and on every dispatcher. attempt increases each time the run is handed to a worker, and doubles as a fencing token. The target should use runId as an idempotency key; see idempotency keys and safe retries.

    Data model

    Three tables carry all the state. Names are illustrative. The SQL is a sketch in PostgreSQL syntax and is not run here.

    CREATE TABLE job (
      job_id         uuid PRIMARY KEY,
      tenant_id      text NOT NULL,
      partition_id   int  NOT NULL,           -- hash(job_id) mod 256
      schedule       text NOT NULL,
      time_zone      text NOT NULL,
      next_fire_at   timestamptz NOT NULL,    -- UTC instant of the next fire
      misfire_policy text NOT NULL,
      concurrency    text NOT NULL,
      paused         boolean NOT NULL DEFAULT false
    );
    CREATE INDEX job_due ON job (partition_id, next_fire_at) WHERE NOT paused;
    
    CREATE TABLE job_run (
      job_id        uuid NOT NULL,
      scheduled_for timestamptz NOT NULL,
      state         text NOT NULL,            -- READY RUNNING SUCCEEDED SKIPPED PARKED
      attempt       int  NOT NULL DEFAULT 0,
      run_at        timestamptz NOT NULL,     -- earliest time a worker may claim it
      lease_owner   text,
      lease_until   timestamptz,
      PRIMARY KEY (job_id, scheduled_for)     -- the deterministic run id
    );
    CREATE INDEX run_ready ON job_run (run_at) WHERE state = 'READY';
    
    CREATE TABLE partition_lease (
      partition_id int PRIMARY KEY,
      owner        text NOT NULL,
      lease_until  timestamptz NOT NULL
    );

    The partial index job_due keeps the due scan a small range read. The partial index run_ready keeps worker claims off the large, mostly finished history. At 72 GB of runs per day the history belongs in partitions by time (table partitioning) so that old data is dropped, not deleted row by row.

    High-level design

    Distributed job scheduler high-level designScheduler API to Job table (write); Dispatchers to Job table (scan due); Partition leases to Dispatchers (ownership); Dispatchers to Run table (insert run); Workers to Run table (claim); Workers to Job targets (invoke); Workers to Parked runs (give up)Scheduler API: register, pauseScheduler APIregister, pauseJob table: next_fire_atJob tablenext_fire_atDispatchers: scan due jobsDispatchersscan due jobsPartition leases: who scans whatPartitionleaseswho scans whatRun table: unique run idRun tableunique run idWorkers: claim, heartbeatWorkersclaim, heartbeatJob targets: idempotent codeJob targetsidempotent codeParked runs: after max attemptsParked runsafter maxattemptswritescan dueownershipinsert runclaiminvokegive up

    Figure 1. The scheduler's parts. How to read this: the job table says when, the run table says what exists, and workers consume the run table. Dispatchers are the only writers of new runs, and they are interchangeable because the run table rejects duplicates.

    The store can be a replicated relational database, or a key-value store with conditional writes and a secondary index on time. What it must offer is: a unique key, an atomic conditional update, an index on due time, and a way to skip rows another worker holds. PostgreSQL's FOR UPDATE SKIP LOCKED is one way, and the documentation says skipped rows give an inconsistent view of the data, so it is not suitable for general-purpose work but can avoid lock contention between several consumers of a queue-like table. That describes the run table exactly.

    sequenceDiagram accTitle: From due job to finished run accDescr: A dispatcher inserts a uniquely keyed run and advances the job's next fire time in one transaction, a worker claims the run with a lease, heartbeats while working, and records completion only if its attempt number is still current. participant D as Dispatcher participant J as Job table participant R as Run table participant W as Worker participant T as Target D->>J: read jobs due in this partition D->>R: insert run (job, scheduled_for) if absent D->>J: advance next_fire_at to the next slot W->>R: claim ready run, set lease, attempt + 1 W->>T: invoke with runId and attempt W->>R: heartbeat extends lease_until T-->>W: result W->>R: complete where attempt matches

    Figure 2. One run. How to read this: the dispatcher's two writes happen in one transaction. The worker's completion is conditional on the attempt number it was given, which is what lets a newer attempt win.

    Deep dive 1: turning time into runs

    Each dispatcher repeats a loop for each partition it covers, about once a second:

    1. Select jobs in the partition whose next_fire_at is at or before the database's current time, up to a batch limit, using the job_due index.
    2. For each, in one transaction, insert the run and advance the job.
    3. Commit.
    INSERT INTO job_run (job_id, scheduled_for, state, run_at)
    VALUES ($1, $2, 'READY', $2)
    ON CONFLICT (job_id, scheduled_for) DO NOTHING;
    
    UPDATE job SET next_fire_at = $3
    WHERE job_id = $1 AND next_fire_at = $2;

    The PostgreSQL documentation describes ON CONFLICT DO NOTHING as an alternative action to raising a unique violation error that simply avoids inserting the row. That gives the safety property: if two dispatchers race, one insert wins, the other does nothing. The guarded UPDATE makes the advance equally harmless to repeat: only the dispatcher that still sees the old next_fire_at moves it. If a dispatcher dies between the two statements, the transaction rolls back and the next scan starts the job again from the same point.

    This is the same idea the Google SRE chapter on distributed cron describes for recovering from a partially completed launch: precompute names that include the scheduled launch time, then look up which exist and launch the missing ones. Its production design records each launch start and finish through a Paxos-replicated log held by a single leader. Our design relies on the unique key instead of a single leader, which removes a bottleneck and a failover pause, at the price of one conditional write per fire.

    Which clock? Dispatchers compare against the database's now(), not each machine's clock. The Quartz documentation for clustered schedulers says the clocks of the nodes must be within a second of each other and warns against running clusters on separate machines unless clocks are synchronised. A design that reads time from one place, the store, avoids that dependency for the due decision. Worker lease checks use the same source.

    Computing the next fire. The job stores a UTC instant, but the schedule is a cron expression in a named time zone. After each fire the dispatcher evaluates the expression in that zone and converts the result to UTC. Kubernetes' CronJob has a timeZone field for the same reason, and its documentation says that putting CRON_TZ or TZ inside the schedule string is not supported. Local time creates two awkward days a year in zones with daylight saving. When clocks move forward, a local time such as 02:30 does not exist. When they move back, one occurs twice. The rule must be explicit and per job: for a missing time, fire once at the first valid instant after it; for a repeated time, fire once, at the first occurrence. Without a stated rule, jobs silently skip or double-fire on those days.

    Spreading the herd. With the optional spreadSeconds, the dispatcher adds hash(job_id) mod spreadSeconds to the nominal time. The lateness SLI is measured against the spread time, so the tenant chooses between "exactly on the hour" and "somewhere in the next ten minutes, with a lighter bill".

    Who scans? With 256 partitions and a dozen dispatchers, each dispatcher holds a lease on about 20 partitions and scans only those. The lease lives in partition_lease or in a coordination service. It reduces redundant scanning. It is not what prevents duplicates, so it needs no fencing for correctness, which makes failover simple.

    flowchart TD accTitle: What the dispatcher does with a due job accDescr: When a job is due the dispatcher checks how late it is and applies the misfire policy, then checks for an active previous run and applies the concurrency policy, then inserts the run or records a skip. A["Job due: next_fire_at reached"] --> B{"Later than the allowed lateness?"} B -- no --> D B -- yes --> C{"Misfire policy"} C -- skip --> S1["Insert run as SKIPPED with reason, advance"] C -- fire-once --> D C -- fire-all --> D2["Insert one run per missed slot, up to maxCatchUp"] D2 --> D D{"Previous run still active?"} D -- no --> E["Insert READY run"] D -- yes --> F{"Concurrency policy"} F -- allow --> E F -- forbid --> S2["Insert run as SKIPPED with reason"] F -- replace --> G["Cancel active run, insert READY run"] E --> H["Advance next_fire_at"] S1 --> H S2 --> H G --> H

    Figure 3. The policy decisions. How to read this: the two questions, "am I late?" and "is the last one still running?", are answered before a run is created. A skip is written as a row with a reason, so it shows up in history and alerts instead of vanishing.

    Deep dive 2: missed fires and overlapping runs

    These two policies decide most of what users experience, and the existing systems agree that they are choices, not constants.

    Missed fires occur when the scheduler was down, or too busy to start a run. Quartz defines a misfire as a persistent trigger that misses its firing time, for example because the scheduler was shut down or no thread was free, and on start it updates misfired triggers by each trigger's misfire instruction, with a "smart policy" default whose behaviour depends on the trigger type. Kubernetes' CronJob offers startingDeadlineSeconds, which is a deadline for starting a Job that missed its scheduled time; after it passes, that instance is skipped. It also describes a counting rule: with more than 100 missed schedules it records a warning event and still starts a Job for the most recent missed schedule, never for the earlier ones.

    Policy Meaning Good for Dangerous for
    skip Ignore the missed slots, resume at the next A refresh whose next run covers the gap Jobs where each slot has distinct meaning
    fire-once One catch-up run now, regardless of how many slots were missed Reconciliations and syncs that process "everything since last time" Jobs that must run for each period separately
    fire-all One run per missed slot, oldest first, up to maxCatchUp Per-period reports A long outage that releases a flood; the cap bounds it

    Overlapping runs occur when a run outlasts its interval. Kubernetes names three behaviours: Allow lets runs overlap, Forbid skips the new run if the previous is unfinished, and Replace replaces the running one with a new one. Implementing forbid needs a check for a READY or RUNNING run of the same job at dispatch time. That check is a read followed by a write, so for strict "never concurrent" semantics the worker's claim must also refuse a run when another run of the job is active, for example through a per-job active-run marker updated in the same transaction. Without it, a race can let two overlapping runs through. Say so in the contract.

    The Google SRE chapter states the underlying trade-off plainly: some jobs are idempotent and safe to repeat, while others, such as a newsletter send, must not run twice; some tolerate a skipped run and others, such as monthly payroll, cannot. It says the team favours skipping a launch over risking a double launch, as far as the infrastructure allows. A shared scheduler should therefore make the choice a declared property of the job rather than a global default.

    Deep dive 3: workers, leases and fencing

    A worker claims runs with a short transaction:

    WITH picked AS (
      SELECT job_id, scheduled_for FROM job_run
      WHERE state = 'READY' AND run_at <= now()
      ORDER BY run_at
      LIMIT 50
      FOR UPDATE SKIP LOCKED
    )
    UPDATE job_run r
    SET state = 'RUNNING', attempt = r.attempt + 1,
        lease_owner = $1, lease_until = now() + interval '30 seconds'
    FROM picked p
    WHERE r.job_id = p.job_id AND r.scheduled_for = p.scheduled_for
    RETURNING r.job_id, r.scheduled_for, r.attempt;

    The worker invokes the target, and a background thread heartbeats by moving lease_until forward (only WHERE lease_owner = $1 AND attempt = $2). A reaper sweeps for RUNNING rows whose lease_until has passed and sets them back to READY so the next claim increments attempt.

    The hard case is the original worker that was not dead, only slow. The Kleppmann article on distributed locking describes exactly this: a client acquires a lock, is paused for a long time, the lease expires, another client acquires the lock, and the first client resumes without noticing, then makes an unsafe change. His remedy is a fencing token, a number that increases each time the lock is granted, which the storage server checks so that a write with an older token is refused. In this design the token is attempt:

    • The completion write is UPDATE ... WHERE attempt = $n AND lease_owner = $me, so a stale worker cannot mark the run finished or release it.
    • The target receives runId and attempt. Targets that write to a shared store should record the highest attempt seen per run and reject lower ones. Targets that cannot do so must be idempotent on runId.
    stateDiagram-v2 accTitle: Life cycle of a run accDescr: A run starts READY, becomes RUNNING when claimed, and ends SUCCEEDED, or returns to READY on a retry or an expired lease, or is parked after too many attempts, or recorded as SKIPPED by policy. [*] --> READY: dispatcher inserts [*] --> SKIPPED: policy skip READY --> RUNNING: worker claims, attempt + 1 RUNNING --> SUCCEEDED: completion with current attempt RUNNING --> READY: failure, run_at = now + backoff RUNNING --> READY: lease expired, reaper RUNNING --> PARKED: attempts exhausted PARKED --> READY: manual redrive SUCCEEDED --> [*] SKIPPED --> [*]

    Figure 4. A run's states. How to read this: two different edges lead from RUNNING back to READY. One is a reported failure with a backoff delay, the other is silence detected by the reaper. Both raise attempt on the next claim, which is what invalidates the previous holder.

    Lease sizing. The lease must exceed the longest expected pause and the heartbeat interval with margin, and it sets the time to notice a dead worker. A 30-second lease and a 10-second heartbeat tolerate two missed heartbeats. Shorter leases recover faster and cause more false takeovers. For jobs that cannot heartbeat, set a lease equal to the job's timeout.

    At-least-once, in numbers. A duplicate execution needs a pause or partition longer than the 30-second lease. That is rare, but across 240 million runs per day "rare" is not zero, so the fence and the idempotent body are mandatory.

    Deep dive 4: retries, parking and fairness

    Retries. A failed attempt moves the run to READY with run_at in the future, using exponential backoff with jitter (timeouts, retries, backoff and jitter). The target's response should classify the failure: retryable (timeout, 503), non-retryable (validation failure), or "retry after N seconds" (a throttling response). Non-retryable failures go straight to parking, since another attempt cannot succeed.

    Parking. After maxAttempts the run enters PARKED, with the last error and attempt history stored, and an alert fires per job, not per run, to avoid a page storm. Redrive is a deliberate action (dead-letter queues and retries).

    Fairness. In a shared service one tenant registering a million jobs at 00:00 must not starve the others. Controls, from cheapest:

    • A per-tenant concurrency cap, enforced at claim time by counting that tenant's RUNNING rows.
    • Claims that round-robin across tenants rather than taking the oldest run_at globally.
    • A per-tenant dispatch budget per second, with excess runs staying READY but with a later run_at.
    • Priority classes for system jobs such as expiring leases, kept in a separate worker pool.

    A tenant over budget sees growing lateness on its own jobs only, which the lateness SLI is partitioned by tenant to show.

    Deep dive 5: failover and the lateness budget

    Failover time directly eats the lateness SLO. If a dispatcher dies, its partitions are unowned until their leases expire. With a 15-second lease and a 1-second scan, a job due just after the death can start up to about 16 seconds late, which breaks the 5-second p99 target.

    Because duplicates are harmless, there is a cheap fix that a leader-based design cannot use: let any dispatcher scan a partition whose last scan is overdue by more than, say, 3 seconds. Several dispatchers may then scan it at once, and the unique run key sorts it out. The lease becomes a hint that keeps the common case efficient, while the helper rule bounds the worst case at a few seconds. The cost is extra reads during a failure, and it is why the due query must be cheap and batched.

    The same reasoning applies to a whole-store failover. If the run store fails over to a replica that lacks the last second of writes, a fire may be re-inserted because the earlier insert was lost, and then run again. That is a duplicate, handled by the idempotent target. A lost run, which is worse, cannot happen as long as next_fire_at and the run insert were in one transaction: either both survived or both were lost, and a lost pair is simply scanned again. See consensus and leader election for the guarantees a store needs for this to hold.

    Bottlenecks and scaling

    • The store's write rate. At the spike, about 33,000 fires per second means 33,000 run inserts plus 33,000 job updates. Shard the store by partition_id, keep rows narrow, and drop old history by time partition.
    • The due scan. The job_due partial index with a batch limit keeps each scan short; add partitions rather than longer batches.
    • Claim contention. Many workers on one hot READY index range collide. SKIP LOCKED reduces blocking, and per-partition claim pools reduce the hot range.
    • Heartbeat load. About 556 updates per second on average is modest, but all heartbeats land on RUNNING rows: keep them in a narrow table or a cache with periodic persistence if volume grows.

    Failure modes

    Failure Effect Mitigation
    Dispatcher dies Partitions unscanned for the lease period Helper scanning of overdue partitions; leases as hints
    Two dispatchers scan one partition Both try the same inserts Unique run key: one wins, the other is a no-op
    Worker crashes mid-run Run stuck RUNNING Lease expiry, reaper, attempt + 1
    Worker paused past its lease Old and new worker both execute Fencing by attempt, idempotent target on runId
    Store failover loses recent writes A fire may repeat Atomic insert and advance; idempotent target
    Target throttles or is down Retries pile up Backoff with jitter, per-target rate limit, parking
    Clock skew between nodes Wrong due decisions in clock-based designs Compare against the store's time
    DST transition Missed or doubled local-time jobs Explicit missing and repeated-time rules
    Tenant floods the queue Others starve Per-tenant caps and round-robin claims
    Long outage Flood of catch-up runs on recovery fire-once default, maxCatchUp cap

    Trade-offs worth stating

    Decision Option A Option B How to choose
    Duplicate prevention Single leader launches Unique run key, many dispatchers The key: no failover pause, same safety
    Delivery At-least-once with fence Skip rather than risk a double Per job: payroll-like jobs may prefer skipping
    Time source Each node's clock The store's clock The store's clock
    Claiming Row locks with skip A broker with delayed delivery Row locks while volume fits one store; a broker when it does not
    Missed fires Fire once Fire all Fire once unless each slot has distinct meaning
    Catch-up flood Unlimited Capped Capped
    Failover Lease expiry only Lease plus helper scanning Helper scanning, when the lateness SLO is tight

    Interview cheat sheet

    Requirements: schedules, per-job policies, multi-tenant, at-least-once. Estimate: average rate, the round-hour spike and run storage (2,778 per second, 33,333 per second, 72 GB per day here). Design: job table with a due index, dispatchers that insert a uniquely keyed run and advance the job in one transaction, workers that claim with leases. Deep dives: the deterministic run id, leases and fencing by attempt, misfire and concurrency policies, helper scanning for failover. Failures: dead dispatcher, paused worker, store failover, DST. Trade-offs: leader versus unique key, skip versus duplicate, store clock versus node clocks.

    Build it

    This lesson has no lab, and the SQL above is a sketch that has not been run. Background jobs and schedulers contains a runnable manual-clock lab for the single-process case.

    In practice: ShopStream's shared scheduler

    NOTE

    This is a realistic scenario, not a case history. It describes no real company, and every number is an illustrative assumption.

    The situation

    ShopStream has 5,000 stores. Each needs a nightly stock reconciliation at 02:00 in the store's local time, a price sync every 15 minutes, and a daily courier-shift reminder. That is 15,000 jobs and about 5,000 x (1 + 96) = 485,000 fires per day, roughly 5.6 per second on average. Four teams currently schedule their own work.

    Starting architecture

    Each service runs in-process timers on every instance, guarded by a lock row in its own database. Behaviour on restart, on missed fires and on overlap differs between teams, and nobody can answer "did store 1042's reconciliation run last night?" without reading four sets of logs.

    Options considered

    Option Gain Cost Risk
    A. Keep per-service timers, standardise a library No new service Four deployments of the same bug surface Lock rows fail differently per team
    B. Shared scheduler service with run table, leases and policies One answer to "did it run?" and one set of semantics A new tier to operate It becomes critical infrastructure
    C. A hosted scheduling product Less to operate Cost, data location, less control of policies Lock-in to its semantics

    The decision

    Field Entry
    Context Missed and overlapping runs were the top source of reconciliation incidents, and no team could see run history across services.
    Decision Build B on the existing relational database, 16 partitions, three dispatchers and a worker pool per team. Reconciliations use fire-once and forbid; price syncs use skip. All targets treat runId as an idempotency key and check attempt.
    Consequences (good) Uniform semantics, queryable run history, a lateness dashboard per tenant.
    Consequences (bad) The scheduler is on the critical path of stock accuracy and needs on-call ownership.
    Revisit when Fires exceed about 1,000 per second, or one database cannot hold the run history.

    Rollout and verification

    1. Run the scheduler in shadow mode: it creates runs but targets only log them. Compare its fire list against the old timers' logs for a week.
    2. Move one team's price syncs first. Alert on lateness above 5 seconds at p99.
    3. Run a game day: kill a dispatcher, pause a worker for 40 seconds, fail over the database, and change a store's time zone data to simulate a daylight-saving change. Assert that no run is lost, that duplicates are rejected by the fence, and that skips carry reasons.
    4. Move reconciliations last, store by store, keeping the old timers disabled but one config flag away.

    The 2 a.m. failure

    At 02:00 a worker running store 1042's reconciliation is paused for 40 seconds by its host. Its 30-second lease expires, the reaper returns the run to READY, and a second worker claims it as attempt 2 and finishes. The first worker wakes and tries to write its results. Its completion update names attempt 1 and matches no row, and the reconciliation target rejects the write because it has already recorded attempt 2 for that run. The on-call engineer sees one run with two attempts and one "stale completion rejected" counter. Without the attempt check, the late write would have overwritten correct stock levels for the store.

    Architect's notes

    • Write the run id into every log line. "Did it run?" must be one query.
    • Pick the missed-fire and overlap policies when the job is registered. Do not default them silently.
    • State the DST rule in the API docs. Tenants in daylight-saving zones will otherwise find out in March or October.
    • Alert on lateness, not on dispatcher health. A healthy process can still be late.
    • Make skipped runs visible. A SKIPPED row with a reason is an audit trail; a silent skip is an incident.
    • Test the pause case, not just the crash case. Crashes are easy to survive; a worker that comes back is not.

    Common mistakes

    • Calling the job directly from the timer. Nothing is recorded, so a crash loses the fire and a duplicate has no key to stop it.
    • Using a lease alone for safety. A paused holder resumes and acts. Add a fencing token or idempotency.
    • Trusting node clocks. Skew moves fires and breaks lease checks. Use one time source.
    • No cap on catch-up. A long outage becomes a flood on recovery.
    • One global worker pool. A single tenant's burst starves the rest.
    • Treating forbid as a guarantee without the claim-time check. A race can let two runs overlap.
    • Evaluating cron in UTC for local-time business jobs. The job drifts an hour twice a year.

    Key takeaways

    • A fire is a row. The job id plus the scheduled time is the run id.
    • The unique key makes dispatching safe. Ownership leases only reduce redundant work.
    • Leases detect silence; fencing handles the slow. attempt is the token.
    • Exactly-once is not available. At-least-once with idempotent targets is.
    • Policies are per job. Missed-fire, overlap, retry and timeout differ with the job's meaning.
    • Use one clock. The store's time decides what is due.
    • Spikes size the system. Round hours, not averages, set the capacity.
    • Make skips and failures visible. Reasons, run history and per-tenant lateness are part of the product.

    Practice exercises

    Exercise 1 - Starter (30 min): Recompute the estimate for 50 million jobs averaging one fire every 30 minutes, with 10% of jobs at the top of the hour spread over 120 seconds. State fires per second on average and at the spike, run rows per day at 250 bytes, and concurrent runs at a 3-second average duration.

    Exercise 2 - Intermediate (2 hours): Write a table with columns "scenario", "misfire policy", "what runs", for a job that missed 6 hourly slots during a 6-hour outage under skip, fire-once, fire-all with maxCatchUp 3, and fire-all with maxCatchUp 10. Then do the same for a daily job whose local time is skipped by a daylight-saving change.

    Exercise 3 - Intermediate (2 hours): Design the forbid guarantee properly. Describe the per-job active-run marker, the exact claim-time check, and how the reaper clears it when a worker dies. Say which race remains if you only check at dispatch time.

    Exercise 4 - Advanced (half day): Plan a failure-injection test: kill a dispatcher, run two dispatchers on one partition, pause a worker past its lease, fail over the store, and flood one tenant. For each, state the invariant you assert (every due slot has exactly one run row, no stale completion is accepted, other tenants' lateness stays under budget) and the metric that proves it.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments