Skip to content

Design a Distributed Job Scheduler

Advanced 67 min read Part 17 of 18

Design a distributed job scheduler: cron and one-off jobs, time-bucketed queues, at-least-once runs, idempotency, partitioned schedulers, retries, heartbeats.

The Problem#

Almost every company runs work that is not triggered by a user clicking a button. Invoices go out on the first of the month. A data pipeline rebuilds yesterday's reports at 02:00. A reminder email fires 24 hours before an appointment. A cache warms itself every five minutes. A retry of a failed webhook delivery happens in 30 seconds, then in 2 minutes, then in 10. On a single machine this is what cron does: a daemon wakes up every minute, checks a table of schedules and starts the matching commands.

A distributed job scheduler is cron rebuilt for a world where one machine is not enough and failure is normal. Think of Apache Airflow scheduling data pipelines, Kubernetes CronJobs, AWS EventBridge Scheduler, Quartz in Java applications, or the internal schedulers that large companies run for millions of tenants. It must accept jobs from many users, store them durably, fire each one close to its scheduled time, hand it to a fleet of workers, notice when a worker dies halfway through, retry failures sensibly, and report status back to the user, all at a rate of thousands of executions per second.

Two terms are worth pinning down at the start, because interviewers use them precisely:

  • A task is the abstract, reusable piece of work: "send an email", "generate a report", "resize an image". It is code, registered once.
  • A job is an instance of a task bound to a schedule and parameters: "send an email to john@example.com at 10:00 on Friday", or "generate the sales report for region EU every day at 02:00 UTC". A recurring job produces many executions (also called runs), one per scheduled time.

The scheduler's main responsibility is simple to state: take a set of jobs and execute each one according to its schedule. The difficulty is in the words hidden inside that sentence. "Execute" means at least once, even if machines crash, and ideally without harmful duplicates. "According to its schedule" means within a couple of seconds of the right time, across time zones, daylight-saving changes and leap days, even when a million jobs are all scheduled for midnight. "A set of jobs" means hundreds of millions of definitions, so no single machine can hold them in memory or scan them every second.

Analogy. Picture a large hospital's medication rounds. Doctors write prescriptions (job definitions): "2 tablets every 8 hours", "one injection at 14:00 tomorrow". The pharmacy files them in a drawer cabinet organised by hour (the time-bucketed store). Every few minutes a charge nurse (the scheduler) opens the drawer for the coming hour and hands the cards that are due to the nurses on duty (workers). Each nurse checks in regularly with the charge nurse (heartbeats); if a nurse collapses mid-round, their unfinished cards are handed to someone else (lease expiry and retry). Every dose is ticked off on the patient's chart before the card is filed as done, and nurses check the chart before giving a dose so that a reassigned card does not result in a double dose (idempotency). If the hospital grows, one charge nurse per ward (partitioned schedulers) replaces the single head nurse, who would otherwise become the bottleneck and a single point of failure.

This problem is a favourite at senior and staff level because it compresses several hard distributed-systems ideas into one design:

  1. Time as a first-class index. Storing and querying "everything due in the next N seconds" efficiently at high write rates, without a hot partition at the current minute.
  2. Delivery semantics. Why exactly-once execution is impossible in general, how to get at-least-once, and how idempotency turns it into effectively-once.
  3. Coordination. Leader election versus partitioning for the scheduler role, fencing out zombies, and detecting dead workers with heartbeats.
  4. Failure handling. Timeouts, retries with backoff and jitter, dead-letter handling, and catching up after an outage without stampeding.

Clarifying Questions#

QuestionWhy it mattersAssumed answer
What kinds of schedules?One-off versus recurring changes the data model.Immediate, at a specific future time, and recurring (cron expressions such as "every day at 10:00").
How precise must execution be?Drives the dispatch architecture.A job should start within about 2 seconds of its scheduled time.
What scale?Sizing of storage, scheduler and queue.Up to 10,000 job executions per second at peak; on the order of 100 million job definitions.
What does a job do? Who runs the code?Whether we run arbitrary containers or call registered task handlers.Jobs invoke registered tasks: code deployed in worker fleets (or an HTTP callback). We do not sandbox untrusted code.
How long do jobs run?Short jobs versus hours-long batch jobs need different failure detection.Mostly seconds; some run for minutes to hours.
What execution guarantee?Exactly-once versus at-least-once shapes everything.At-least-once; tasks are expected to be idempotent, and the platform helps with idempotency keys.
Do users need to monitor jobs?Status APIs and secondary indexes.Yes: users can see status and history of their jobs and executions.
Cancel and reschedule?Extra state transitions.Nice to have (we cover them as an extension).
Dependencies between jobs (DAGs)?Airflow-style workflows are a larger problem.Out of the core scope; discussed as a variant.
Multi-tenant?Fairness and isolation between customers.Yes, many internal teams or external customers share the platform.
Time zones?Cron in local time hits daylight-saving edge cases.Schedules carry an explicit IANA time zone; UTC by default.

Requirements#

Functional Requirements#

  1. Schedule jobs to run immediately, at a specific future time, or on a recurring schedule expressed as a cron expression with a time zone.
  2. Monitor jobs: see each job's definition, next run time, and the status of its executions (scheduled, queued, running, succeeded, failed, retrying), with attempt history and error messages.
  3. Configure behaviour per job: retry policy (max attempts, backoff), timeout, and priority.

Below the line (extensions): cancel or pause a job, reschedule a job, job dependencies and DAGs, rate limits per tenant, callbacks on completion.

Non-Functional Requirements#

  1. Timeliness: an execution starts within 2 seconds of its scheduled time under normal operation.
  2. Scale: sustain 10,000 executions per second, with bursts above that at popular times (the top of every hour, midnight UTC).
  3. At-least-once execution: a scheduled execution is never silently dropped, even if schedulers, queues or workers crash. Duplicates are possible but rare and bounded.
  4. High availability: no single point of failure; scheduler failover in seconds, not minutes.
  5. Durability: once a job is accepted, it survives the loss of any machine or availability zone.
  6. Observability: every execution's state transitions are queryable by the job's owner within seconds.
  7. Isolation: a tenant that schedules a million jobs at midnight must not delay everyone else's jobs.

The sharpest trade-off sits between requirements 1 and 3. Timeliness pushes towards fast, in-memory dispatch. At-least-once pushes towards durable writes before every step. The design that satisfies both uses two tiers: a durable store as the source of truth, and a short-horizon, fast queue for precise firing.

Capacity Estimation#

See Back-of-the-Envelope Estimation and Numbers Every Engineer Should Know for the method.

Executions#

  • Peak rate: 10,000 executions per second.
  • Average rate: assume about a third of peak, 3,000 per second, because load is concentrated at round times. That is 3,000 × 86,400 ≈ 260 million executions per day. If peak were sustained all day, it would be 864 million.
  • Top-of-the-hour spike: humans write 0 * * * * (every hour on the hour) and 0 0 * * * (midnight) far more than 17 * * * *. In practice a large fraction of recurring jobs land on minute 0, and many on second 0. If 20 million daily jobs all target midnight UTC, firing them within 2 seconds would need 10 million per second. No reasonable system does that, so the design must spread such spikes (Deep Dive 9).

Job definitions#

  • Assume 100 million active jobs (one-off and recurring) across all tenants.
  • A job definition (task name, parameters up to a few KB, schedule, retry policy, owner, metadata) averages about 1 KB.
  • Total: 100 M × 1 KB ≈ 100 GB. Small enough for one large database in principle, but the read and write rates below argue for a horizontally scalable store.

Execution records#

  • Each execution record (job id, scheduled time, status, attempt, worker, timestamps, short error message) is about 300 to 500 bytes.
  • 260 M per day × 400 bytes ≈ 100 GB per day.
  • Keep 30 days of history online: about 3 TB, plus indexes. Older history moves to cheap storage (see Data Lifecycle, Tiering and Retention).

Write and read rates#

  • Each execution causes several writes: created (scheduled), queued, running, completed. With 4 state changes per execution at 10,000 executions per second, that is 40,000 writes per second at peak, plus heartbeats from long-running jobs.
  • Heartbeats: if 50,000 executions are running at once and each heartbeats every 10 seconds, that is 5,000 heartbeat writes per second (or far fewer if heartbeats go to an in-memory lease store rather than the database).
  • Monitoring reads: users and dashboards query status. Assume a few thousand reads per second, mostly by job or by owner and time range.

Queue and workers#

  • Messages through the dispatch queue: 10,000 per second at peak, small (under 1 KB, since parameters can be fetched or inlined).
  • Workers: if an average job takes 2 seconds of work, Little's law (in-flight work = arrival rate × time in system) gives 10,000 × 2 = 20,000 executions in flight. At 50 concurrent executions per worker process (I/O-bound tasks), that is about 400 worker processes, before headroom.
QuantityEstimateImplication
Peak executions10,000 per secondDispatch must be horizontally scalable
Execution history~100 GB per day, ~3 TB for 30 daysPartitioned store, TTL and tiering
State-change writes~40,000 per second at peakWrite-optimised, horizontally scalable DB
Job definitions~100 GBFits easily; indexed by id and owner
In-flight executions~20,000Lease and heartbeat tracking at this scale
Hourly spikepotentially millions at :00Jitter, smoothing and tenant fairness

The numbers point to a write-heavy, time-indexed workload in which the scarce resources are write throughput on the "current time" slice of data and the coordination needed to dispatch it exactly once per scheduled time.

Core Entities#

  • Task. A registered unit of code: name, version, the task queue its workers listen on, default timeout and retry policy. Tasks are reusable.
  • Job. A task plus a schedule and parameters, owned by a user or tenant. Fields: job id, owner, task name, parameters, schedule (type plus cron expression or timestamp plus time zone), retry policy, timeout, priority, status (active, paused, cancelled), next run time.
  • Execution. One run of a job for one scheduled time. Fields: execution id (often derived from job id plus scheduled time), scheduled time, status, attempt number, worker id, lease expiry, start and end times, result or error. A one-off job has one execution; a recurring job has one per occurrence.
  • Worker. A process that polls a task queue, runs executions and heartbeats. Not stored as a business entity, but tracked for leases and health.

The key modelling decision, which we will justify in the high-level design, is to separate the Job (the definition) from the Execution (each occurrence). Definitions are read when creating executions and when users browse them. Executions are what the scheduler queries by time, what workers update, and what users monitor.

API Design#

All endpoints are behind an API Gateway and Backend-for-Frontend that authenticates the caller and enforces per-tenant quotas.

Create a job#

POST /jobs
Idempotency-Key: 7c1e...
{
  "task": "send-email",
  "parameters": { "to": "john@example.com", "template": "weekly-digest" },
  "schedule": { "type": "cron", "expression": "0 10 * * FRI", "timezone": "Europe/London" },
  "retryPolicy": { "maxAttempts": 5, "initialBackoffSeconds": 10, "backoffMultiplier": 2 },
  "timeoutSeconds": 300,
  "priority": "normal"
}
-> 201 { "jobId": "job_8f2...", "nextRunAt": "2026-12-04T10:00:00Z" }

schedule.type is one of immediate, once (with runAt), or cron (with expression and timezone). The server validates the cron expression, computes the first run time and returns it so the user can confirm it means what they think. The Idempotency-Key makes a retried creation return the same job rather than creating a duplicate (see Idempotency and Safe Retries).

Inspect jobs and executions#

GET /jobs/:jobId
-> 200 { job definition, status, nextRunAt, lastExecution }
 
GET /jobs/:jobId/executions?from=...&to=...&cursor=...
-> 200 { executions: [ { executionId, scheduledAt, status, attempt, startedAt, finishedAt, error } ], nextCursor }
 
GET /jobs?owner=me&status=failed&from=...&to=...&cursor=...
-> 200 { jobs or executions matching the filter }

The last query, "show me my failed executions in the last day", drives a secondary index by owner and time.

