Design a Scalable Scheduler for Ad-Hoc and Periodic Tasks

Medium · System Design · Software Engineer · Technical Screen

Prompt

Architect a distributed task scheduling service that accepts workload definitions from clients, dispatches executions onto a shared fleet of worker hosts when their scheduled time arrives, and tracks every execution until completion.

Unless narrowed during the discussion, support the following core capabilities:

  • Trigger modes: Clients can submit a workload to execute right away, run once at a designated future timestamp, or fire repeatedly on a calendar pattern such as a cron schedule.
  • Execution visibility: Every individual invocation (run) exposes queryable lifecycle state, exit status, attempt history, and captured standard output/error streams.
  • Lifecycle management and retries: Unsuccessful runs retry automatically under configurable per-workload backoff policies. Callers can suspend, resume, modify, or remove a workload definition and abort an active run.

Assumptions to clarify or state explicitly:

  • Treat each workload payload as an opaque execution unit—such as a container image digest with command-line flags—so the platform governs when and where runs execute rather than their internal application logic.
  • Operating parameters are intentionally left open for you to scope: total active schedules, daily execution volume, top-of-hour or midnight traffic spikes, start-time precision targets, execution durations (from seconds to many hours) with timeouts, delivery semantics (at-most-once vs. at-least-once paired with idempotent user code), priority tiers, tenant quotas, workflow dependencies, and catch-up rules when recurring slots are missed during control-plane downtime.

Scope & Expectations

  • Requirements & capacity sizing: State explicit scale, latency, and delivery-guarantee assumptions, and translate them into storage footprints, database write rates, and worker-slot concurrency estimates.
  • APIs, data model, and architecture: Define the client management endpoints, internal worker execution protocol, database schema, run state machine, and core control-plane and worker-plane components.
  • Scalable due-time discovery & duplicate prevention: Show how due schedules are located efficiently across millions of stored jobs without full-table scans, and how concurrent or recovering nodes avoid launching duplicate runs.
  • Failure handling, traffic spikes, and missed slots: Cover worker heartbeat loss and network partitions, retry accounting, sharp calendar bursts, and post-outage catch-up behavior.