Change a job (extensions)#

PATCH  /jobs/:jobId        { schedule?, parameters?, status: "paused" | "active" }
DELETE /jobs/:jobId        -> cancels future executions; running ones get a cancellation request
POST   /jobs/:jobId/run    -> trigger an immediate extra execution

Worker-facing API#

Workers do not use the public API. They talk to the dispatch layer:

poll(taskQueue, maxTasks)                 -> leased executions with lease expiry
heartbeat(executionId, leaseToken, progress?) -> { leaseExtendedUntil, cancelRequested }
complete(executionId, leaseToken, result)
fail(executionId, leaseToken, error, retryable)

The lease token (an attempt number or fencing token) appears in every worker call. If a worker's lease expired and the execution was given to someone else, the old worker's late complete is rejected because its token is stale. This is how the system fences out zombie workers.

EndpointCallerPurpose
POST /jobsUsersCreate one-off or recurring job
GET /jobs/:id, GET /jobs/:id/executionsUsersMonitor status and history
GET /jobs?owner&status&from&toUsersSearch executions by owner and time
PATCH, DELETE /jobs/:idUsersPause, reschedule, cancel
poll, heartbeat, complete, failWorkersLease work, report liveness and results

High-Level Design#

Build it requirement by requirement.

1. Scheduling jobs: storing definitions and executions#

A Job Service receives POST /jobs, validates the task name, parameters and schedule, and writes two things:

  1. The Job row: the definition, keyed by job_id.
  2. The first Execution row: keyed so that the scheduler can find it by time. For a one-off job this is the only execution. For a cron job, it is the next occurrence only.

Why not store just the job and compute occurrences on the fly? Because the scheduler's core question is "what is due in the next few seconds?", and answering that by scanning 100 million job definitions and evaluating each cron expression is hopeless. Materialising each upcoming occurrence as an execution row, indexed by scheduled time, turns the question into a narrow range read.

Why only the next occurrence, not all future ones? A job running every minute would need 525,600 rows per year, most of which would have to be rewritten if the user edits the schedule. Materialising one occurrence at a time keeps storage proportional to the number of jobs, makes edits cheap, and fits naturally with "when this execution is dispatched, compute and insert the next one".

The execution table is indexed by time bucket. Executions are partitioned by a coarse time bucket (for example, the minute or the hour of scheduled_at) and sorted within the bucket by exact time and execution id. "Everything due between 10:00:00 and 10:05:00" is then a read of one or a few partitions. Deep Dive 3 explains why the bucket also needs a shard suffix: otherwise every write for the current minute lands on one partition.

Which database? The access pattern is a high-rate stream of inserts and status updates, range reads by time bucket, point reads by execution id and per-owner queries. A wide-column or key-value store with partition plus sort keys fits naturally: Cassandra, DynamoDB, ScyllaDB or Bigtable. A sharded relational database (PostgreSQL partitioned by time, or a distributed SQL database) also works and makes secondary indexes and transactions easier. See Choosing a Database: A Decision Guide.

2. Firing executions on time#

Now something has to find due executions and start them. Three increasingly good approaches:

Bad: workers query the database directly. Every worker runs SELECT ... WHERE scheduled_at <= now() AND status = 'scheduled' LIMIT 10 every second and tries to claim rows. With hundreds of workers this is hundreds of overlapping range queries per second on the hottest partition, constant contention on the same rows, and poor timing (a job is picked up only when some worker's poll happens to come round).

Good: a scheduler polls the database and pushes to a queue. A dedicated Scheduler queries the execution table every second for rows due now, publishes them to a dispatch queue, and marks them queued. Workers consume from the queue. Database load is now one query per second per scheduler partition, and the queue gives workers a clean, scalable interface. The weakness is timing: polling every second at 10,000 rows per second means big result sets and some jobs being picked up up to a second late; and a scheduler pause (GC, failover) delays everything.

Great: two tiers, a durable store plus a short-horizon timer queue. Separate finding due work from firing it:

  1. A Watcher scans the execution table periodically (for example every minute) for executions due in the next few minutes (say, the next 5), and loads them into a fast timer queue with their exact fire times. Its query is cheap because it reads a small, well-defined time range ahead of time.
  2. The timer queue delivers each execution at its scheduled moment to the dispatch queue for its task. This can be a message queue with per-message delay (Amazon SQS lets a message be delayed by up to 15 minutes), a Redis sorted set scored by fire time, or an in-memory timing wheel inside the scheduler process.
  3. Executions created with a scheduled time inside the current look-ahead window (including immediate jobs) are pushed straight to the timer queue by the Job Service, so they are not missed by a scan that already ran.

Precision now depends only on the timer queue, which can fire within milliseconds, while the database is read in large, efficient, predictable batches. Deep Dive 2 compares the timer-queue options.

3. Executing jobs on workers#

Workers are long-running processes, deployed by the teams that own the tasks, that poll one or more named task queues ("email", "reports", "image-resize"). This is the model used by workflow engines such as Temporal, where the application names a task queue for each kind of work and configures workers to poll the same name. A worker:

  1. Polls the dispatch queue and receives an execution with a lease (for example, 60 seconds).
  2. Marks it running in the execution table with its worker id and attempt number.
  3. Runs the task with the job's parameters, heartbeating periodically to extend the lease and report progress.
  4. Completes or fails it: writes the final status, and on failure the platform schedules a retry as a new attempt at a later time (Deep Dive 7).
  5. Acknowledges the message so it is not redelivered.

If the worker dies, heartbeats stop, the lease expires, and the execution becomes available to another worker. That is the backbone of at-least-once execution (Deep Dive 5).

Recurring jobs. When an execution of a cron job is dispatched (not when it completes, so that a slow run does not delay the next occurrence), the scheduler computes the next fire time from the cron expression and inserts the next execution. If the user wants "never overlap" semantics, the policy is checked at dispatch: skip or delay the new execution while the previous one is still running.

4. Monitoring jobs#

Users need "my jobs" and "my executions in a time range, filtered by status". The execution table is partitioned by time bucket, which is great for the scheduler but useless for "show me job X's history". Add:

  • A secondary index by job id (partition job_id, sort scheduled_at) for a job's history.
  • A secondary index by owner (partition owner_id, sort scheduled_at) for "my executions".

In DynamoDB these are global secondary indexes (eventually consistent, which is fine for monitoring); in Cassandra they are separate denormalised tables written alongside the main one. A Status Service answers the monitoring APIs from these indexes, with recent state optionally served from a cache.

The full high-level design#

Components:

  • API Gateway. Authentication, per-tenant quotas and rate limits on job creation.
  • Job Service. Validates and stores job definitions, materialises the next execution, and short-circuits near-term executions into the timer queue.
  • Jobs table. Job definitions keyed by job id, with an index by owner.
  • Executions table. One row per occurrence, partitioned by time bucket plus shard, sorted by scheduled time. The source of truth for what must run and what happened.
  • Scheduler tier (watchers and next-occurrence calculator). Partitioned across instances; each owns a set of shards via leases from a coordination service. Scans its shards' look-ahead window, loads the timer queue, and inserts next occurrences for cron jobs.
  • Timer queue. Holds executions due within the next few minutes and releases each at its fire time. Delayed-message queue, Redis sorted set or in-memory timing wheel.
  • Dispatch queues. One per named task queue, so each worker fleet consumes only its own work and scales independently.
  • Worker fleets. Owned by task teams; poll their queue, run tasks, heartbeat, report results.
  • Lease store. Tracks which worker holds which execution until when. Can be the dispatch queue's own visibility timeout, the execution table, or a fast store like Redis.
  • Reconciler. Finds executions whose lease expired or that were due but never dispatched, and re-enqueues or retries them. The safety net behind at-least-once.
  • Status Service and indexes. Serves monitoring queries from secondary indexes by job and by owner.
  • Coordination service. etcd or ZooKeeper for shard ownership, leader election and fencing tokens. See ZooKeeper and etcd.

Key Flows#

Flow 1: Create a recurring job and fire its first occurrence#

Important details:

  • Time zones are resolved when computing the next run. "10:00 Europe/London" is 10:00 UTC in winter and 09:00 UTC in summer. The stored scheduled_at is always UTC, computed from the cron expression in the job's zone, so the scheduler never thinks about zones.
  • Marking loaded is an optimisation, not a guarantee. If the watcher crashes after loading the timer queue but before marking, the next scan loads the execution again. The timer queue or the dispatch step must deduplicate by execution id, and workers must tolerate the rare duplicate anyway.
  • The next occurrence is inserted at dispatch time. A run that takes 15 minutes does not delay next week's occurrence, and a missed completion (worker crash) does not stop the series.

Flow 2: A worker dies mid-execution#

Two failure flavours look identical from the outside: the worker crashed, or it is alive but partitioned or paused (a long garbage-collection pause, a stuck network). In the second case, the old worker might still finish and try to report. The token check rejects that late write, but the side effect of the task (the email) may already have happened twice. That is why at-least-once execution requires idempotent tasks (Deep Dive 6).

Flow 3: A task fails and is retried with backoff#

In practice, "D schedules" means the platform component that handles fail (the Job Service or a Retry Service) computes the next attempt time and writes it through the same path as any scheduled execution: into the execution table, and into the timer queue if it falls inside the look-ahead window. Retries are therefore durable; a crash right after a failure does not lose the retry.

Execution lifecycle#

Every arrow is a conditional write on the execution row (compare the current status and attempt, then set the new ones), so two components racing to move the same execution cannot both succeed. That single rule prevents most double-dispatch bugs.

Data Model#

TablePartition keySort keyPurpose
jobsjob_idnoneDefinitions; index on (tenant_id, created_at)
executionsbucket#shard, e.g. 2026-12-04T10:00#07scheduled_at#execution_idScheduler range scans of due work
executions_by_jobjob_idscheduled_atHistory of one job
executions_by_tenanttenant_id#dayscheduled_at#execution_id"My executions" queries
attemptsexecution_idattemptPer-attempt details and errors
taskstask_namenoneRegistered tasks and their task queues

Notes:

  • Execution id is deterministic: hash(job_id, scheduled_at). Re-materialising the same occurrence (after a crash, or by two racing schedulers) produces the same id, so an insert-if-not-exists deduplicates it. This is the seed of idempotency for the whole pipeline.
  • The shard suffix spreads one minute's executions across N partitions (Deep Dive 3).
  • TTL on execution rows (for example 30 days) keeps the hot table small; a change-data-capture stream copies finished executions to a warehouse or object storage for long-term history.
  • Denormalised index tables (Cassandra) or GSIs (DynamoDB) are written alongside the main table and can lag slightly, which is acceptable for monitoring.

See Data Modeling and Partitioning and Sharding.

Deep Dives#

1. Job definitions, cron expressions and the meaning of time#

Everything in a scheduler starts with "when should this run?". Getting that question right is surprisingly subtle.

Cron syntax. The classic Unix cron expression has five fields: minute, hour, day of month, month and day of week. 0 10 * * FRI means "at minute 0 of hour 10, every Friday". */15 * * * * means every 15 minutes. 0 2 1 * * means 02:00 on the first of every month. Many schedulers add a seconds field (Quartz uses six or seven fields) and extensions such as L for "last day of month" or W for "nearest weekday". Two old cron quirks to know: when both day-of-month and day-of-week are restricted, traditional cron fires when either matches, not both; and different implementations number weekdays differently (0 or 7 for Sunday). A platform should pick one dialect, document it, and validate expressions on creation by showing the next few fire times.

Other schedule types. Not everything is cron:

  • Fixed rate: "every 5 minutes starting now", measured from a start time, not from the clock's minute boundary.
  • Fixed delay: "5 minutes after the previous run finished". The next execution can only be computed on completion, so it is materialised by the completion handler, not at dispatch.
  • One-off: a single timestamp.
  • Immediate: scheduled at "now"; the scheduler is acting as a durable queue with retries.
  • Calendars: "every business day except holidays in the UK". Implemented as cron plus an exclusion calendar.

Computing the next fire time. Given the expression, the time zone and the previous fire time, find the earliest matching time strictly after it. A simple, correct algorithm increments field by field: find the next matching month, then day, then hour, then minute, resetting lower fields when a higher one changes. For pathological expressions (February 30th never exists), cap the search (for example, five years) and reject the job.

Time zones and daylight saving. A job "every day at 02:30 America/New_York" has two edge cases a year:

  • Spring forward: clocks jump from 02:00 to 03:00, so 02:30 does not exist that day. Options: skip the run, or run at 03:00 (the first valid time after). Most schedulers run it once, at the shifted time.
  • Fall back: 01:00 to 02:00 happens twice. A job at 01:30 could fire twice. The usual rule is to fire once, at the first occurrence.

The robust implementation: store the cron expression and the IANA time zone (never a fixed offset like UTC-5, which ignores DST), compute the next fire time in that zone with a proper time library, convert to a UTC instant, and store that instant as scheduled_at. Everything downstream works purely in UTC. When time-zone rules change (governments do change them, sometimes at short notice), upgrade the time-zone database and recompute next_run_at for affected jobs.

Misfire policy. What should happen if the scheduler was down from 09:58 to 10:07 and a job was due at 10:00? Options, chosen per job:

  • Fire once now (the usual default): run the missed execution as soon as possible.
  • Fire all missed: for an every-minute job after a 7-minute outage, run 7 executions. Right for jobs that process a time window each ("aggregate minute 10:03"), wrong for jobs that send a notification.
  • Skip: drop missed runs and wait for the next one. Right for "refresh the cache" or "take a snapshot of current state".
  • Fire if not too late: run only if less than a threshold (say 1 hour) late.

Airflow's equivalent is the catchup flag, which decides whether missed intervals are backfilled when a DAG is enabled or recovers. A well-designed scheduler records the scheduled time and the actual start time separately, so tasks can use the scheduled time (the logical time) to decide what data to process, which makes late and re-run executions behave deterministically.

Overlap policy. If a job runs every 5 minutes and one run takes 8 minutes, should the next start anyway? Options: allow concurrent runs, skip the new one, queue it until the previous finishes, or cancel the old one and start the new one. Kubernetes CronJobs, for example, expose this choice as a concurrency policy (Allow, Forbid, Replace). The scheduler checks it at dispatch by looking at the job's most recent execution.

Parameters and versioning. Parameters are stored with the job and copied into each execution at materialisation time, so editing a job does not change an execution that is already queued. Tasks are versioned; a job can pin a version or follow the latest. Large parameters (a 10 MB input file) belong in object storage with a reference in the job.

2. Firing within 2 seconds: the timer queue#

The requirement is to start each execution within 2 seconds of its scheduled time at 10,000 per second. Options for the fast tier:

Bad: frequent database polling. Query WHERE bucket = current_minute AND scheduled_at <= now() AND status = 'scheduled' every 100 ms. You get good precision, but every query re-reads the same partition, and at 10 polls per second across N shards and several scheduler replicas, the hottest partition in the database is hammered for no new information.

Good: in-memory priority queue in each scheduler. Each scheduler loads its shards' executions for the next few minutes into a min-heap keyed by fire time, and a timer thread pops entries as they become due and publishes them. O(log n) per insert and pop, precise to milliseconds. The catch is durability and failover: the heap is lost when the process dies, so a new owner must reload the window from the database. That is acceptable precisely because the database remains the source of truth; the heap is only a cache of the next few minutes.

Good: hashed and hierarchical timing wheels. For very large numbers of timers, a min-heap's O(log n) and poor cache behaviour can matter. A timing wheel is a circular array of buckets, each representing a tick (say 100 ms); a timer due in k ticks goes in bucket (current + k) mod size, and a pointer advances one bucket per tick, firing everything in it. Inserts and expiries are O(1). Hierarchical wheels (seconds, minutes, hours) handle long delays by cascading timers down to finer wheels as they approach. The idea comes from "Hashed and Hierarchical Timing Wheels: Data Structures for the Efficient Implementation of a Timer Facility" (Varghese and Lauck, SOSP 1987). Kafka uses a hierarchical timing wheel for its internal delayed operations, and Netty provides a HashedWheelTimer.

Great: a delayed-delivery queue or a Redis sorted set as a shared timer tier. Instead of each scheduler holding timers in memory, use shared infrastructure:

  • Delayed messages. Amazon SQS supports per-message delivery delays of up to 15 minutes. The watcher, scanning 5 minutes ahead, sends each execution with DelaySeconds = scheduled_at - now. SQS stores it durably and makes it visible at the right time. Precision is typically within a second or so, and you inherit SQS's durability and scale. RabbitMQ (via a delayed-message plugin), ActiveMQ and Pulsar (delayed delivery) offer similar features.
  • Redis sorted set as a timer queue. ZADD timers:{shard} <fire_epoch_ms> <execution_id>. A dispatcher loop runs a Lua script every 50 to 100 ms that atomically takes all members with score up to now (ZRANGE timers:{shard} -inf <now> BYSCORE LIMIT 0 500, then ZREM them) and pushes them to the dispatch queue. Sharding the key spreads load across Redis nodes. Durability comes from Redis persistence plus the database as the source of truth: if Redis loses data, the reconciler reloads the window.
-- Lua: atomically pop up to 500 due timers from one shard
local due = redis.call('ZRANGE', KEYS[1], '-inf', ARGV[1], 'BYSCORE', 'LIMIT', 0, 500)
if #due > 0 then
  redis.call('ZREM', KEYS[1], unpack(due))
  for _, id in ipairs(due) do redis.call('LPUSH', KEYS[2], id) end
end
return #due
OptionPrecisionDurabilityThroughputOperational cost
DB polling every 100 ms~100 msStrong (it is the DB)Limited by hot partitionLow, but wasteful
In-memory heap per schedulermsLost on crash; reload windowHighMedium (failover reload)
Timing wheel per schedulerone tickLost on crash; reload windowVery highMedium
SQS delayed messages~1 sStrong, managedVery highLow (managed); 15-minute cap
Redis sorted set50 to 100 msMedium; DB is backupVery highMedium

The look-ahead window size balances two concerns. A longer window (say 15 minutes) means fewer scans and more tolerance of scanner hiccups, but more timer-queue memory and more work to undo when users cancel or edit jobs. A shorter window (1 minute) keeps the timer tier small but leaves less slack if a scan is late. Five minutes with scans every minute gives four chances to load any execution before it is due. New executions due inside the window must be inserted into the timer queue directly by the Job Service, or they will be missed until the next scan, which could already be too late.

Cancelling a loaded execution. If a user cancels a job whose next execution is already in the timer queue, removing it from SQS is not possible (messages cannot be deleted before they are received). Instead, the cancel marks the execution row cancelled, and the dispatcher or worker checks the row's status before running. With Redis, ZREM removes it directly. In both cases the database row is the final authority.

Clock discipline. "Within 2 seconds" assumes the scheduler's clock is right. Keep all scheduler hosts synchronised with NTP or a cloud time service (typically within a few milliseconds), and never rely on a client-provided time to decide when to fire. See Time, Clocks and Ordering.

3. The time-bucketed store and the hot-partition problem#

The executions table is the system's spine. Its job is to answer one query extremely well: "give me every execution due in time range [t1, t2) for shard s", while absorbing tens of thousands of inserts and updates per second.

The naive key and why it fails. Partitioning by scheduled_minute alone means every execution due in the same minute goes to one partition. At 10,000 per second, that is 600,000 rows written into a single partition per minute, and every status update for currently running jobs also hits it. Distributed databases cap the throughput of a single partition: DynamoDB, for example, documents a per-partition limit of about 1,000 write units per second, and a Cassandra partition is served by a fixed set of replicas. One minute's partition becomes a hot spot that throttles the whole system, and the hot spot moves forward with the clock, so adding nodes does not help.

Write sharding. Append a shard number to the bucket: partition key = bucket#shard, where shard = hash(execution_id) mod N. With N = 64, each minute's writes are spread across 64 partitions, about 160 per second each at peak, comfortably within limits. The scheduler tier is partitioned the same way: scheduler instance k owns shards k, k + M, k + 2M and so on, and scans only its own bucket#shard partitions.

How big should N be? Large enough that peak per-partition writes are well under the store's limit, and small enough that each scheduler's scan is not dominated by per-partition overhead. A useful rule: N is a few times the maximum number of scheduler instances you expect, so ownership can be rebalanced in small steps. N is hard to change later (old rows were written with the old N), so choose generously; scanning an empty partition is cheap.

Bucket size. Minute buckets keep partitions small and scans precise. Hour buckets mean fewer partitions but huge ones during busy hours. For a look-ahead scan of 5 minutes, minute buckets mean reading 5 × (shards owned) partitions per scan, each a single sequential read. Very sparse systems can use hour buckets; busy ones use minutes.

Status updates are the other half of the load. Each execution moves through several states. Two ways to keep updates from re-heating the time partition:

  1. Keep only scheduling state (scheduled, loaded, dispatched) in the time-bucketed row, and record running state (running, heartbeats, results) in a separate table keyed by execution_id, which spreads uniformly.
  2. Or keep everything in one row but rely on the shard suffix to spread the writes. Simpler, and fine if per-partition rates stay within limits.

Option 1 is the usual choice at high scale: the scheduler's partitions are written once (on materialisation) and updated once (on dispatch), and are then read-only history.

Finding stragglers. What about executions whose bucket is in the past but which never ran (the scheduler for that shard was down for 10 minutes)? The watcher's scan should cover [last_scanned_until, now + window), not just [now, now + window). Each scheduler stores a per-shard high-water mark ("I have loaded everything up to 10:05:00 for shard 7") in the coordination service or the database. A new owner of the shard resumes from that mark, so nothing is skipped after failover. Late executions are then subject to the job's misfire policy.

Choosing the store.

StoreFitWatch out for
Cassandra or ScyllaDBExcellent write throughput; partition plus clustering key is exactly bucket#shard plus scheduled_at#idTombstones from deletes and TTL expiry; avoid reading heavily deleted partitions; use lightweight transactions sparingly for conditional updates
DynamoDBManaged, conditional writes are cheap, TTL built in, GSIs for monitoringPer-partition throughput limits (hence sharding), GSI lag, item size limit of 400 KB
PostgreSQL (partitioned by time)Transactions, SKIP LOCKED claiming, rich indexesSingle-primary write ceiling; needs sharding (Citus or application-level) at 40,000 writes per second
Distributed SQL (CockroachDB, Spanner, YugabyteDB)SQL plus horizontal scale plus transactionsHot ranges at the current time still need the shard prefix; higher write latency

Whatever the store, two capabilities are essential: conditional writes (compare-and-set on status and attempt) and efficient range reads within a partition. See Storage Engines: B-Trees vs LSM Trees for why LSM-based stores like Cassandra absorb this insert-heavy pattern well.

4. Leader-based versus partitioned schedulers#

Someone must run the watcher scans and the timer dispatch. If two instances do it for the same data without coordination, every execution fires twice. If one instance does it and dies, nothing fires. Three designs:

Single leader (active-passive). All scheduler instances compete for a leadership lease in a coordination service (etcd, ZooKeeper, Consul) or a database row. The winner does all scanning and dispatching; the others wait. On leader failure, the lease expires (say after 10 seconds) and another instance takes over, reloads the look-ahead window and resumes from the high-water mark.

  • Pros: simplest correct design; no double dispatch while leadership is exclusive; easy to reason about.
  • Cons: throughput is capped by one machine (scan, timer and publish for 10,000 per second is feasible, but leaves little headroom for spikes); failover gap of lease timeout plus reload (10 to 30 seconds), which violates "within 2 s" during failover; and a single machine's GC pause delays everything.
  • The zombie problem. A leader that pauses for 15 seconds may wake up still believing it is leader, while a new leader has taken over. Both dispatch. The fix is a fencing token: each new leadership term gets a monotonically increasing number (an etcd revision or ZooKeeper zxid serve well), every write the scheduler makes carries it, and the store rejects writes with a token lower than the highest it has seen. See Leader Election and Coordination Services.

Many production schedulers start this way. Kubernetes runs its CronJob controller inside the controller manager, which uses leader election so that only one instance is active at a time. Google described its distributed cron service in "Reliable Cron across the Planet" (Davidovič and Guliani, ACM Queue, 2015): a leader elected through Paxos launches jobs, and replicas share the state of launches through the Paxos log, so a new leader knows which launches were already attempted.

Partitioned (sharded) schedulers. Split the shard space among many scheduler instances. Each instance holds a lease on a subset of shards and is the single owner (a "leader") for each of them. Ownership is assigned by:

  • Lease per shard in the coordination service: each instance tries to acquire leases for shards up to its fair share; on failure, its leases expire and others pick them up.
  • Consistent hashing over the membership list: instances register in etcd or ZooKeeper; each shard is owned by the instance it hashes to. Membership changes move only about 1/n of shards. See Consistent Hashing.
  • A consumer group: if executions flow through a partitioned log (Kafka topic partitioned by shard), the log's group protocol assigns partitions to scheduler instances.

Partitioning scales linearly with instances, limits the blast radius of one failure to its shards, and makes failover faster (a smaller window to reload). It inherits the zombie problem per shard, solved the same way: a fencing token per shard lease.

Leaderless with database locking. No elected owner at all: every scheduler instance competes for due rows using row-level locks, such as PostgreSQL's SELECT ... FOR UPDATE SKIP LOCKED, so each row is claimed by exactly one instance at a time. Quartz's clustered mode coordinates instances through locks in its database job store, and Airflow 2 runs multiple active schedulers that rely on row-level locking in the metadata database. This is attractive at moderate scale because there is nothing extra to operate. At 10,000 executions per second the lock traffic on one database becomes the bottleneck, which pushes high-scale systems back to partitioning.

DesignThroughputFailover impactComplexityTypical use
Single leader with standbyOne machineAll jobs pause for lease timeout plus reloadLowSmall and medium systems, control-plane cron
Partitioned with per-shard leasesScales with instancesOnly failed instance's shards pauseMediumHigh-scale multi-tenant schedulers
Leaderless with DB row locksBounded by DB lock throughputNo failover step; others keep claimingLow (if DB already exists)Quartz-style clusters, Airflow, moderate scale

What to say in the interview. "I'd partition the scheduling work by shard. Each scheduler instance holds leases on a set of shards from etcd, each lease carries a fencing token that is checked on every dispatch write, and a per-shard high-water mark lets a new owner resume without gaps. That gives horizontal scale, fast failover limited to a few shards, and no double dispatch from zombies. For a smaller system I'd start with a single leader and the same fencing, because it is simpler and the upgrade path to partitioning is just making the lease per shard."

5. At-least-once execution, end to end#

"At-least-once" is a promise that no scheduled execution is silently lost. Proving it means walking through every hand-off and asking: if the component holding the execution dies right now, who notices and who resumes?

Why not exactly-once? Because the scheduler cannot atomically "run the task" and "record that it ran". A worker may send the email and then crash before reporting success. From the outside, "crashed before sending" and "crashed after sending" are indistinguishable, so the platform must either retry (risking a duplicate) or not retry (risking a loss). A system that promises at-least-once chooses to retry. Exactly-once effects are achievable only when the task's side effect and the completion record can be made atomic or idempotent, which is the task's responsibility with platform help (Deep Dive 6). See Delivery Guarantees: At-Most, At-Least and Exactly-Once.

The hand-offs and their safety nets:

Hand-offFailureSafety net
Client to Job ServiceRequest times out; client unsure if job was createdIdempotency key on POST /jobs; client retries safely
Job Service to DBCrash after definition insert, before execution insertSingle transaction or conditional batch write; or a repair scan over jobs whose next_run_at has no execution row
DB to timer queue (watcher scan)Watcher crashes after reading, before loadingPer-shard high-water mark advanced only after loading; new owner rescans
Timer queue loses entries (Redis failover)Executions due soon vanish from the fast tierReconciler compares DB rows due in the past with status still scheduled or loaded and re-enqueues
Timer to dispatch queueDispatcher crashes mid-batchPop-and-push in one atomic step (Lua), or at-least-once publish with dedupe by execution id
Dispatch queue to workerWorker crashes before startingMessage visibility timeout expires; redelivered
Worker during executionWorker crashes or hangsHeartbeats stop; lease expires; reconciler requeues with attempt + 1
Worker to DB (completion)Crash after doing the work, before recordingLease expires, task re-runs: the duplicate that idempotency must absorb
Retry schedulingCrash between failure and scheduling retryRetry written durably to the execution table as part of handling fail

The pattern repeats: every component holds an execution only under a lease or a watermark that expires, and the durable store is always updated before the hand-off is acknowledged. The reconciler is the final backstop: a periodic job that queries for executions in suspicious states (scheduled in the past and never dispatched; running with an expired lease; queued for far too long) and pushes them back through the pipeline.

Visibility timeouts versus explicit leases. If the dispatch queue is SQS, its visibility timeout is a built-in lease: a received message is hidden for N seconds and reappears unless deleted. Workers extend it (ChangeMessageVisibility) while running. This is enough for short jobs. For long jobs, and for the platform to show "running on worker X since 10:00:03" to users, keep an explicit lease in the execution store too: lease_until and lease_token columns updated by heartbeats. The reconciler acts on the explicit lease; the queue's timeout is the second line of defence.

Ordering of acknowledgement. A worker must write succeeded before acknowledging the queue message. The reverse order (ack, then write) loses the execution entirely if the worker dies between the two. With "write, then ack", the worst case is a redelivery whose handler sees the row is already succeeded and acks without running.

Bounding duplicates. At-least-once does not mean "often twice". Duplicates arise only from specific races: a worker that completed but died before recording, a zombie worker after lease expiry, a redelivered message whose original was still running. With leases sized well above typical run time, heartbeats every few seconds and fencing tokens on completion, duplicates are rare (well below 0.1 percent of executions in a healthy system). But they are never zero, so the contract with task authors must say so explicitly.

6. Idempotency: turning at-least-once into effectively-once#

If an execution can run twice, the task must be written so that running it twice has the same effect as running it once. That is idempotency. The platform cannot make arbitrary code idempotent, but it can make it easy.

Give every execution a stable identity. The execution id is deterministic, hash(job_id, scheduled_at), and the platform passes it to the task on every attempt, along with the attempt number. Retries and duplicates of the same occurrence share the id; the next occurrence has a different one. Tasks use it as an idempotency key.

Patterns task authors use:

  1. Natural idempotency. "Set the user's status to inactive" or "write the report file to reports/2026-12-04.csv" (overwriting) are idempotent by construction. Prefer these designs: compute the output for the logical time and overwrite.
  2. Idempotency key passed downstream. Calls to payment providers and many APIs accept an idempotency key; passing the execution id means the provider deduplicates retries. Stripe's API, for example, supports an Idempotency-Key header on requests.
  3. Dedupe table. Before performing the side effect, insert (execution_id) into a table with a unique constraint, in the same transaction as the effect if the effect is a database write. A duplicate fails the insert and skips the work.
  4. Transactional outbox. If the task writes to its own database and must also emit an event or email, write the business change and an outbox record in one transaction; a relay sends the outbox record once (with its own dedupe). See Distributed Transactions: 2PC, Sagas and Outbox.
  5. Check-then-act with conditional writes. "Charge the invoice if it is unpaid": UPDATE invoices SET status = 'charging' WHERE id = :id AND status = 'unpaid' succeeds only once.

Fencing tokens at the side effect. A dedupe table stops two sequential duplicates. Two concurrent duplicates (a zombie and its replacement running at the same time) can still race. When the side effect is in a store you control, pass the lease token and reject writes from lower tokens, the same way the scheduler fences zombie leaders. Martin Kleppmann popularised this argument in his critique of using lease-based locks without fencing, and in Designing Data-Intensive Applications (2017): a lease alone never guarantees mutual exclusion, because the holder can pause past its expiry without knowing.

-- Task-side dedupe: perform the effect only once per execution
BEGIN;
INSERT INTO task_runs (execution_id, attempt, started_at)
VALUES (:execution_id, :attempt, now())
ON CONFLICT (execution_id) DO NOTHING;
-- if 0 rows inserted: another attempt already did (or is doing) the work -> exit
UPDATE accounts SET balance = balance + :credit WHERE id = :acct;
COMMIT;

What the platform should guarantee and document:

  • The execution id and attempt number are passed to every attempt.
  • The same execution id is never reused for a different scheduled time.
  • A completion is accepted only from the current lease holder.
  • Duplicates are possible; here are the conditions under which they occur.

Non-idempotent tasks. Some tasks genuinely cannot be made idempotent (sending an SMS through a provider without idempotency support). Options: accept rare duplicates (a duplicate reminder is usually harmless), add an at-most-once mode (do not retry after the task has started; record "started" durably first and never redeliver if found), or put a dedupe check as close to the side effect as possible. Offer at-most-once as an explicit per-job setting; never make it the silent default. See Idempotency and Safe Retries.

7. Retries, backoff and timeouts#

Failures come in two kinds, and treating them the same is the most common retry bug.

  • Transient failures will probably succeed if tried again: a 503 from a dependency, a network timeout, a database failover, a worker crash. Retry these.
  • Permanent failures will fail every time: invalid parameters, a missing file, a bug that throws on this input, a 400 or 404 from a dependency. Retrying wastes capacity and can cause harm (repeated partial side effects). Fail fast and surface the error.

Tasks report which kind they hit (fail(..., retryable = true | false)), and the platform applies sensible defaults when they do not (unknown exceptions retryable up to the limit; explicit validation errors not).

Exponential backoff with jitter. After attempt n fails, wait base × multiplier^(n-1), capped at a maximum, and randomise it. With base 10 s, multiplier 2 and cap 1 hour: 10 s, 20 s, 40 s, 80 s and so on. Without jitter, thousands of executions that failed together (because a shared dependency went down at 10:00:00) all retry together at 10:00:10, 10:00:30 and so on, creating synchronised waves that knock the recovering dependency over again. "Full jitter" picks a uniform random delay between 0 and the computed backoff; "equal jitter" keeps half the backoff fixed and randomises the other half. Both break up the waves. See Resilience Patterns: Timeouts, Retries and Circuit Breakers.

delay(n) = random_between(0, min(cap, base * multiplier^(n-1)))     # full jitter
attempt 1 fails at 10:00:00 -> retry in U(0, 10 s)
attempt 2 fails            -> retry in U(0, 20 s)
attempt 5 fails            -> retry in U(0, 160 s)
after maxAttempts          -> status Failed, alert owner, optional dead-letter

Retries are scheduled executions. A retry is simply a new attempt with a future scheduled_at, written durably and dispatched through the same timer path. This reuses all the machinery (look-ahead scans, timer queue, leases), survives crashes, and shows up in monitoring as "retrying, next attempt at 10:00:40". It also means the scheduler's capacity planning must include retry traffic, which can spike when a popular dependency fails.

Timeouts, more than one. Temporal's model is a good template because it separates timeouts by what they protect:

  • Schedule-to-start: maximum time an execution may wait in the queue before a worker picks it up. Exceeding it signals a starved or missing worker fleet; the platform can alert or fail the attempt.
  • Start-to-close: maximum run time of a single attempt. Exceeding it means the attempt is presumed stuck; it is failed and retried.
  • Heartbeat timeout: maximum gap between heartbeats. Much shorter than start-to-close for long jobs, so a dead worker is detected in seconds rather than at the end of a 2-hour run timeout.
  • Schedule-to-close: total budget across all attempts. "Retry for up to 1 hour, then give up" is a cleaner contract than "retry 7 times".

Retry budgets and circuit breaking. If a dependency is completely down, every execution that uses it will retry until exhausted, multiplying load by maxAttempts. Two protections: a retry budget per task queue or tenant (retries may be at most, say, 20 percent of executions; beyond that, back off harder), and a circuit breaker in the worker that fails fast while the dependency is unhealthy and lets retries resume when it recovers.

Dead-letter handling. An execution that exhausts its attempts goes to Failed, the owner is notified, and the full attempt history (errors, timings, worker ids) is kept for debugging. Offer a "re-run" button that creates a new attempt sequence with the same execution id, so idempotency keys still apply.

Poison executions. An execution that crashes the worker process itself (out-of-memory on a giant input, a segfault in a native library) looks like a worker failure, not a task failure, so naive accounting retries it forever and takes down a worker each time. Count lease expiries per execution as attempts, cap them, and quarantine the execution after a small number of worker crashes.

8. Worker heartbeats and failure detection#

When a worker holds an execution, the platform needs to know whether that worker is alive and making progress. Heartbeats are the mechanism; their tuning is the art.

What a heartbeat is. A periodic message from the worker, per execution or per worker, that says "I am alive and still working on executions X, Y and Z". The platform responds by extending each lease (lease_until = now + lease_duration) and can piggyback instructions such as "cancellation requested for Y". Temporal-style heartbeats can also carry progress details ("processed 40,000 of 100,000 rows"), which a retried attempt can read to resume from a checkpoint instead of starting over.

Per-execution versus per-worker heartbeats.

  • Per-worker: one heartbeat covers all executions on that worker. Cheap (5,000 workers at one beat per 5 s is 1,000 writes per second). But it only proves the process is alive, not that a particular execution is making progress; a single stuck thread holding one execution looks healthy.
  • Per-execution: each running execution beats separately, ideally from inside the task's progress loop. More expensive (50,000 running executions at one beat per 10 s is 5,000 writes per second) but detects stuck executions precisely. Write them to a fast lease store (Redis, or the queue's visibility extension) rather than the main database to keep load down.