Step-by-step walkthrough

  1. Clarify requirements and scope

    Two engineering problems sit at the heart of a distributed job scheduler: 1. Pinpointing due work without full scans: With millions of stored schedules, how do we pull only the handful of tasks firing this second instead of sweeping the whole database on every tick? 2. Guaranteeing crash safety without duplicate launches: Control-plane pods, dispatchers, network links, and worker hosts can stall or die unexpectedly. How do we prevent a single scheduled slot from starting twice and recover runs whose host vanishes mid-execution?

    Functional requirements

    • Flexible triggers: Clients can submit a job to run immediately (now), once at a future timestamp (at), or repeatedly on a cron schedule (a compact text pattern like "0 0 * * *" specifying repeating calendar times in a chosen time zone).
    • Run tracking and logs: Each execution of a job is a run with queryable status, exit code, attempt history, and streaming stdout/stderr logs.
    • Lifecycle controls and retries: Failed runs retry automatically according to a per-job policy. Clients can pause, resume, update, or delete a job, trigger an ad-hoc run, or cancel an in-flight run.

    Stated scale and delivery assumptions

    • When vs. where: Primary focus is when jobs run across a pool of homogeneous worker slots; matching heterogeneous CPU/RAM/GPU shapes is covered as a follow-up extension.
    • Scale and burstiness: 10M active job definitions (8M recurring cron jobs, 2M future one-off jobs) producing 50M runs/day, with sharp calendar spikes: ~200,000 runs at the top of every hour (:00) and 1,000,000 runs at midnight UTC.
    • Start-time precision: Start within 2 seconds (p99) of the scheduled timestamp whenever free worker slots exist.
    • Delivery guarantee: At-least-once execution with at most one live attempt at a time. True end-to-end "effectively-once" execution requires collaboration with user code: we inject RUN_ID, ATTEMPT, and SCHEDULED_AT so jobs can be idempotent (safe to run more than once without duplicating side effects). Non-idempotent jobs can set on_worker_lost: "fail" for at-most-once execution.
    • Durations, priorities, and missed runs: Runs last from 1 second to 24 hours (median 20s, mean 60s) with enforced timeouts. Support 3 priority tiers (high, normal, low), per-tenant concurrency caps, and explicit catch-up policies (run_once, skip, run_all) if a shard was down when slots came due.
  2. Back-of-the-envelope numbers

    Let's size storage, worker fleet capacity, and database write rates before drawing boxes. To size the worker fleet, we use Little's Law (a queuing rule stating that the average number of concurrently active items equals average arrival rate multiplied by average duration):

    Storage
      Job definitions      10M active jobs x ~2 KB (spec + cron + retry policy) = ~20 GB
      Run metadata         50M runs/day -> 50,000,000 / 86,400 s = ~580 runs/sec average
                           50M runs/day x ~1 KB = ~50 GB/day (~1.5 TB for 30 days of hot history)
      Task logs            50M runs/day x ~20 KB avg = ~1 TB/day -> streamed to object storage (S3/GCS)
    
    Worker fleet
      Average busy slots   580 runs/sec x 60 sec mean duration = ~34,800 (~35k) concurrent runs
      Provisioned fleet    6,250 worker hosts x 16 container slots = 100,000 total slots
      Max slot turnover    100,000 slots / 60 sec mean duration = ~1,670 run completions (and starts)/sec
    
    Database writes
      Lifecycle writes     create run + advance trigger + claim + started + finished + attempt = 6 writes/run
      Steady-state rate    (580 runs/s x 6) + (35,000 active runs / 10s lease renewal) = ~7,000 row writes/s
      Midnight naive spike 1M run inserts + 1M trigger updates in 1 second = ~2,000,000 row writes/s (300x!)
      Midnight smoothed    Same 2M writes spread across a 60-second lookahead = ~33,300 writes/s total
      Across 64 shards     ~110 writes/s/shard steady; ~520 writes/s/shard avg during the 23:59 minute
    

    Three architectural rules fall straight out of these numbers: 1. Never scan definitions: Reading 10M rows every second to find ~580 due jobs is wasteful; we must index only the next fire timestamp. 2. Pre-create runs 60 seconds ahead: Spreading the midnight run-creation burst over 23:59:00–23:59:59 turns a 2M-writes/sec cliff into a gentle ~520-writes/sec/shard workload. 3. Worker slots bound burst latency: Even if all 1M midnight runs are queued instantly at 00:00:00, only 100k - 35k = 65k worker slots are free; draining the remaining 935k runs is a fleet-capacity problem, not a database problem.

  3. Client and worker APIs

    Clients talk over HTTPS using an Idempotency-Key header (a client-generated unique token so retrying a timed-out POST returns the original job instead of creating a duplicate). Workers communicate over internal mTLS using long-polling (holding a poll request open for up to 20 seconds when queues are empty so new runs start immediately without busy-loop polling).

    Client REST API
      POST /v1/jobs                         Idempotency-Key: <uuid>
        {
          "name": "nightly-ledger-reconcile",
          "task": { "image": "registry.internal/finops@sha256:3c8d...",
                    "command": ["python", "reconcile.py", "--date", "{{scheduled_date}}"] },
          "schedule": { "type": "cron", "cron": "0 0 * * *", "timezone": "America/Chicago" },
                      -- or {"type": "at", "at": "2026-11-15T09:00:00Z"} or {"type": "now"}
          "priority": "normal",             -- high | normal | low
          "timeout_s": 3600,
          "retry": { "max_attempts": 3, "backoff_s": 30, "max_backoff_s": 600 },
          "on_worker_lost": "retry",        -- retry | fail ("fail" enforces at-most-once)
          "concurrency": "forbid",          -- allow | forbid | replace
          "catchup": "run_once",            -- run_once | skip | run_all
          "starting_deadline_s": 3600,
          "start_window_s": 0               -- optional hash jitter window for non-urgent cron jobs
        }
        -> 201 { "job_id": "job_4b8e", "version": 1, "next_run_at": "2026-11-15T06:00:00Z" }
    
      PATCH  /v1/jobs/{job_id}              If-Match: <version>   (412 Precondition Failed on conflict)
      POST   /v1/jobs/{job_id}:pause        POST /v1/jobs/{job_id}:resume
      DELETE /v1/jobs/{job_id}              POST /v1/jobs/{job_id}:run
      GET    /v1/jobs/{job_id}/runs         GET  /v1/runs/{run_id}
      POST   /v1/runs/{run_id}:cancel       GET  /v1/runs/{run_id}/logs?attempt=1&follow=true
    
    Internal Worker Pull Protocol (mTLS)
      POST /internal/lease      { worker_id, free_slots } -> [ { run_id, attempt, task, timeout_s, scheduled_at } ]
      POST /internal/started    { run_id, attempt }
      POST /internal/heartbeat  { worker_id, runs: [ { run_id, attempt }, ... ] }
                                -> { renewed: [...], stop: [ { run_id, attempt, reason } ] }
      POST /internal/finished   { run_id, attempt, outcome, exit_code, log_uri }
    

    Two details here do heavy lifting later: - {{scheduled_date}} uses the logical schedule slot, never the wall clock: If a midnight job runs 12 minutes late at 00:12, it still receives the date it was scheduled for, making idempotent upserts easy. - Every worker RPC carries (run_id, attempt): The attempt integer acts as a fencing token (a monotonically increasing version number; if a stalled worker reports back after Attempt 2 has already started, the server rejects Attempt 1's update).

  4. Data model and run state machine

    We partition state into 64 logical shards by shard_id = hash(job_id) % 64 across PostgreSQL clusters (each with a synchronous standby in another availability zone). Keeping a job, its trigger, and all of its runs on the same shard lets us create a run and advance its schedule inside one fast local ACID transaction.

    jobs          PK job_id
                  shard_id, tenant_id, name, task_json, schedule_type, cron_expr, timezone,
                  priority (0=high, 1=normal, 2=low), timeout_s, retry_json, on_worker_lost,
                  concurrency, catchup, starting_deadline_s, start_window_s,
                  state ('ACTIVE' | 'PAUSED' | 'DELETED'), version, idempotency_key
                  UNIQUE (tenant_id, idempotency_key)
    
    triggers      PK job_id   -- ONLY active jobs that have a future firing time
                  shard_id, next_fire_at (UTC)
                  INDEX (shard_id, next_fire_at)
    
    runs          PK run_id
                  shard_id, job_id, tenant_id, scheduled_at, eligible_at, priority, job_version,
                  state, attempt, worker_id, lease_until, started_at, finished_at,
                  exit_code, retries_used, infra_retries_used
                  UNIQUE (job_id, scheduled_at)  -- guarantees at most ONE run row per schedule slot!
                  INDEX (shard_id, priority, eligible_at) WHERE state = 'PENDING'
                  INDEX (shard_id, lease_until) WHERE state IN ('CLAIMED', 'RUNNING', 'CANCELLING')
                  INDEX (job_id, scheduled_at DESC)
    
    attempts      PK (run_id, attempt) (worker_id, started_at, ended_at, outcome, exit_code, log_uri)
    

    Notice two schema choices: - Separating scheduled_at from eligible_at: scheduled_at identifies the logical calendar slot (2026-12-01 00:00:00Z) and never changes, preserving UNIQUE (job_id, scheduled_at). eligible_at controls when workers are allowed to pick up the run (moved forward by retry backoffs or start-window jitter). - Partial indexes keep hot queries fast: Even if runs holds 150M finished rows from recent days (older partitions archive to cold tables), the WHERE state = 'PENDING' index only indexes waiting runs, and the reaper index only indexes the ~35,000 currently active runs.

                         claim (attempt += 1)           started
       [ PENDING ] ------------------------------> [ CLAIMED ] ---------> [ RUNNING ]
            ^                                           |                      |
            |     backoff / requeue (retries left)      | lease expired        | finished / timeout
            +-------------------------------------------+----------------------+
                                                                               |
                                                        no retries left        v
                                                   [ SUCCEEDED | FAILED | TIMED_OUT | LOST ]
       (Any active state --cancel--> CANCELLING --> CANCELLED; concurrency=forbid --> SKIPPED)
    
  5. High-level architecture

     Clients (CLI, UI, Services)
              | HTTPS
              v
     [ Stateless API Servers ] ------- create/edit jobs + triggers -----------+
                                                                              v
     [ Shard Owners (N pods) ] -- fire due triggers (60s lookahead) --> [ Sharded PostgreSQL ]
       (~8 shards/pod via etcd)   reap expired worker leases            [ 64 logical shards  ]
                                                                        [ + Sync AZ Standbys ]
     [ Stateless Dispatchers ] -- claim PENDING runs, renew leases -----------^
            ^          |
            | poll     | runs + stop signals
            |          v
     [ Worker Fleet: 6,250 hosts x 16 slots ] ---- chunked stdout/stderr ---> [ Object Storage ]
            ^
            | pre-scale before calendar spikes
     [ 24h Capacity Forecaster ] ---> [ Cluster Autoscaler ]
    
    • Shard owners ("when"): Coordinated via lightweight 10-second leases in etcd so each of the 64 shards has one active driver loop firing triggers and reaping dead worker leases. Crucially, etcd is used only for work distribution — database constraints guarantee correctness even if two pods briefly process the same shard.
    • Dispatchers ("hand-off"): Stateless RPC servers that keep a 200 ms cached summary of which shards have PENDING work so worker long-polls go straight to shards with ready runs.
    • Worker agents ("execution"): Run tasks in isolated containers, enforce local wall-clock timeouts, stream logs directly to S3/GCS, and batch lease renewals every 10 seconds.
  6. Deep dive 1: Finding due jobs without scanning

    Why scanning fails and how triggers fixes it: Scanning jobs every second touches all 10,000,000 definitions even when zero jobs are due. Instead, triggers stores only (shard_id, next_fire_at, job_id) sorted in a B-tree index on (shard_id, next_fire_at). Each pass performs a bounded range scan (next_fire_at <= now() + 60s), costing O(log N + K) where K is the count of due triggers — completely independent of total stored jobs!

    LOOKAHEAD_S = 60
    BATCH_SIZE = 500
    
    
    def fire_due_triggers(db, shard_id: int) -> int:
        """Pre-create PENDING runs due within the next 60s for one shard and advance triggers."""
        with db.transaction() as tx:
            due_rows = tx.query(
                """
                SELECT job_id, next_fire_at
                FROM triggers
                WHERE shard_id = :shard_id
                  AND next_fire_at <= now() + (:lookahead_s * interval '1 second')
                ORDER BY next_fire_at
                LIMIT :batch_size
                FOR UPDATE SKIP LOCKED
                """,
                {"shard_id": shard_id, "lookahead_s": LOOKAHEAD_S, "batch_size": BATCH_SIZE},
            )
            for job_id, fire_at in due_rows:
                job = tx.get_job(job_id)
                slots_to_create, next_fire_at = plan_trigger(job, fire_at, tx.now())
    
                for slot in slots_to_create:
                    eligible_at = slot + spread_offset(job)
                    # ON CONFLICT DO NOTHING ensures idempotency if two schedulers race
                    tx.execute(
                        """
                        INSERT INTO runs (
                            run_id, shard_id, job_id, tenant_id, scheduled_at,
                            eligible_at, priority, job_version, state, attempt
                        )
                        VALUES (
                            :run_id, :shard_id, :job_id, :tenant_id, :slot,
                            :eligible_at, :priority, :version, 'PENDING', 0
                        )
                        ON CONFLICT (job_id, scheduled_at) DO NOTHING
                        """,
                        {
                            "run_id": new_run_id(),
                            "shard_id": shard_id,
                            "job_id": job_id,
                            "tenant_id": job.tenant_id,
                            "slot": slot,
                            "eligible_at": eligible_at,
                            "priority": job.priority,
                            "version": job.version,
                        },
                    )
    
                if next_fire_at is None:
                    # One-off 'at' job finished firing; remove from triggers
                    tx.execute("DELETE FROM triggers WHERE job_id = :job_id", {"job_id": job_id})
                else:
                    tx.execute(
                        "UPDATE triggers SET next_fire_at = :next_at WHERE job_id = :job_id",
                        {"next_at": next_fire_at, "job_id": job_id},
                    )
            return len(due_rows)
    

    Key details of this 60-second lookahead: - Start precision comes from eligible_at: A run scheduled for 12:00:00 is inserted around 11:59:00 with state = 'PENDING', eligible_at = 12:00:00. Dispatchers only claim rows where eligible_at <= now(), so the run never starts early, and if a shard owner crashes at 11:59:40, failover causes zero start delay! - Handling job edits, pauses, and deletes cleanly: Because a job's next run may already sit in runs as PENDING during the 60-second lookahead window, PATCH, :pause, and DELETE delete any unclaimed PENDING runs for that job_id in the same shard transaction (and on PATCH, rewind triggers.next_fire_at to the earliest deleted slot so the next pass recreates it with the updated job_version). - Time zones, Daylight Saving Time (DST), and clock skew: Cron expressions are evaluated in the job's IANA time zone (e.g., America/New_York) starting from the previous scheduled slot (never local now(), which would skip missed slots) and stored in UTC. On spring-forward days, nonexistent local times (02:30) fire once at 03:00; on fall-back days, repeated local times (02:30) fire only on the first occurrence. All comparisons use PostgreSQL now() on the shard primary so clock skew across scheduler pods cannot trigger early runs.

  7. Deep dive 2: Preventing duplicate runs across crashes

    Suppose a shard-owner pod freezes for 15 seconds during garbage collection, loses its etcd shard lease to another pod, and then wakes up mid-transaction. Or suppose two dispatchers poll the same shard at once. We prevent duplicate runs at three independent checkpoints:

    1. At run creation (triggers -> runs): UNIQUE (job_id, scheduled_at) in PostgreSQL makes it physically impossible to insert two runs rows for the 2026-12-01 00:00:00Z slot of job_id, even if two shard owners run fire_due_triggers simultaneously.
    2. At worker dispatch (PENDING -> CLAIMED): A dispatcher claims runs with a single atomic UPDATE ... FOR UPDATE SKIP LOCKED query that increments attempt and grants a short 30-second startup lease:
    UPDATE runs
    SET state = 'CLAIMED',
        attempt = attempt + 1,
        worker_id = :worker_id,
        lease_until = now() + interval '30 seconds'
    WHERE run_id IN (
        SELECT run_id
        FROM runs
        WHERE shard_id = :shard_id
          AND state = 'PENDING'
          AND eligible_at <= now()
          AND tenant_id <> ALL(:tenants_at_concurrency_cap)
        ORDER BY priority ASC, eligible_at ASC
        LIMIT :free_slots
        FOR UPDATE SKIP LOCKED
    )
    RETURNING run_id, attempt, job_id, job_version;
    

    Right before returning claimed runs to the worker, the dispatcher checks the job's concurrency policy if an earlier run of the same job_id is currently CLAIMED or RUNNING: allow proceeds normally, forbid marks the newly claimed run SKIPPED immediately, and replace transitions the older run to CANCELLING before starting the new one. 3. At worker status reporting (the attempt fencing token): Every started, heartbeat, and finished update filters WHERE run_id = :run_id AND attempt = :attempt AND state IN ('CLAIMED', 'RUNNING'). If a network drop caused attempt = 1 to expire and attempt = 2 has already been claimed, late messages from attempt = 1 match zero rows in runs (they are logged in attempts for audit only).

  8. Deep dive 3: Lost workers, self-fencing, and retries

    What happens if a worker stops sending heartbeats halfway through a job because its network cable failed, while its container is still running? If the server immediately launches Attempt 2 on another host, two live copies run side by side!

    We prevent concurrent live attempts using worker self-fencing backed by local monotonic clocks (time.monotonic(), which measures elapsed seconds accurately regardless of wall-clock jumps):

    t =  0 s   Worker sends heartbeat; server sets lease_until = t_server + 60 s (>= 60 s)
    t = 10 s   Network partition begins; worker heartbeats start timing out
    t = 45 s   Worker sees 45 s elapsed on its monotonic clock since t = 0 s -> sends SIGTERM to container
    t = 55 s   After 10 s shutdown grace, worker sends SIGKILL -> container is guaranteed dead!
    t = 60 s   Server lease_until timestamp passes (reaper still waits during 30 s grace window)
    t = 90 s   Server reaper sees lease_until < now() - 30 s -> marks Attempt 1 LOST and requeues Attempt 2
    

    Notice the 35-second safety buffer (90 s - 55 s = 35 s): Attempt 1 kills itself at least 35 seconds before the server ever allows Attempt 2 to start, without needing synchronized wall clocks across machines!

    Separate retry budgets and jittered backoff: - Application exit failures (non-zero exit code) consume retries_used up to job.retry.max_attempts. - Infrastructure failures (lost worker lease, container image pull error) consume a separate infra_retries_used budget (MAX_INFRA_RETRIES = 3) so a dying cloud VM does not burn a customer's application retries — while a "poison job" that repeatedly kernel-panics 3 different machines gets quarantined (LOST) instead of taking down the whole fleet. - Exponential backoff with jitter multiplies retry delays by a random factor (0.5 to 1.0) so if a shared downstream database goes down for 50,000 jobs at once, their retries spread out smoothly instead of slamming back in synchronized waves.

    import random
    
    MAX_INFRA_RETRIES = 3
    
    
    def backoff_seconds(retry_num: int, base_s: float, max_s: float) -> float:
        """Compute exponential backoff with 50%-100% jitter to prevent retry storms."""
        raw_delay = min(max_s, base_s * (2 ** (retry_num - 1)))
        return raw_delay * random.uniform(0.5, 1.0)
    
    
    def handle_lost_attempt(tx, run, job) -> None:
        """Reap an expired attempt (fenced on run.attempt) and either requeue or fail."""
        tx.record_attempt(run.run_id, run.attempt, outcome="LOST")
        if job.on_worker_lost == "fail" or run.infra_retries_used >= MAX_INFRA_RETRIES:
            tx.set_run_state(run.run_id, run.attempt, new_state="LOST")
            return
    
        next_infra_count = run.infra_retries_used + 1
        delay_s = backoff_seconds(next_infra_count, base_s=10.0, max_s=300.0)
        tx.requeue_run(
            run_id=run.run_id,
            expected_attempt=run.attempt,
            eligible_at=tx.now() + delay_s,
            infra_retries_used=next_infra_count,
        )
    

    For timeouts and cancellations, workers kill tasks surpassing timeout_s locally (SIGTERM -> grace -> SIGKILL), and POST /v1/runs/{id}:cancel sets state = 'CANCELLING' so the worker's very next 10-second heartbeat response delivers a stop command.

  9. Deep dive 4: Midnight bursts and catch-up after outages

    Tracing 1,000,000 jobs scheduled for 00:00:00 UTC:

    23:59:00   All 1M midnight triggers enter the 60s lookahead (~15,625 triggers per shard).
               Capped at 1,000 inserts/s/shard to protect steady traffic, all 1M PENDING rows
               exist in PostgreSQL by ~23:59:16.
    00:00:00   eligible_at <= now() becomes true! Workers have ~65,000 free slots (100k - 35k busy)
               and immediately claim the first 65,000 midnight runs.
    00:00:01+  935,000 midnight runs remain queued. Slots free up at 100,000 / 60s = ~1,670 slots/s,
               while normal steady traffic arrives at ~580 runs/s:
               - Pure FIFO: 935,000 / 1,670 = ~560 s (~9.3 min max delay, delaying 00:01 jobs too)
               - Priority-ordered: high/normal steady traffic goes first; low-priority midnight batch
                 drains at (1,670 - 580) = 1,090/s -> ~860 s (~14.3 min max delay, zero impact on high)
    

    Three levers control burst delay — and only the first one adds capacity: 1. Predictive pre-scaling (shortens total backlog): Because cron schedules are known ahead of time, the Capacity Forecaster expands schedules 24 hours ahead into per-minute slot demand. At 23:40, the autoscaler expands the fleet from 100k to 300k slots (+12,500 spot/on-demand VMs for ~30 minutes): 265k runs start immediately at 00:00:00, and the remaining 735k drain at (300k / 60s - 580) = ~4,420/s in ~166 seconds (< 3 minutes). 2. Priority queues (protects latency-sensitive jobs): Ordering claims by (priority, eligible_at) ensures urgent high jobs due at 00:01 never wait behind 900k nightly batch reports. 3. Opt-in start windows (start_window_s): Setting start_window_s = 900 sets eligible_at = scheduled_at + (hash(job_id) % 900) while keeping scheduled_at = 00:00:00 intact so user scripts still process the exact midnight window.

    Handling missed runs after a shard outage (plan_trigger): Suppose a shard was down for 45 minutes and an every-minute job has next_fire_at 45 slots in the past. Notice a subtle trap: if we only check one slot at a time, run_once would accidentally fire all 45 missed runs across 45 passes! Instead, whenever more than one slot is already in the past (next_slot <= now), run_once and skip jump straight to the latest overdue slot:

    MAX_CATCHUP_PER_PASS = 100
    
    
    def plan_trigger(job, fire_at, now):
        """Decide which run slots to emit and the new next_fire_at, even after a long outage."""
        next_slot = next_fire_time(job, after=fire_at)
    
        # Check if two or more recurring slots have already passed during an outage
        if next_slot is not None and next_slot <= now:
            if job.catchup == "run_all":
                return catch_up_all_slots(job, fire_at, now)
            # For 'run_once' or 'skip', collapse all missed slots down to the latest overdue one
            fire_at = latest_fire_time_at_or_before(job, now)
            next_slot = next_fire_time(job, after=now)
    
        if job.catchup == "skip" and (now - fire_at) > job.starting_deadline_s:
            return [], next_slot  # Too stale to be useful (e.g., a missed morning alert)
    
        return [fire_at], next_slot
    
    
    def catch_up_all_slots(job, fire_at, now):
        """Replay every missed slot in chronological order, capped per pass to avoid DB floods."""
        slots = []
        cursor = fire_at
        while cursor is not None and cursor <= now and len(slots) < MAX_CATCHUP_PER_PASS:
            slots.append(cursor)
            cursor = next_fire_time(job, after=cursor)
        return slots, cursor
    
  10. Scaling, failure recovery, and monitoring

    • Horizontal database scaling: Start 64 logical shards across 8 PostgreSQL clusters (8 shards/cluster); as run volume grows 8x, migrate logical shards onto dedicated clusters with zero job_id changes. Archive finished runs and attempts older than 3 days into partitioned history tables.
    • Database primary failover subtlety: When a shard primary fails over to its synchronous AZ standby (~15 seconds), workers could not renew leases during the blip. Before resuming the reaper on a newly promoted primary, the shard owner extends all live lease_until rows by 60 seconds so healthy runs are never falsely reaped! (As long as failover completes well inside the worker's 45-second self-fencing window, running tasks continue uninterrupted.)
    • Log streaming: Workers upload chunked logs directly to S3/GCS (attempts.log_uri); live follow=true tails proxy to the worker while RUNNING and read from object storage once finished.
    • Key operational metrics (SLIs):
      1. Schedule start lag (started_at - eligible_at, p50/p99 by priority): Primary user-facing SLO (< 2s when slots are free).
      2. Trigger lag per shard (now() - min(next_fire_at)): Alerts immediately if a shard owner stalls.
      3. Ready backlog vs. free worker slots + 1-hour forecast: Drives autoscaling alarms.
      4. Infrastructure LOST rate and SKIPPED rate: Spikes pinpoint unhealthy worker hosts or network partitions.
  11. Summary of key trade-offs

    • In-database (shard_id, next_fire_at) B-tree index vs. external Redis timer wheel: Keeps job definitions, triggers, and run creation in one transactional store with zero dual-write drift, easily handling ~580 runs/s across 64 shards.
    • 60-second lookahead vs. just-in-time run creation: Smooths the 1M midnight write spike by 60x and hides shard-owner failover, in exchange for deleting unclaimed PENDING runs when jobs are edited or paused.
    • Database uniqueness + attempt fencing vs. relying on leader election: UNIQUE (job_id, scheduled_at), SKIP LOCKED, and WHERE attempt = :attempt guarantee correctness even when paused leaders overlap.
    • Worker self-fencing + at-least-once retries vs. waiting indefinitely: Cutting off silent workers at 45s and reassigning at 90s recovers dead hosts quickly without concurrent live copies, at the cost of killing long runs if a worker loses control-plane network for > 45s.
    • Predictive fleet pre-scaling vs. start-window jitter: Pre-scaling buys sub-3-minute midnight latency with compute spend; priorities and jitter reorder the queue for free without adding slot capacity.

Intuition & how it works

Imagine a hospital pharmacy managing 10 million recurring prescriptions. Reading all 10 million patient folders every second to check whose refill is due right now would overwhelm the staff. Instead, the pharmacy keeps a sorted index-card drawer ordered by next refill time (triggers), pulls only the cards due in the next 60 seconds onto a "ready tray" (PENDING runs), and stamps an incrementing attempt number on each bottle whenever a technician claims it so two technicians can never dispense the same dose twice.

Naive designs fail at scale for three reasons. First, scanning 10 million job rows every second reads 9,999,420 idle rows just to find ~580 due runs, and inserting 1,000,000 midnight runs at 00:00:00 slams the database with 2,000,000 writes in a single second. Second, trusting leader election (picking one active scheduler node via a temporary lock) alone to prevent duplicates breaks whenever a scheduler pauses during garbage collection and wakes up after a replacement leader has already taken over. Third, immediately rerunning a job as soon as worker heartbeats stop risks running two live copies simultaneously if the silent worker is merely cut off from the network.

Walk through four concrete events to see how the system stays fast and safe: 1. Lookahead trigger firing (23:59:00): Shard Owner #5 queries triggers via the (shard_id, next_fire_at) B-tree index (a sorted tree index that finds time ranges in logarithmic time), inserts the 00:00:00 PENDING run (attempt = 0, eligible_at = 00:00:00), and updates next_fire_at to tomorrow in one transaction — guarded by UNIQUE (job_id, scheduled_at). 2. Atomic worker claim (00:00:00): Worker #19 has 4 free container slots and long-polls (holds an HTTP request open until work is ready) a Dispatcher, which runs UPDATE ... FOR UPDATE SKIP LOCKED to flip the run from PENDING to CLAIMED with attempt = 1 and a 30-second startup lease. 3. Execution and lease renewal (00:00:01+): Worker #19 starts the container (RUNNING, 60-second lease), streams stdout directly to object storage (S3/GCS), and renews its lease every 10 seconds using (run_id, attempt = 1) as a fencing token (a monotonically increasing version check that rejects stale attempts). 4. Network partition and self-fencing: Suppose Worker #19 loses network at 00:00:20. After 45 seconds without a heartbeat reply on its local monotonic clock (an elapsed-time counter unaffected by wall-clock jumps), Worker #19 kills its own container by 00:01:15, leaving a 35-second safety buffer before the server reaper marks attempt = 1 LOST at 00:01:50 (60s lease + 30s grace) and requeues attempt = 2.

Key trade-offs

  • B-tree index on triggers(shard_id, next_fire_at) in PostgreSQL vs. a separate Redis sorted set: Keeping triggers in the same sharded database as jobs and runs lets "insert run + advance next_fire_at" commit in one atomic transaction with zero risk of Redis-to-DB drift after crashes, easily supporting ~580 runs/s across 64 shards.
  • 60-second run pre-creation (lookahead) vs. creating runs at the exact second due: Pre-creating runs spreads the 2,000,000-write midnight spike across a full minute (~520 writes/s/shard) and hides 15-second scheduler failovers, at the cost of deleting unclaimed PENDING runs when a user edits, pauses, or deletes a job.
  • Database constraints + attempt fencing vs. relying on single-leader locks: Enforcing UNIQUE (job_id, scheduled_at) on creation and WHERE attempt = :attempt on worker updates guarantees no duplicate schedule slots and no stale status overwrites, turning etcd shard leases into a pure performance optimization.
  • Pull-based worker long-polling vs. pushing tasks from the scheduler: Workers request work only when they actually have free slots, avoiding stale cluster state or pushing tasks to overloaded hosts, with long-polling eliminating polling delay.
  • 60-second worker lease (+ 30s grace) vs. aggressive 5-second timeouts: Waiting ~90 seconds before declaring a worker dead takes slightly longer to recover from a hardware crash, but avoids killing healthy multi-hour jobs during brief network blips or garbage-collection pauses.
  • At-least-once default (retry) vs. at-most-once opt-in (fail): Automatically rerunning lost workers prevents silent job drops (and becomes effectively-once when jobs write outputs idempotently using RUN_ID), while non-idempotent jobs can opt into on_worker_lost: "fail".
  • Pre-scaling worker capacity vs. priorities and start-window jitter: Only adding worker machines before known bursts reduces total queue drain time; priorities and hash-jittered start windows simply choose which jobs wait in line for free.

Common mistakes

  • Scanning the entire jobs table on every scheduler tick: Even at 1 tick per second, scanning 10M rows saturates database I/O before a single job runs.
  • Advancing next_fire_at relative to now() instead of the previous scheduled_at slot: If a shard recovers from a 30-minute outage and computes next_fire_time(after=now()), every missed slot vanishes silently without applying the job's catchup policy.
  • Evaluating schedules with each scheduler pod's local wall clock: Clock drift between pods causes fast hosts to fire runs early; using the shard database's now() gives one consistent clock per shard.
  • Trusting leader election alone to prevent duplicate runs: A paused leader can resume and execute SQL after its etcd lease expires; database uniqueness (UNIQUE (job_id, scheduled_at)) and fencing tokens (attempt) are mandatory.
  • Reassigning a silent worker's run while the old container is still alive: Without worker self-fencing before the server's lease + grace expires, network partitions produce two concurrent live containers corrupting external state.
  • Accepting worker finished RPCs without checking attempt: A delayed failure from Attempt 1 can overwrite a live or succeeded Attempt 2.
  • Sharing one retry counter between application bugs and dead worker VMs: Infrastructure faults should use a separate infra_retries_used budget so bad hosts do not exhaust user retries, while still capping retries to quarantine "poison" jobs that crash hosts.
  • Retrying without random jitter: When an upstream API fails for 50,000 jobs simultaneously, fixed-interval backoffs cause all 50,000 jobs to hammer the API again at the exact same second.
  • Storing stdout/stderr logs inside PostgreSQL: Streaming ~1 TB/day of text through relational tables destroys database write throughput and cache hit rates; stream logs directly from workers to object storage.

Follow-up questions

  • Suppose a million cron tasks all share a 00:00 UTC trigger. Walk through how your architecture absorbs that spike and bounds startup lag. On the database side, all 1M triggers enter the lookahead window at 23:59:00, and the 64 shard owners batch-insert the PENDING runs at a capped ~1,000 runs/s/shard, finishing smoothly around 23:59:16 with eligible_at = 00:00:00. At 00:00:00, worker capacity is the real bottleneck: with 100k total slots and ~35k busy, 65k midnight runs start immediately and 935k wait, draining at ~1,670 slots/s (~9.3 minutes under FIFO, or ~14.3 minutes behind ~580/s higher-priority steady traffic). To cut that wait under 3 minutes, our 24-hour Capacity Forecaster pre-scales the worker fleet to 300k slots at 23:40 (starting 265k runs immediately and draining the rest at ~4,420/s in ~166 seconds), while priority ordering keeps urgent jobs ahead of batch reports and opt-in start_window_s hash jitter spreads non-urgent jobs cleanly.
  • Suppose an execution node goes silent 120 minutes into a 180-minute task. How does the control plane decide whether to launch a replacement attempt, and how do you guard against split-brain execution if that host is merely network-partitioned? First, check out-of-band cloud VM status: if the hypervisor confirms the instance terminated, we can mark the attempt LOST immediately; otherwise we wait the full lease + grace (~90 s, or a longer configured lease for multi-hour jobs). Even if the execution host is still running behind a network partition, its local agent tracks elapsed time since its last acknowledged heartbeat on its monotonic clock and self-fences (SIGTERM at 45s, SIGKILL at 55s), guaranteeing the container stops at least 35 seconds before the control plane launches a replacement. Next, job.on_worker_lost decides whether to requeue (retry with incremented attempt, ideally resuming from checkpoints saved under the stable RUN_ID) or stop (fail for non-idempotent jobs), and any late RPC or per-attempt output from the stale attempt is fenced out by its outdated attempt token.
  • How would you extend the platform to support workflow DAGs where downstream tasks wait until all upstream prerequisites finish successfully? Store a DAG (Directed Acyclic Graph, a dependency graph with no loops, validated via depth-first search on job save) in job_edges(upstream_job_id, downstream_job_id, slot_mapping). Downstream runs are pre-created in state = 'WAITING' with unmet_deps = K, paired to upstream runs by scheduled_at (or a window rule like "all 24 hourly slots for a daily job"). Whenever an upstream run transitions to SUCCEEDED, a transactional outbox event inserts an idempotent row into satisfied_deps(downstream_run_id, upstream_run_id) and decrements unmet_deps, flipping the downstream run to PENDING the moment unmet_deps hits 0 (or marking it UPSTREAM_FAILED if an upstream run exhausts all retries).
  • How must worker assignment evolve once tasks specify heterogeneous CPU, RAM, and GPU footprints instead of uniform slots? Generic slot counts no longer suffice because a 64 GB RAM or 4-GPU task cannot fit across two half-empty machines. Workers advertise free (cpu, memory_gb, gpu_type, free_gpus) in their poll requests, and runs are partitioned into per-resource-class queues (CPU-standard, high-memory, per-GPU-model) so scarce GPU hosts only inspect matching GPU queues. Because small tasks can endlessly fill tiny gaps and starve large shapes, dispatching must add best-fit bin packing (placing small tasks onto already partially filled hosts to preserve empty machines), all-or-nothing gang reservations for multi-GPU tasks, or hand off physical placement ("where") to a dedicated cluster orchestrator like Kubernetes or Slurm while keeping our service focused on triggers and retries ("when").

Follow-up questions

Similar questions

More Fluidstack interview questions

All 2 Fluidstack questions →