A common hybrid: per-worker heartbeats for liveness, plus per-execution heartbeats only for long-running tasks that opt in.

Choosing the interval and timeout. With heartbeat interval h and timeout T (the lease duration):

  • Detection time for a crashed worker is between T minus h and T.
  • False positives happen if a healthy worker misses beats for longer than T (GC pause, network blip, CPU starvation). Setting T to about 3 to 5 times h tolerates a couple of missed beats.
  • Typical values: h = 5 to 10 s, T = 30 s for jobs that run for minutes; for jobs that run in seconds, rely on the start-to-close timeout and skip heartbeats.

The trade-off is classic: shorter timeouts detect failures faster but cause more false positives, which cause duplicate executions. For a scheduler that promises at-least-once, a false positive is not a correctness bug, but it is a cost and, for non-idempotent tasks, a visible duplicate. Adaptive detectors help in noisy environments: the phi accrual failure detector ("The φ Accrual Failure Detector", Hayashibara, Défago, Yared and Katayama, SRDS 2004) outputs a continuous suspicion level based on the observed distribution of heartbeat arrival times, so the threshold adapts to each worker's normal jitter. Cassandra and Akka use variants of it. See Heartbeats, Failure Detection and Gossip.

Zombies and fencing. A worker that was declared dead may not be dead. When its lease expires, the reconciler bumps the attempt number and lease token and requeues. If the old worker wakes up and heartbeats with the old token, the response tells it "lease lost; stop", and the worker should abort the task (cooperatively, by checking a flag between steps). If it never heartbeats and just tries to complete, the store rejects the stale token. Side effects that already happened are covered by idempotency (Deep Dive 6).

Graceful shutdown. Deployments restart workers constantly. A worker receiving a termination signal should stop polling for new work, finish or checkpoint running executions within a grace period, and release leases explicitly (so they are picked up immediately rather than after a timeout). Kubernetes gives pods a configurable termination grace period (30 seconds by default) for exactly this.

9. Scaling to 10,000 executions per second and surviving the top of the hour#

Scale has two parts here: the steady 10,000 per second, and the spikes at round times that can be orders of magnitude larger.

Scaling each tier independently.

TierLoad at 10,000 per secondHow it scales
Job ServiceJob creation rate (much lower than execution rate for recurring jobs)Stateless, behind a load balancer
Executions store~40,000 writes per second plus scansShard suffix per bucket; add nodes; separate scheduling and running state
WatchersScan 10,000 rows per second ahead of timePartition shards across instances
Timer queue10,000 inserts and 10,000 releases per secondShard by key (Redis) or rely on managed scale (SQS)
Dispatch queues10,000 messages per secondOne queue per task queue; partitioned queues for hot ones
Workers20,000 in flight at 2 s averageAutoscale per fleet on backlog and schedule-to-start latency
Lease and heartbeat store~5,000 to 10,000 writes per secondRedis cluster or the queue's own visibility mechanism

Each tier is horizontally scalable, and the boundaries between them are queues or partitioned stores, so a slowdown in one does not cascade into the others. See Pattern: Scaling Writes.

Batching. At this rate, per-item round trips dominate. The watcher reads partitions in pages of hundreds of rows and loads the timer queue in batches (SQS accepts up to 10 messages per SendMessageBatch call; Redis pipelining handles thousands per round trip). The dispatcher pops due timers in batches. Workers poll for up to N tasks at a time. Batching reduces request rates by 10 to 100 times with no loss of precision at the 2-second level.

The top-of-the-hour problem. Suppose 5 million jobs are scheduled for 0 0 * * * (midnight UTC). Firing them all within 2 seconds needs 2.5 million dispatches per second and as many workers ready at once, which no sane deployment provisions for one second a day. Strategies, combined:

  1. Admit it in the contract. The 2-second guarantee applies to the platform's dispatch capacity, with a published per-tenant rate. A tenant who schedules 5 million jobs for one instant gets them dispatched at their quota rate, starting on time.
  2. Encourage or apply jitter. Many schedules mean "roughly daily", not "exactly at 00:00:00". Offer a per-job jitter window ("anywhere in the first 10 minutes of the hour"), and default to it for jobs that do not need precision. A deterministic jitter, offset = hash(job_id) mod window, keeps each job's run time stable from day to day while spreading the herd evenly. Jenkins' H symbol in cron expressions (a hashed value) is a well-known example of exactly this idea.
  3. Pre-load early. Spikes are predictable from the execution table. Watchers can load the timer queue for midnight starting several minutes before, so the only work at 00:00:00 is release.
  4. Pre-scale workers for known spikes. The scheduler knows how many executions are due per task queue in each upcoming minute and can publish that as a scaling signal, so worker fleets grow before midnight rather than after the backlog appears.
  5. Fair dispatch across tenants. Without fairness, one tenant's 5 million midnight jobs delay every other tenant's one job. Dispatch per task queue through per-tenant sub-queues served round-robin or by weighted fair queuing, with per-tenant rate limits (token buckets). A small tenant's job then waits behind at most one batch of the big tenant's, not behind 5 million. See Rate Limiting and Throttling.

Autoscaling workers on the right signal. CPU is a poor signal for I/O-bound tasks. Better signals are the backlog per task queue and the schedule-to-start latency (how long ready executions wait for a worker). Scale out when schedule-to-start exceeds, say, 1 second; scale in slowly. Combine reactive scaling with the scheduler's forecast of due counts for the next 10 minutes, which is a rare luxury: a scheduler knows its future load exactly.

Backpressure. If workers cannot keep up, the backlog grows in the dispatch queue, which is fine for a while. If it grows past a threshold, the dispatcher should stop releasing low-priority work (batch reports) while continuing high-priority work (user-facing reminders). This is load shedding by priority, and it beats a uniform slowdown of everything. Each execution's priority comes from its job definition, and the fair dispatcher honours it within each tenant's share.

10. Task queues and worker routing#

Not every worker can run every task. Image resizing needs a GPU or lots of memory; payment tasks must run in a locked-down network; a team's tasks run in that team's deployment. The scheduler routes executions to the right fleet through named task queues.

The model. Each task is registered with a task queue name. When an execution fires, it is placed on its task queue. Worker processes declare which queues they poll. The platform never needs to know what the worker code does; it only matches executions to workers polling the right queue. This is exactly how Temporal works: a component called the Matching Service manages task queues and hands tasks to workers polling them. When a worker is already waiting in a long poll, the task is handed over directly in memory (a "sync match"); when none is waiting, the task is persisted and delivered later. Heavily used task queues are split into partitions served by different Matching instances, so one queue is not limited to one machine.

Why separate queues per kind of work:

  • Independent scaling. The email fleet scales on email backlog; the report fleet on report backlog.
  • Isolation. A flood of slow report jobs cannot starve fast email jobs of workers.
  • Security boundaries. Payment tasks run only on workers in the payment network, polling a queue only they can access.
  • Hardware fit. CPU-heavy, memory-heavy and GPU tasks go to fleets with the right instance types.
  • Ownership. Each team deploys and versions its own workers without coordinating with others.

Push versus pull to workers. Workers pull (long-poll) rather than having the scheduler push to them. Pull means the scheduler does not need to know which workers exist, how loaded they are or where they run; a worker asks for work only when it has capacity, which is natural backpressure. Push requires the scheduler to track worker capacity and to handle the case where a worker accepts a push and then fails. Pull with long polling gives near-push latency (a waiting poll returns within milliseconds of a task arriving) without those problems.

Versioning and routing. When a task's code changes incompatibly, run old and new worker versions side by side and route by version (a task queue per major version, or a version tag matched at poll time), draining the old version once its in-flight executions finish. Temporal and similar engines provide versioning features for this; a home-grown scheduler can implement it with versioned queue names.

Sticky routing. Some tasks benefit from running on the same worker as before (a warm cache, a local checkpoint). Temporal uses per-worker "sticky" queues for exactly this reason: a workflow's next task goes to the worker that has its state cached, falling back to the shared queue if that worker does not respond quickly. The same idea applies to long-running jobs that checkpoint locally.

11. Beyond single jobs: dependencies, DAGs and durable execution#

Interviewers often ask "what if jobs depend on each other?" Two families of systems answer it differently.

DAG schedulers (Airflow-style). A workflow is a directed acyclic graph of tasks: extract, then transform in parallel for three regions, then load, then email the report. Apache Airflow defines DAGs in Python code; each scheduled run of a DAG (a "DAG run") has a logical date (the data interval it covers), and each task in it is a task instance with its own state. The scheduler repeatedly evaluates which task instances have all upstream dependencies satisfied and queues them to executors (Celery workers, Kubernetes pods). Key ideas:

  • Dependency resolution: a task becomes runnable when all its upstream tasks succeeded (or according to a trigger rule such as "all done" or "one failed").
  • Logical time and backfills: because each run is tied to a data interval, re-running last Tuesday's pipeline is a matter of creating a DAG run for that interval. Turning on catchup creates runs for every missed interval since the start date.
  • Sensors: tasks that wait for an external condition (a file landing, a partition appearing), ideally in a deferrable mode that releases the worker slot while waiting.
  • Idempotent tasks writing to partitions keyed by logical date, so re-runs overwrite rather than duplicate.

Extending our design for DAGs: store the DAG definition with the job; when a DAG run's execution fires, create task-instance rows in a pending state; when a task instance completes, a dependency resolver checks its downstream tasks and enqueues those whose dependencies are now satisfied. Each task instance flows through the same queue, lease, heartbeat and retry machinery.

Durable execution engines (Temporal-style). Instead of a static graph, a workflow is ordinary code (charge card; if success, reserve stock; wait up to 3 days for shipment; send email). The engine records every step's result in an event history, and if a worker crashes, another worker replays the workflow code against the history to rebuild its state and continue from where it stopped. That requires workflow code to be deterministic (no direct clock reads, random numbers or I/O outside recorded activities), with side effects isolated in activities that are retried with their own policies. Timers ("wait 3 days") are durable: they are stored by the engine, and no worker sits idle waiting. Millions of workflows can be open at once, consuming storage but no worker capacity until something is ready to run, so compute scales with work that is ready, not with the number of open workflows. See Temporal and Workflow Engines and Pattern: Multi-Step Processes and Workflows.

When to use which. A scheduler with retries handles independent jobs. A DAG scheduler fits batch data pipelines with fixed structure and time-partitioned data. A durable execution engine fits long-lived business processes with branching, waiting and compensation (sagas). In an interview, say which one the question is really asking for. "Design a job scheduler like Airflow" is usually about the scheduling core in this case study, with DAGs as a follow-up.

Interesting internals worth knowing. A Temporal cluster has a Frontend service for API traffic, a History service that owns workflow state partitioned into a fixed number of history shards, a Matching service that manages task queues, and internal workers. Scaling the cluster means adding History instances (to share shard ownership), Matching instances (to serve task-queue partitions) and Frontend instances; adding application workers helps only when the backlog is work waiting to execute, not when workflow state updates are the bottleneck. This split between coordination capacity and execution capacity applies to our scheduler too: watchers, timer queue and stores are coordination; worker fleets are execution. Scale them separately and monitor them separately.

12. Cancel, reschedule, multi-tenancy and disaster recovery#

Cancel. Cancelling a job sets its status to cancelled and must stop future executions:

  • Scheduled but not loaded: mark the execution row cancelled; the watcher skips it.
  • Loaded in the timer queue: remove it if the timer tier supports deletion (Redis ZREM); otherwise rely on a status check at dispatch time.
  • Dispatched, not started: the worker checks status before starting (one extra read, or a cached "cancelled set" lookup).
  • Running: cancellation is cooperative. The next heartbeat response carries cancelRequested, and the task is expected to stop at a safe point. Forcible termination is a last resort, because killing a task mid-write can leave inconsistent state.

Reschedule and edit. Changing a cron expression or parameters updates the job and replaces the next execution: delete or cancel the materialised one (with the same caveats as cancel), compute the new next run time, insert a new execution. Use a job version number: each execution carries the version it was created from, and the dispatcher drops executions whose version is older than the job's current version. That one check resolves every race between edits and in-flight scheduling.

Pause and resume. Pausing marks the job paused; the next-occurrence calculator stops materialising, and any loaded execution is dropped at dispatch. Resuming applies the misfire policy to decide whether to run missed occurrences.

Multi-tenancy. Many teams or customers share the platform. Requirements:

  • Quotas: number of active jobs, executions per minute, maximum parameters size, maximum concurrent executions per tenant.
  • Fair dispatch (Deep Dive 9) and per-tenant task queues or sub-queues so one tenant's backlog does not delay another.
  • Isolation of code: if tenants supply their own worker code, they run their own workers polling their own queues; the platform never executes tenant code itself. If the platform must run tenant code (for example, a serverless "run this container on a schedule" product), it needs sandboxing like the Code Judge case study describes.
  • Access control: a tenant can see and manage only its own jobs; workers authenticate to the dispatch layer and can poll only authorised queues. See Authentication and Authorization.

Availability and disaster recovery.

  • Within a region, every tier runs across at least three availability zones: replicated store (Cassandra replication factor 3 with quorum writes, or a managed multi-AZ service), queues that replicate across zones, schedulers whose shard leases fail over across zones.
  • Across regions, the usual design is active-passive per tenant or per shard: each shard's scheduling runs in one home region at a time; the store replicates to a standby region; on regional failure, standby schedulers acquire the shard leases (from a coordination service that itself spans regions, or by an operator-controlled failover) and resume from the replicated high-water marks. Asynchronous replication means the last few seconds of state may be missing, which at-least-once semantics and the reconciler handle: some executions run twice, none are lost, assuming replication of the execution table is not behind by more than the time it took to detect the failure.
  • Avoid active-active scheduling of the same shard in two regions: without a cross-region consensus on ownership, every execution in that shard fires twice. If you need it, run the shard lease through a globally replicated consensus store (Spanner, or etcd stretched across regions, with the latency that implies).

See Disaster Recovery and Backups and Multi-Region and Global Data.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Hot partition for the current minuteThrottled writes and scans; jobs fire latebucket#shard partition key; separate scheduling state from running state; batch writes
Top-of-the-hour or midnight herdMillions due at once; dispatch backlog; late jobs for everyoneDeterministic jitter windows, pre-loading timers, pre-scaling from due-count forecast, per-tenant fair dispatch and quotas
Scheduler leader or shard owner diesIts shards stop firing until failoverLease expiry plus fast takeover; per-shard high-water mark; partition shards so only a fraction pause
Zombie scheduler after a pauseDouble dispatch of a shard's executionsFencing tokens on every dispatch write; conditional status transitions; dedupe by execution id
Timer tier loses state (Redis failover, bad deploy)Near-term executions vanish from the fast pathDB remains source of truth; reconciler re-enqueues past-due rows still in scheduled or loaded state
Worker crash mid-executionExecution stallsHeartbeats and leases; reconciler requeues with attempt + 1
Worker alive but paused (GC, partition)Duplicate execution after lease expiryLease token checks on heartbeat and completion; cooperative abort; idempotent tasks
Dependency outage causes mass failuresRetry storm multiplies load on a recovering serviceExponential backoff with full jitter, retry budgets, circuit breakers, schedule-to-close limits
Poison execution crashes workersRepeated worker loss, starved fleetCount lease expiries as attempts; quarantine after N crashes; alert with execution id
One tenant floods the systemOther tenants' jobs delayedPer-tenant quotas, token buckets, weighted fair queuing, per-tenant sub-queues
DST or time-zone rule changeJobs fire an hour early or late, or twiceStore IANA zone, compute UTC instants with a maintained tz database, explicit DST policy, recompute on tzdata updates
Execution history growthSlow monitoring queries, storage costTTL on hot tables, CDC to warehouse or object storage, per-tenant partitioned history indexes

What Interviewers Expect#

Mid-level#

  • Distinguishes task, job and execution, and captures the requirements: immediate, one-off and cron schedules; status monitoring; 10,000 executions per second; about 2 s precision; at-least-once.
  • Proposes a clear API (create job, get status and history) and a data model that separates job definitions from executions.
  • Draws a working design: a store of executions indexed by time, a scheduler that finds due work and puts it on a queue, and workers that execute and report.
  • Explains retries at a basic level and recognises that a worker can crash mid-job.

Senior#

  • Explains why executions are materialised one occurrence at a time and indexed by time bucket, and identifies the hot-partition problem and the shard-suffix fix.
  • Designs the two-tier dispatch (periodic look-ahead scans plus a precise timer queue) and compares delayed messages, Redis sorted sets and in-memory heaps or timing wheels.
  • Walks the at-least-once chain: leases, visibility timeouts, heartbeats, write-before-ack, reconciler; and explains why exactly-once execution is not achievable but idempotency gives effectively-once.
  • Covers retry policy properly: transient versus permanent, exponential backoff with jitter, multiple timeout types, dead-letter handling.
  • Handles cron details: time zones, daylight saving, misfire and overlap policies.

Staff+#

  • Compares leader-based, partitioned and leaderless (row-lock) schedulers with failover and throughput consequences, and uses fencing tokens to make zombies harmless.
  • Treats the top-of-the-hour herd and multi-tenant fairness as first-class problems with concrete mechanisms (deterministic jitter, forecasts, weighted fair dispatch, quotas).
  • Separates coordination capacity from execution capacity, routes work through named task queues to independently scaled fleets, and explains pull-based workers.
  • Discusses the extension to DAGs and durable execution, and when to adopt an existing engine (Airflow, Temporal) rather than building one.
  • Covers regional failure: active-passive per shard, replication lag versus duplicates, and why active-active scheduling of the same shard is dangerous.
Deep Dive: timing wheels and next-fire computation in codeShow

A hashed timing wheel. The wheel has size slots, each holding a list of timers; one slot per tick. A timer due in d ticks is placed in slot (cursor + d) mod size with a "rounds" counter floor(d / size) for delays longer than one revolution. Each tick, the cursor advances, and in the current slot every timer with rounds 0 fires; others have their rounds decremented. Insert and cancel are O(1); each tick costs O(timers in that slot).

type Timer = { id: string; rounds: number; fire: () => void };
 
class TimingWheel {
  private slots: Timer[][];
  private cursor = 0;
  constructor(private size: number, private tickMs: number) {
    this.slots = Array.from({ length: size }, () => []);
    setInterval(() => this.tick(), tickMs);
  }
  schedule(id: string, delayMs: number, fire: () => void) {
    const ticks = Math.max(1, Math.ceil(delayMs / this.tickMs));
    const slot = (this.cursor + ticks) % this.size;
    this.slots[slot].push({ id, rounds: Math.floor((ticks - 1) / this.size), fire });
  }
  private tick() {
    this.cursor = (this.cursor + 1) % this.size;
    const keep: Timer[] = [];
    for (const t of this.slots[this.cursor]) {
      if (t.rounds === 0) t.fire(); else { t.rounds--; keep.push(t); }
    }
    this.slots[this.cursor] = keep;
  }
}

With a 100 ms tick and 600 slots, one revolution is a minute; a 5-minute look-ahead window means timers carry up to 4 rounds. A hierarchical wheel instead keeps, say, a 100 ms wheel of 10 slots, a 1 s wheel of 60 slots and a 1-minute wheel of 60 slots; a timer goes into the coarsest wheel that can hold it and cascades into finer wheels as its time approaches, so no slot accumulates many not-yet-due timers. This is the structure described by Varghese and Lauck in 1987, and its O(1) insert and expiry are why high-throughput systems with millions of timeouts (network stacks, Kafka's delayed operations) prefer it over heaps.

Next fire time for a cron expression. Correct implementations are fiddly; here is the shape of the algorithm, operating in the job's local time zone:

next_fire(expr, tz, after):
  t = to_local(after, tz) + 1 minute, seconds set to 0
  for up to 5 years of iterations:
    if month(t) not in expr.months:   t = first minute of next allowed month; continue
    if not day_matches(expr, t):      t = first minute of next day;          continue
    if hour(t) not in expr.hours:     t = first minute of next allowed hour; continue
    if minute(t) not in expr.minutes: t = next allowed minute;               continue
    candidate = to_utc(t, tz)          # apply DST policy:
                                       #   nonexistent local time -> shift forward
                                       #   ambiguous local time   -> first occurrence
    return candidate
  error "schedule never fires"
 
day_matches: if both day-of-month and day-of-week are restricted, classic cron uses OR;
             otherwise use whichever is restricted.

Each continue jumps forward by a whole unit and resets lower fields, so even sparse schedules converge in a few dozen iterations. Production systems use well-tested libraries (cron-utils, croniter, the scheduler built into the language's ecosystem) and add property-based tests around DST boundaries.

Deep Dive: numbers worked throughShow

Look-ahead scan cost. With 64 shards, minute buckets and a 5-minute window rescanned every minute, each scan reads 5 buckets × 64 shards = 320 partitions, but only one new minute's worth of rows is new each time. To avoid rereading, a watcher tracks its high-water mark and reads only [mark, now + 5 min): one new minute per scan, 64 partitions, 600,000 rows at peak (10,000 per second × 60 seconds). Spread across, say, 8 scheduler instances, each reads 75,000 rows per minute, about 1,250 rows per second, trivial for any of the candidate stores.

Timer queue memory. At 10,000 per second, a 5-minute window holds 3 million timers. In Redis, a sorted-set member with a 16-byte id costs roughly 80 to 100 bytes including skip-list overhead, so about 300 MB, sharded over a few nodes. An in-memory timing wheel in Java with a small object per timer is similar, a few hundred MB spread across scheduler instances.

Failover gap. A shard owner with a 10 s lease, renewing every 3 s, fails. Takeover happens 7 to 10 s later; the new owner reloads its window, which takes about one second for its shards. Executions in those shards due during the gap fire up to about 11 s late. With 64 shards over 8 instances, one failure delays one-eighth of executions for about 11 s. To meet 2 s even during failover, use warm standbys per shard: a second instance pre-loads the same window without dispatching and takes over the moment it acquires the lease, with the dispatch dedupe by execution id absorbing any overlap.

Duplicate rate. Suppose 0.01 percent of worker processes die each minute (a deploy or crash rate) and an average execution runs 2 seconds. The fraction of executions interrupted is about 0.01 percent × 2/60, roughly 3 in a million. Even allowing for zombie scenarios and redelivery races, duplicates should be on the order of 1 in 100,000 or rarer in a healthy fleet. They are rare enough to be surprising and common enough, at 260 million executions a day, to happen hundreds to thousands of times daily. Hence the need for idempotency.

Heartbeat load. 20,000 in-flight executions; only the 10 percent that run longer than 30 s heartbeat, every 10 s: 200 writes per second. Per-worker heartbeats from 400 workers every 5 s: 80 per second. Negligible compared with the state-change writes.

Retry amplification. If a dependency used by 20 percent of executions fails for 10 minutes, with maxAttempts = 5 and backoff 10, 20, 40, 80 s, each affected execution makes up to 5 attempts within about 2.5 minutes. Peak load on the dependency is up to about 5 times normal at the start of the outage. A retry budget of 20 percent caps retries at 2,000 per second for the platform, protecting the dependency and the scheduler.

Storage over time. 260 million executions per day × 400 bytes ≈ 104 GB per day. With 30-day TTL and replication factor 3: about 9.4 TB of disk in the hot store. Compressed in columnar form for long-term history (roughly 10 to 20 times smaller), a year is about 2 to 4 TB in object storage.

Deep Dive: the small-scale version on one PostgreSQL databaseShow

Most teams do not need 10,000 executions per second. Knowing when the full design is overkill is a staff-level signal. A single PostgreSQL primary with a hot standby comfortably handles hundreds to a few thousand job state changes per second. That covers the background-work needs of most products. Several popular libraries are built exactly this way, for example Oban in Elixir, pg-boss in Node.js, and Que and GoodJob in Ruby. The design collapses to one table and three queries.

CREATE TABLE execution (
  id            uuid PRIMARY KEY,
  job_id        uuid NOT NULL,
  queue         text NOT NULL,
  scheduled_at  timestamptz NOT NULL,
  status        text NOT NULL DEFAULT 'scheduled',
  attempt       int  NOT NULL DEFAULT 0,
  lease_token   bigint,
  lease_until   timestamptz,
  payload       jsonb
);
CREATE INDEX due_idx ON execution (queue, scheduled_at)
  WHERE status = 'scheduled';
 
-- Worker claims up to 10 due executions; concurrent workers skip each other's rows
UPDATE execution e
SET status = 'running', attempt = attempt + 1,
    lease_token = nextval('lease_seq'), lease_until = now() + interval '60 seconds'
WHERE e.id IN (
  SELECT id FROM execution
  WHERE queue = $1 AND status = 'scheduled' AND scheduled_at <= now()
  ORDER BY scheduled_at
  LIMIT 10
  FOR UPDATE SKIP LOCKED)
RETURNING e.id, e.lease_token, e.payload;
 
-- Reaper: return expired leases to the queue (run every few seconds)
UPDATE execution SET status = 'scheduled', lease_token = NULL
WHERE status = 'running' AND lease_until < now();

Why it works. FOR UPDATE SKIP LOCKED lets many workers query the same index at once. Each worker locks the rows it picks and skips rows another transaction has already locked, so workers never block each other or take the same row. The partial index covers only rows waiting to run, so it stays small even when the table holds millions of finished rows. Completion is a conditional update: UPDATE ... SET status = 'succeeded' WHERE id = $1 AND lease_token = $2. That gives the same token fencing as the distributed design. Workers learn about new work by polling every second or so, or through LISTEN/NOTIFY for a low-latency wake-up.

A transactional bonus. Because jobs live in the same database as application data, a request can insert its business row and its follow-up job in one transaction. That is the transactional outbox for free: no job is ever enqueued for a transaction that rolled back, and no committed transaction misses its job. Distributed queues cannot offer this without an outbox relay.

Where it stops scaling.

  • Dead tuples. Every state change rewrites a row, and PostgreSQL's MVCC leaves the old version behind until vacuum cleans it up. High-churn job tables need aggressive autovacuum settings and short-lived rows. Delete or archive finished executions, or partition by day and drop old partitions.
  • One primary limits writes. In practice the ceiling is somewhere in the low thousands of claims per second, depending on hardware and batch size.
  • Polling cost. Thousands of idle workers polling every second make a noticeable load; a small dispatcher that claims in batches and hands work out can help.
  • Long transactions. A long-running transaction elsewhere in the database stops vacuum from cleaning up, so the job table bloats.

When to graduate. Move to the full design when you exceed the single-primary write ceiling, need multi-region operation, or need strict isolation between many tenants. Interviewers reward candidates who say: "I would start here, and these are the metrics that would tell me to move." See PostgreSQL in Practice.

Redis-based libraries take the other common path, for example Sidekiq in Ruby, BullMQ in Node.js, and Celery with a Redis broker in Python. Delayed jobs sit in a sorted set scored by run time and ready jobs in lists. Durability depends on Redis persistence settings, so a failover can lose recently enqueued jobs unless the library adds its own safeguards. They are fast and simple, and fit work where an occasional loss after a crash is acceptable or can be detected and repaired.

Deep Dive: priorities, preemption and resource-aware placementShow

A time scheduler decides when work becomes runnable. A cluster scheduler decides where it runs and on what resources. Interviews about job schedulers often drift into the second question, so it helps to know how the two fit together.

Priorities. Give each task queue, or each execution, a priority class such as critical, normal or batch. Dispatch serves higher classes first. Strict priority can starve lower classes forever, so add one of these:

  • Aging: raise an execution's effective priority the longer it waits.
  • Weighted shares: for example critical 70 percent, normal 25 percent, batch 5 percent of dispatch slots. Lower classes can use whatever capacity the higher ones leave idle, and are guaranteed their minimum share otherwise.

Weighted fair queuing comes from network packet scheduling. Applying it per tenant inside each class gives two-level fairness: first across priority classes, then across tenants within a class.

Preemption. When critical work arrives and the fleet is full, the platform can stop batch executions to free capacity. Preemption only works if tasks expect it:

  • They must be idempotent or checkpointing, recording progress in heartbeats.
  • The worker gets a cancellation signal and a grace period, for example 30 seconds, to save its progress.
  • The preempted execution goes back on the queue without spending a retry attempt. Being preempted is not the task's fault.

Cloud spot or preemptible instances raise the same issue at the machine level. Batch fleets on spot capacity need the same checkpoint-and-resume discipline.

Resource-aware placement. If tasks declare resource needs (CPU, memory, GPU, a licence or another scarce token), the dispatcher must match each task to a worker with that capacity free. The options:

  • Simple: separate task queues per resource profile, each with its own fleet. This is what the main design does.
  • General: workers report their free capacity when they poll, and the matcher gives each worker only tasks that fit. Fitting tasks onto workers is a bin-packing problem; greedy heuristics such as best-fit work well in practice.
  • Delegate: hand placement to a cluster scheduler. Each execution becomes a Kubernetes Job or a pod with resource requests, and the Kubernetes scheduler filters and scores nodes. The time scheduler stays responsible only for timing, retries and status.

Google's Borg, described in "Large-scale cluster management at Google with Borg" (Verma et al., EuroSys 2015), combined priorities, quotas, preemption and bin-packing at very large scale. It also showed the payoff of mixing latency-sensitive and batch work on shared machines: batch work fills the gaps.

Concurrency limits as a resource. Many real limits are not CPU but downstream capacity: "at most 5 concurrent runs against this partner's API" or "one migration per database at a time". Model each limit as a named semaphore. Store it in Redis with a lease per slot, or in the database as a count with conditional updates. Workers acquire a slot before running and release it when done, and a slot whose lease expires frees itself. Overlap policies such as "forbid concurrent runs of this job" are a special case: a semaphore of size 1 keyed by job id.

Deep Dive: testing a schedulerShow

Scheduler bugs show up rarely, at awkward times, and in the presence of failures. Ordinary unit tests miss most of them. Four techniques catch what matters.

1. Inject the clock. Never call the system clock directly in scheduling logic. Pass in a clock interface, so tests can jump forward by an hour in microseconds and stop time at the exact boundary where bugs live. Test cases worth having:

  • Executions due exactly at the end of a scan window.
  • Cron expressions across month ends and leap days, for example 0 0 29 2 *.
  • Both kinds of daylight-saving transition, in several time zones.
  • A worker whose lease expires one millisecond before its completion arrives.

2. Check the cron parser against a reference. Generate random cron expressions and random start times. Compare your next-fire results with a mature implementation, and investigate every disagreement. Parser and next-fire bugs are among the most common scheduler defects in practice, because the edge cases (day-of-month or day-of-week semantics, step values, ranges that wrap) are subtle.

3. Check properties, not examples. Write the guarantees down as properties that can be checked over a full history of events:

  • No lost executions: every execution created and acknowledged before time T reaches a terminal state by T plus its schedule-to-close timeout.
  • Bounded lateness: with no injected failures, dispatch lag stays within 2 s.
  • Fencing: no completion with a stale token is ever accepted, and no two workers are recorded as holding the same live lease.
  • Single fire for overlap-forbidden jobs: no two runs of such a job overlap in time.

4. Simulate and inject faults. Run the scheduler, timer tier, database stub and workers in one process, driven by a seeded random scheduler. Inject faults: kill processes, pause them (to emulate GC stalls), drop and reorder messages, fail writes, and skew clocks. After each run, check the properties. When a seed fails, the same seed replays the bug exactly. FoundationDB's team is well known for building this kind of deterministic simulation testing into their development process. Jepsen-style testing (Kyle Kingsbury's work) does the same against real deployed clusters: it partitions networks and checks the recorded history.

In staging and production:

  • Canary jobs: synthetic jobs scheduled every minute in every shard that record their actual start time. They measure dispatch lag continuously, from the user's point of view.
  • Game days: kill a scheduler instance, fail over the timer tier, and deploy a crashing worker. Confirm that alerts fire and that recovery matches the expected bounds, such as the roughly 11 s failover gap.
  • Shadow reconciliation: periodically compare "executions that should have fired", recomputed from job definitions, with "executions that did fire". Any gap is a bug, even if no customer has noticed yet.
Deep Dive: security and safe multi-tenancyShow

A scheduler runs other people's work on a timer, often with powerful credentials. That makes it a tempting target.

Payloads and secrets.

  • Encrypt payloads at rest; they often hold customer data.
  • Never store raw secrets in job definitions. Store a reference to a secret manager entry, and have the worker resolve it at run time with its own identity. Rotating the secret then needs no job edits, and leaked execution history does not leak credentials.
  • Redact payloads in logs and in the monitoring API, according to tenant settings.

HTTP targets and webhooks. If jobs can call arbitrary URLs, the scheduler is a server-side request forgery (SSRF) risk: a tenant could point a job at internal metadata endpoints or private services. Defences:

  • Resolve hostnames and block private, loopback and link-local address ranges.
  • Make outbound calls from an isolated egress tier with no access to internal networks.
  • Re-check the address after redirects.
  • Sign each outbound request with an HMAC over the body and a timestamp, so receivers can verify it came from the scheduler and reject replays.

Authorisation. Scope every API call to a tenant. A job's worker identity should be able to run only that tenant's task types, and the worker poll API should authenticate fleets so one tenant's worker cannot poll another tenant's queue. Audit every job create, edit, pause and delete with the actor and the time. A malicious "run every minute" edit to a billing job is an incident you will want to trace. See Authentication and Authorization.

Resource abuse. Quotas cover:

  • Jobs per tenant.
  • Minimum schedule interval, for example at most once per minute on standard plans.
  • Payload size.
  • Concurrent executions.
  • Retry volume.

Together they stop accidental and deliberate denial of service. A tenant who creates 10 million jobs due at the same second should hit a creation-rate limit long before they reach the timer tier. Per-tenant fair dispatch then keeps their backlog from delaying anyone else.

Untrusted code. If the platform runs customer-supplied code rather than calling customer endpoints, isolation becomes the dominant concern. Use per-execution sandboxes such as gVisor or Firecracker microVMs, no ambient credentials, and network egress controls. The Code Judge case study covers these techniques in depth.

Deep Dive: how real schedulers are builtShow
  • Unix cron. One daemon per machine reads crontabs and wakes each minute. No durability of missed runs (if the machine is off at the scheduled minute, the job simply does not run; anacron exists to catch up on machines that are not always on), no retries, no distribution. Everything in this case study is about adding what cron leaves out.
  • Quartz (Java). A library scheduler embedded in applications. In clustered mode, several application instances share a relational database job store; instances coordinate through database locks so each trigger fires on exactly one node, and misfire instructions decide what happens to triggers missed while all nodes were down. It is the leaderless-with-row-locks design at moderate scale.
  • Kubernetes CronJob. A controller (running in the leader-elected controller manager) creates a Job object for each scheduled time; the Job creates pods. Notable options map directly to ideas here: concurrencyPolicy (Allow, Forbid, Replace) for overlap, startingDeadlineSeconds for misfires, and a time-zone field in newer versions. The documentation warns that a CronJob can occasionally create two Jobs or none for a scheduled time, so jobs should be idempotent: the at-least-once lesson in official form.
  • Apache Airflow. DAG-oriented batch orchestration. The scheduler parses DAG files, creates DAG runs for data intervals, and queues runnable task instances to an executor (Celery, Kubernetes and others). Since version 2.0, several schedulers can run at once, coordinating through row-level locks in the metadata database, which removed the single-scheduler bottleneck and single point of failure.
  • Google's distributed cron. As described in "Reliable Cron across the Planet" (ACM Queue, 2015), the service replicates its state with Paxos; a single elected leader launches jobs and records each launch's start and completion in the replicated log, so that after a failover the new leader knows which launches were in flight. The article emphasises that most cron jobs should be idempotent or safe to skip, and that the scheduler must decide explicitly what to do with launches whose outcome is unknown.
  • Temporal. Durable execution with task queues, workers that long-poll, activity heartbeats with progress details, separate schedule-to-start, start-to-close and heartbeat timeouts, retry policies, and built-in schedules (a cron-like feature implemented as workflows). Its architecture splits coordination (Frontend, History, Matching) from execution (your workers).
  • Cloud schedulers. Managed services such as AWS EventBridge Scheduler and Google Cloud Scheduler accept one-off and cron schedules with time zones, invoke targets (functions, queues, HTTP endpoints) with retry policies and dead-letter queues, and state at-least-once delivery. They are the right default when you do not need custom routing or worker fleets.

The common threads: durable schedules, explicit misfire and overlap policies, leases and fencing for the scheduler role, pull-based workers, and at-least-once with idempotent tasks.

Deep Dive: failure walkthroughsShow

1. A shard owner pauses for 40 seconds. Scheduler B owns shards 22 to 42 and hits a long GC pause. Its leases (10 s) expire; scheduler C acquires them with new fencing tokens and resumes from the high-water marks, reloading the next 5 minutes of timers. B wakes up, still holding timers in memory, and tries to dispatch the 10:00:30 batch. Every dispatch write (status scheduled to queued) carries B's old token and is rejected; the lease-renewal response tells B it has lost the shards, and B drops its in-memory timers. Result: executions in those shards fired up to about 11 seconds late, none twice.

2. Redis, used as the timer tier, loses a shard. A Redis primary fails and its replica is promoted, missing the last second of writes, about 10,000 timers. The reconciler, running every 30 seconds, finds rows whose scheduled_at is past, status still loaded, and no dispatch record, and pushes them straight to the dispatch queue. They run up to about 30 seconds late. To tighten this, reconcile more frequently for the most recent minute, or have watchers re-verify the last minute's loads after any timer-tier failover event.

3. A payment provider has a 15-minute outage. Payment-task executions start failing with 503s. Retries back off with jitter; the circuit breaker in the payment workers opens after a burst of failures and fails fast, recording a retryable failure without calling the provider. Schedule-to-close (1 hour) is not reached. When the provider recovers, half-open probes succeed, the breaker closes, and the jittered retries drain the backlog over a few minutes without a synchronised wave. Idempotency keys (the execution id) passed to the provider mean that the few requests that actually succeeded before timing out are not charged twice.

4. The midnight herd meets a deploy. At 23:58, a bad worker deploy for the reports fleet starts crashing on startup. At 00:00, 2 million report executions become due. Schedule-to-start latency climbs; the autoscaler adds instances, which also crash. Detection: crash-looping pods and schedule-to-start alerts. Response: roll back the deploy; meanwhile the executions sit safely in the dispatch queue (leases are not held by crashed workers because they never polled successfully). After rollback, workers drain the backlog at the fleet's rate. Misfire policies decide whether very late runs still execute; the logical time passed to each execution means the reports still cover the correct day.

5. Daylight saving in a region where the rules changed. A government announces, with a few weeks' notice, that it will not observe DST this year. Jobs in that zone would fire an hour off. Response: ship the updated time-zone database to the Job Service and schedulers, then run a migration that recomputes next_run_at and the materialised next execution for every job in that zone. Because only one occurrence per job is materialised, this touches one row per job, not a year of rows.

6. A regional outage. The primary region fails. The execution table has been replicating asynchronously to the standby region with about 1 second of lag. Operators (or automation with a strict quorum) fail over shard leases to standby schedulers, which resume from replicated high-water marks. Executions dispatched in the last second before the failure may be dispatched again (duplicates absorbed by idempotency); executions created in that last second may be missing (clients retrying with idempotency keys recreate them). The scheduler meets at-least-once for everything that was acknowledged to clients more than the replication lag before the failure; that bound is the real recovery point objective and should be stated.

Deep Dive: a 45-minute interview plan and common variantsShow
MinutesWhat to do
0 to 5Define task, job, execution. Requirements: immediate, one-off and cron; monitor status; 10,000 per second; 2 s precision; at-least-once.
5 to 10Entities, API (create job, get status and history), data model separating jobs from executions.
10 to 20High-level design: time-bucketed executions table, watcher plus timer queue, dispatch queues, workers with leases, status indexes.
20 to 28Deep dive: precision and scale. Hot partitions and shard suffix; two-tier dispatch; partitioned schedulers with fencing.
28 to 38Deep dive: at-least-once. Leases, heartbeats, write-before-ack, reconciler, idempotency keys; retries with backoff and jitter.
38 to 45Top-of-the-hour herd, tenant fairness, failure modes; extensions (DAGs, cancel, multi-region).

Variants and what changes:

  • "Design a delayed message queue" or "schedule a notification for later". Same two-tier design without cron; the timer tier is the heart of it. See also the Notification System case study.
  • "Design Airflow". Add DAG definitions, a dependency resolver, logical dates and backfills (Deep Dive 11); executors map to our worker fleets.
  • "Design a distributed cron for internal infrastructure". Lower scale (thousands of jobs) but stronger correctness expectations; a single leader with fencing, replicated state and explicit handling of unknown-outcome launches (the Google design) is often the best answer.
  • "Design a rate-limited webhook retry system". Executions are deliveries; retries with backoff and jitter, per-destination rate limits and circuit breakers dominate.
  • "Design a ride-reminder or appointment-reminder system". One-off jobs at user-chosen times, heavy at round times; emphasise jitter tolerance, cancellation when the appointment changes, and idempotent notification sending.
  • "Run user-supplied containers on a schedule". Add sandboxing and resource quotas for untrusted code, as in the Code Judge case study.
Deep Dive: observability and SLOsShow

SLOs:

  • 99 percent of executions dispatched within 2 s of their scheduled time (measured as dispatched_at - scheduled_at), excluding executions delayed by their own tenant's quota.
  • 99.99 percent of executions reach a terminal state (succeeded, failed after retries, cancelled); none remain stuck in a non-terminal state for longer than their schedule-to-close timeout plus a margin.
  • Status visible in the monitoring API within 5 s of any state change.

Key metrics (see Observability: Logs, Metrics and Traces):

  • Dispatch lag distribution per shard and per task queue: the single most important health signal. A rising tail on one shard points to its owner.
  • Schedule-to-start latency per task queue: rising values mean a worker fleet is under-provisioned or broken.
  • Backlog per task queue and per tenant.
  • Reconciler actions per minute, by reason (lease expired, never dispatched, stuck queued). A healthy system has a low, steady rate; a spike is an incident in some tier.
  • Duplicate indicators: completions rejected for stale tokens, dispatch writes rejected for stale fencing tokens.
  • Retry rate and failure reasons per task; retry budget consumption.
  • Shard lease churn: frequent ownership changes indicate unhealthy schedulers or a flapping coordination service.
  • Heartbeat gaps distribution, to tune timeouts based on reality.

Tracing. Carry a trace id from job creation through each execution's dispatch, lease, run and completion, so "why did my 10:00 job start at 10:00:09?" can be answered by looking at one trace with timestamps for scan, timer, dispatch and poll.

Audit trail. Every state transition is an event (execution id, from, to, actor, token, timestamp) appended to a log. It powers the monitoring UI, debugging and post-incident analysis, and it is the natural input for change-data-capture into a warehouse.

Load testing. Synthetic tenants that create millions of jobs targeting the same minute validate jitter, fairness and pre-scaling before real customers do. See Capacity Planning and Load Testing.

Key Takeaways#

  • Separate tasks, jobs and executions. Store job definitions once; materialise only the next occurrence of each job as an execution indexed by time. That makes "what is due now?" a narrow range read and keeps edits cheap.
  • Index by time bucket plus shard. A time-only partition key creates a hot partition that follows the clock; a shard suffix spreads the load and gives the scheduler tier its unit of ownership.
  • Two tiers for precision. Periodic look-ahead scans of the durable store feed a fast timer queue (delayed messages, a Redis sorted set or a timing wheel) that fires within milliseconds. The database stays the source of truth; the timer tier is rebuildable.
  • Partition the scheduler and fence it. Per-shard leases from etcd or ZooKeeper give horizontal scale and small failover blast radius; fencing tokens and conditional state transitions make paused or partitioned zombies harmless. A single leader with the same fencing is a fine starting point.
  • At-least-once is a chain of leases. Every hand-off holds work under a lease or watermark that expires; durable writes come before acknowledgements; a reconciler catches anything that falls through.
  • Idempotency makes duplicates harmless. Deterministic execution ids, idempotency keys passed downstream, dedupe tables, outboxes and fencing at the side effect turn at-least-once into effectively-once.
  • Retry well. Classify transient versus permanent failures, back off exponentially with jitter, use separate schedule-to-start, start-to-close, heartbeat and schedule-to-close timeouts, and cap retries with budgets and circuit breakers.
  • Heartbeats detect dead workers; tokens handle the ones that are not really dead. Tune interval and timeout to balance detection speed against false positives, and abort cooperatively when a lease is lost.
  • Plan for the herd and for tenants. Deterministic jitter, pre-loading, forecast-driven pre-scaling, weighted fair dispatch and quotas keep the top of the hour from hurting everyone.