System Design

C17

Job scheduler with DAGs

Run jobs on a cron schedule, each as a DAG of tasks, across many nodes and workers. Postgres holds the state; leases and unique keys make every step safe to repeat.

Not startedSaved in this browser only.
  1. 1Every scheduler node ticks. A unique key on (job, fire time) makes a repeated fire a no-op, so no leader is needed.
  2. 2A run is a DAG of task rows. A task becomes ready in the transaction that marks its last parent succeeded.
  3. 3Workers claim tasks with SKIP LOCKED and hold a lease they renew by heartbeat. The attempt number fences a worker that lost its lease.
  4. 4Execution is at least once, so tasks are idempotent. A task that must never repeat gets one attempt, and a person decides.
C17
    A

    The prompt and requirements

    questions first, then numbers
    "Design a scheduler that runs jobs on a schedule and in dependency order, at most once, across a cluster."
    questionanswer assumed
    How many jobs?100,000 jobs from 500 teams.
    How often do they run?Every minute to monthly; 24 runs per job a day on average.
    How big is a job?A DAG of 10 tasks on average; a task runs seconds to hours.
    What does "at most once" mean here?One run per fire time, and one recorded success per task. Tasks are idempotent; a task that must never repeat gets one attempt.
    Who runs the task code?Workers pull tasks. The scheduler only decides what is ready.
    What about runs missed during downtime?A policy per job: all, latest or none.
    Time zones?Schedules are in UTC.
    Do teams share workers?Yes, by weight. Priority goes first.
    jobnightly-orderscron 0 2 * * *catch-up latestteam data6 tasks, a DAGone run per fire timerun · Oct 6 02:00run · Oct 7 02:00run · Oct 8 02:00UNIQUE (job_id, scheduled_for)a second fire of 02:00inserts nothingits tasks: one row per nodeready when every parent succeededextract_ordersextract_usersjoincheckloadpublish
    requirementtarget
    Fire on timerun created within 5 s of its fire time
    Runs per job and fire timeexactly 1, with any number of nodes
    Recorded successes per task and runexactly 1
    Dependency orderno task starts before all its parents succeed
    Dead worker's task restartswithin lease + backoff: 40 s
    Scheduler outagecatch up by policy on restart

    I fire each schedule time once and run each task after its parents succeed. A lost task is retried when its lease ends, so tasks are idempotent.

    B

    Estimates

    arithmetic shown
    runs
    100,000 jobs × 24 = 2.4 million a day
    tasks
    2.4 M × 10 = 24 million a day
    average
    24 M ÷ 86,400 s ≈ 278 task starts a second
    burst
    40% of jobs fire at :00, 3 root tasks each: 40,000 × 3 = 120,000 tasks ready at once
    drain
    120,000 ÷ 2,000 a second ≈ 60 s; spread over 10 minutes: 200 a second
    running
    278 a second × 60 s per task ≈ 16,667 tasks at once
    heartbeats
    16,667 ÷ 10 s ≈ 1,667 single-row updates a second
    storage
    24 M × 500 B ≈ 12 GB a day; 30 days ≈ 360 GB

    The 40% at :00, the 3 roots and the 60 s per task are assumptions; say them out loud. The claim rate and the bytes per task were measured in the lab.

    The average is about 278 task starts a second. The danger is the top of the hour: 120,000 tasks ready at once.

    C

    API

    definitions, triggers, the worker protocol
    callresult
    PUT /jobs/:name200 with the next fire time. 422 for a bad cron line or a cycle.
    POST /jobs/:name/runsTrigger or backfill a fire time. 201, or 409 if that run exists.
    PATCH /jobs/:namePause or resume. 200.
    GET /runs/:idRun state, every task, every attempt.
    POST /runs/:id/tasks/:t/retry202 for a failed task; 409 otherwise.
    POST /tasks/claimWorker: 200 with run, task, attempt, lease end; 204 if nothing is ready.
    POST /tasks/:id/heartbeat200 with the new lease end; 409 when the lease is lost.
    POST /tasks/:id/completeBody: attempt, ok. 200, or 409 when the attempt is stale.

    The fire time is the idempotency key of a trigger: two POSTs for one time make one run. The attempt number is the key of every worker call.

    Defining a job is an idempotent PUT. Workers pull with claim, heartbeat and complete, and a stale attempt number gets 409.

    D

    Data model

    entities, then SQL
    copied per runteamsPKnameweightshare of workersfair share inside a priorityjobsPKidFKteamcron0 2 * * *catch_upall, latest, nonenext_fire_atindexeddue: next_fire_at <= nowjob_tasksPKjob_idPKnameparentsacyclicmax_attemptstimeoutmax_attempts 1: at most oncerunsPKidUQjob_idUQscheduled_forstatetasks_leftcounts downone run per fire timetasksPKrun_idPKnamestate6 stateswaiting_onparents leftattemptsfencing tokenworker, lease_untilready_atbackoffready queue per team, indexedattemptsPKrun_id, taskPKattemptworkerstart_seq, end_seqoutcomelost, timeout …history of every try
    hot rows
    Ready and running tasks only; partial indexes skip the rest.
    growth
    About 500 B per task with its attempt and indexes. Partition tasks and attempts by day; drop old days.
    clock
    Every call takes now. In production, read it from Postgres so all nodes share one clock.
    jobs, runs, tasks, attemptssql
    -- A team gets a share of the workers in proportion to its weight.
    CREATE TABLE teams (
      name   text PRIMARY KEY,
      weight int  NOT NULL CHECK (weight > 0)
    );
    
    -- A job: a schedule, a DAG of tasks, and what to do with fire times missed during downtime.
    CREATE TABLE jobs (
      id           bigint      GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
      name         text        NOT NULL UNIQUE,
      team         text        NOT NULL REFERENCES teams,
      cron         text        NOT NULL,
      catch_up     text        NOT NULL CHECK (catch_up IN ('all', 'latest', 'none'))1,
      priority     int         NOT NULL DEFAULT 0,
      next_fire_at timestamptz NOT NULL,
      paused       boolean     NOT NULL DEFAULT false
    );
    CREATE INDEX jobs_due ON jobs (next_fire_at) WHERE NOT paused;
    
    -- The DAG: each task names its parents. max_attempts = 1 means at most once.
    CREATE TABLE job_tasks (
      job_id       bigint   NOT NULL REFERENCES jobs ON DELETE CASCADE,
      name         text     NOT NULL,
      parents      text[]   NOT NULL DEFAULT '{}',
      max_attempts int      NOT NULL DEFAULT 3 CHECK (max_attempts >= 1)2,
      timeout      interval NOT NULL,
      PRIMARY KEY (job_id, name)
    );
    
    -- One run per job and fire time, whoever creates it and however often.
    CREATE TABLE runs (
      id            bigint      GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
      job_id        bigint      NOT NULL REFERENCES jobs,
      scheduled_for timestamptz NOT NULL,
      created_by    text        NOT NULL,
      state         text        NOT NULL DEFAULT 'running'
                    CHECK (state IN ('running', 'succeeded', 'failed')),
      tasks_left    int         NOT NULL,
      UNIQUE (job_id, scheduled_for)3
    );
    
    -- One row per task in a run. waiting_on counts parents that have not succeeded yet.
    CREATE TABLE tasks (
      run_id       bigint      NOT NULL REFERENCES runs,
      name         text        NOT NULL,
      team         text        NOT NULL,
      priority     int         NOT NULL,
      state        text        NOT NULL
                   CHECK (state IN ('waiting', 'ready', 'running', 'succeeded', 'failed', 'skipped')),
      waiting_on   int         NOT NULL CHECK (waiting_on >= 0)4,
      attempts     int         NOT NULL DEFAULT 0,
      max_attempts int         NOT NULL,
      timeout      interval    NOT NULL,
      ready_at     timestamptz,
      worker       text,
      lease_until  timestamptz,
      started_at   timestamptz,
      PRIMARY KEY (run_id, name)
    );
    CREATE INDEX tasks_ready ON tasks (team, priority DESC, ready_at, run_id, name)
      WHERE state = 'ready'5;
    CREATE INDEX tasks_running ON tasks (lease_until) WHERE state = 'running';
    
    -- Every attempt, with a sequence number taken inside the claim and the finish transactions.
    -- The numbers follow commit order, so a test can prove a child started after its parents ended.
    CREATE SEQUENCE attempt_seq;6
    CREATE TABLE attempts (
      run_id    bigint NOT NULL,
      task      text   NOT NULL,
      attempt   int    NOT NULL,
      worker    text   NOT NULL,
      start_seq bigint NOT NULL DEFAULT nextval('attempt_seq'),
      end_seq   bigint,
      outcome   text   CHECK (outcome IN ('succeeded', 'failed', 'lost', 'timeout')),
      PRIMARY KEY (run_id, task, attempt)
    );
    1. 1What a job does with fire times missed while no scheduler ran.
    2. 2One attempt means at most once: a lost attempt fails the run instead of running again.
    3. 3One run per fire time. Any node may fire; a second insert does nothing.
    4. 4Parents not yet succeeded. The task is ready when it reaches 0.
    5. 5The ready queue: one index ordered per team, so a claim reads the head of each team.
    6. 6Numbers taken inside the claim and finish transactions follow commit order. The tests use them to prove dependency order.

    A job holds the schedule and the DAG. Each fire time makes one run, with a task row per node that counts its parents left.

    E

    The architecture

    click a step; its path lights up
    Teams and CIdefine, triggerScheduler nodestick every secondReaperleases, timeoutsScheduler APIjobs, runsWorkersN, pull tasksPostgresjobs, runs, tasksTask targetswarehouse, APIs

    Step 1: Define

    • PUT the job: a cron line, a catch-up policy, a team, and the DAG of tasks.
    • Refuse a cron line that does not parse and a DAG with a cycle (422).
    • Store next_fire_at, the first fire time after now, in UTC.

    If it fails

    The PUT is retried: it writes the same definition again. A change applies from the next run.

    Scheduler nodes create runs, workers pull and finish tasks, a reaper recovers lost ones, and Postgres holds every state.

    F

    Capabilities used

    what each tool gives you
    toolcapabilitywhat it gives this designalso used for
    PostgresFOR UPDATE SKIP LOCKEDNodes split due jobs; workers split ready tasks; reapers split stuck tasks. Nobody waits.Job queues, payroll batches
    PostgresUnique key and ON CONFLICT DO NOTHINGOne run per job and fire time, from any number of nodes.Idempotent APIs
    PostgresConditional UPDATE and its row countHeartbeat and finish only while the attempt and worker match: a fencing token.State machines, leases
    PostgresCounters updated under the row lockwaiting_on releases a child once; tasks_left ends the run once.Stock, seat counts
    PostgresPartial indexes on stateThe ready queue per team and the running tasks by lease end stay small.Outboxes, soft deletes
    PostgresTransactionsA tick creates the run, its tasks and the next fire time together, or none of them.Every multi-row change
    PostgresSequences inside transactionsThe attempt log follows commit order, so dependency order can be checked.Audit logs
    ServiceCron parser and next-fire search in UTCFire times without a timer per job; catch-up walks them.Billing cycles, reports
    ServiceLease, heartbeat and backoff timersA dead worker is noticed in one lease; retries wait longer each time.Locks, client retries
    TargetsIdempotency keysA retried task repeats its effect safely when the target dedupes on run and task.Payments, emails

    Postgres gives me SKIP LOCKED to split work, unique keys to make firing idempotent, and fenced conditional updates for leases.

    G

    Deep dive: firing on time, once

    cron, the tick, catch-up
    who fireswherestatus
    Every node ticks; SKIP LOCKED; unique (job, fire time)PostgresApproved
    One leader with a lease (T6)PostgresFence its writes
    One cron daemon on one machinecronSingle point
    An in-memory timer per jobServiceLost on restart
    Fire with no unique key, trust the lockPostgresDuplicates
    no scheduler running07:20 restart, one tick02:0003:0004:0005:0006:0007:0008:00all6 runslatest3 runsnone2 runsrun createdfire time with no runnext fire time
    policyafter the outageuse it for
    all4 runs: 04:00, 05:00, 06:00, 07:00Each period's data matters: hourly rollups
    latest1 run: 07:00Only fresh state matters: a cache rebuild
    noneno run; next at 08:00A missed run has no value: a reminder
    tick and next fire timepseudo code
    tick(now, node):                       // every node, every second
      BEGIN
        jobs = jobs WHERE next_fire_at <= now
               FOR UPDATE SKIP LOCKED1
        FOR EACH job IN jobs:
          fires = fire times from next_fire_at to now,
                  kept or dropped by the catch-up policy2
          FOR EACH fire IN fires:
            INSERT run (job, fire) ON CONFLICT DO NOTHING3
            IF a row was inserted: one task row per DAG node
          job.next_fire_at = cron.next(now)4
      COMMIT
    
    cron.next(after):                       // the first fire time > after
      t = the minute after `after`
      LOOP:
        IF month not allowed:  t = 1st of next month, 00:00
        ELSE IF day not allowed: t = next day, 00:00
        ELSE IF hour not allowed: t = next hour, :005
        ELSE IF minute not allowed: t = t + 1 minute
        ELSE RETURN t
    1. 1Two nodes never wait for each other: each takes the due jobs the other has not locked.
    2. 2A fire time older than a 1-minute grace counts as missed. all keeps up to 24 of them.
    3. 3The unique key on (job, fire time). A node with a stale view fires again and inserts nothing.
    4. 4From now, not from the last fire time, so a long outage does not fire every missed minute.
    5. 5Skip whole months, days and hours. A yearly job takes at most about 125 steps, not half a million minutes.
    Tested source Go: tick · Go: fire times and catch-up · Go: next fire time · SQL: due jobs, run, tasks, advance
    Go: tickgo
    
    // Tick fires every due job: it locks due jobs with SKIP LOCKED, creates one run per fire time
    // the catch-up policy allows, and moves the job's next fire time past now. Any number of nodes
    // may tick at once; the unique key on (job, fire time) makes a repeated fire a no-op.
    func (s *Store) Tick(ctx context.Context, now time.Time, node string) ([]Fired, error) {
      var out []Fired
      err := pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
        type due struct {
          id           int64
          cron, policy string
          next         time.Time
        }
        rows, err := tx.Query(ctx, q["due"], now, 100)
        if err != nil {
          return fmt.Errorf("due jobs: %w", err)
        }
        jobs, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (due, error) {
          var d due
          err := r.Scan(&d.id, &d.cron, &d.policy, &d.next)
          return d, err
        })
        if err != nil {
          return fmt.Errorf("due jobs: %w", err)
        }
        for _, j := range jobs {
          sched, err := Parse(j.cron)
          if err != nil {
            return err
          }
          // Schedules run in UTC; Postgres returns times in the session's zone.
          fires, err := FireTimes(sched, j.next.UTC(), now.UTC(), j.policy, s.Grace, s.CatchUpCap)
          if err != nil {
            return fmt.Errorf("job %d: %w", j.id, err)
          }
          for _, f := range fires {
            fired := Fired{JobID: j.id, For: f}
            err := tx.QueryRow(ctx, q["create_run"], j.id, f, node).Scan(&fired.RunID)
            switch {
            case errors.Is(err, pgx.ErrNoRows): // the run exists already
            case err != nil:
              return fmt.Errorf("create run of job %d for %s: %w", j.id, f, err)
            default:
              fired.Created = true
              if _, err := tx.Exec(ctx, q["create_tasks"], fired.RunID, j.id, now); err != nil {
                return fmt.Errorf("create tasks of run %d: %w", fired.RunID, err)
              }
            }
            out = append(out, fired)
          }
          next, err := sched.Next(now.UTC())
          if err != nil {
            return err
          }
          if _, err := tx.Exec(ctx, q["advance"], j.id, next); err != nil {
            return fmt.Errorf("advance job %d: %w", j.id, err)
          }
        }
        return nil
      })
      if err != nil {
        return nil, fmt.Errorf("tick by %s: %w", node, err)
      }
      return out, nil
    }
    
    Go: fire times and catch-upgo
    
    // FireTimes lists the runs a tick creates for a job whose next fire time is next. Fire times
    // within grace of now are on time; older ones were missed while no scheduler ran, and the
    // job's policy decides what happens to them.
    func FireTimes(s *Schedule, next, now time.Time, policy string, grace time.Duration, limit int) ([]time.Time, error) {
      var missed, onTime []time.Time
      for f := next; !f.After(now); {
        if f.Before(now.Add(-grace)) {
          missed = append(missed, f)
          if len(missed) > limit {
            missed = missed[1:] // keep only the newest limit
          }
        } else {
          onTime = append(onTime, f)
        }
        var err error
        if f, err = s.Next(f); err != nil {
          return nil, err
        }
      }
      switch policy {
      case CatchUpAll:
        return append(missed, onTime...), nil
      case CatchUpLatest:
        all := append(missed, onTime...)
        if len(all) == 0 {
          return nil, nil
        }
        return all[len(all)-1:], nil
      case CatchUpNone:
        return onTime, nil
      }
      return nil, fmt.Errorf("unknown catch-up policy %q", policy)
    }
    
    Go: next fire timego
    
    // Next returns the first fire time strictly after t, in t's time zone. It skips a month, a day or
    // an hour at a time when that field does not match, and steps minutes only inside a matching
    // hour. Minutes and hours move on the absolute clock, so on a daylight-saving change a local time
    // that does not exist is skipped, and a local time that happens twice fires twice.
    func (s *Schedule) Next(t time.Time) (time.Time, error) {
      loc := t.Location()
      t = t.Truncate(time.Second).Add(time.Duration(60-t.Second()) * time.Second)
      end := t.AddDate(5, 0, 0)
      for t.Before(end) {
        switch {
        case !s.month[t.Month()]:
          t = time.Date(t.Year(), t.Month()+1, 1, 0, 0, 0, 0, loc)
        case !s.dayMatches(t):
          t = time.Date(t.Year(), t.Month(), t.Day()+1, 0, 0, 0, 0, loc)
        case !s.hour[t.Hour()]:
          t = t.Add(time.Duration(60-t.Minute()) * time.Minute)
        case !s.minute[t.Minute()]:
          t = t.Add(time.Minute)
        default:
          return t, nil
        }
      }
      return time.Time{}, fmt.Errorf("cron %q after %s: %w", s.src, t.Format(time.RFC3339), ErrNever)
    }
    
    // dayMatches applies the cron day rule: with both day fields restricted, either may match.
    func (s *Schedule) dayMatches(t time.Time) bool {
      dom, dow := s.dom[t.Day()], s.dow[t.Weekday()]
      switch {
      case s.anyDom && s.anyDow:
        return true
      case s.anyDom:
        return dow
      case s.anyDow:
        return dom
      default:
        return dom || dow
      }
    }
    
    SQL: due jobs, run, tasks, advancesql
    -- Jobs whose next fire time has come. Every scheduler node runs this; SKIP LOCKED splits the due
    -- jobs between nodes instead of making them wait for each other.
    SELECT id, cron, catch_up, next_fire_at
    FROM jobs
    WHERE NOT paused AND next_fire_at <= $1
    ORDER BY next_fire_at, id
    LIMIT $2
    FOR UPDATE SKIP LOCKED;
    
    -- The unique key (job_id, scheduled_for) makes firing idempotent: a second node, a retry or a
    -- replay inserts nothing.
    INSERT INTO runs (job_id, scheduled_for, created_by, tasks_left)
    SELECT $1, $2, $3, count(*) FROM job_tasks WHERE job_id = $1
    ON CONFLICT (job_id, scheduled_for) DO NOTHING
    RETURNING id;
    
    -- Roots are ready at once; every other task waits for its parents.
    INSERT INTO tasks (run_id, name, team, priority, state, waiting_on, max_attempts, timeout, ready_at)
    SELECT $1, d.name, j.team, j.priority,
           CASE WHEN cardinality(d.parents) = 0 THEN 'ready' ELSE 'waiting' END,
           cardinality(d.parents), d.max_attempts, d.timeout, $3
    FROM job_tasks d JOIN jobs j ON j.id = d.job_id
    WHERE d.job_id = $2;
    
    UPDATE jobs SET next_fire_at = $2 WHERE id = $1;

    Tested: 3 nodes ticked 30 due jobs at once and made 30 runs; a stale replay made none. The cron tests include months without a 31st, a leap day, and the two daylight-saving days in New York.

    Every node ticks; SKIP LOCKED splits due jobs, the unique key absorbs a repeat, and the catch-up policy decides what downtime costs.

    H

    Deep dive: running the DAG

    claims, readiness, fair share
    claimpseudo code
    claim(now, worker):
      BEGIN
        task = the head of each team's ready queue1
               ORDER BY priority DESC,
                        running(team) / weight(team)2,
                        ready_at
               LIMIT 1 FOR UPDATE SKIP LOCKED3
        task.state = running; task.attempts += 1
        task.worker = worker; task.lease_until = now + 30 s
        log the attempt
      COMMIT
      RETURN (run, task, attempt)            // attempt = fencing token4
    1. 1Read from an index per team. Sorting every ready task per claim measured 2.6 times slower with 5,000 ready.
    2. 2Fair share: the team furthest below its weight goes next. Priority classes still go first.
    3. 3Concurrent workers get different tasks and never block each other.
    4. 4Every later call carries it. A stale attempt changes 0 rows.
    Tested source Go: claim and heartbeat · SQL: claim
    Go: claim and heartbeatgo
    
    // Claim takes the next ready task for worker and logs the attempt, in one transaction. ok is
    // false when no task is ready.
    func (s *Store) Claim(ctx context.Context, now time.Time, worker string) (c Claim, ok bool, err error) {
      err = pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
        err := tx.QueryRow(ctx, q["claim"], now, worker, float64(s.Lease.Milliseconds()), headsPerTeam).
          Scan(&c.RunID, &c.Task, &c.Attempt, &c.LeaseUntil)
        if errors.Is(err, pgx.ErrNoRows) {
          return nil
        }
        if err != nil {
          return fmt.Errorf("claim: %w", err)
        }
        if _, err := tx.Exec(ctx, q["log_start"], c.RunID, c.Task, c.Attempt, worker); err != nil {
          return fmt.Errorf("log attempt: %w", err)
        }
        c.Worker, ok = worker, true
        return nil
      })
      if err != nil {
        return Claim{}, false, fmt.Errorf("claim for %s: %w", worker, err)
      }
      return c, ok, nil
    }
    
    // Heartbeat extends the lease. It returns ErrLeaseLost when the worker no longer holds the
    // attempt or the task ran past its timeout; the worker must then stop.
    func (s *Store) Heartbeat(ctx context.Context, now time.Time, c *Claim) error {
      tag, err := s.DB.Exec(ctx, q["heartbeat"], c.RunID, c.Task, c.Attempt, c.Worker, now, float64(s.Lease.Milliseconds()))
      if err != nil {
        return fmt.Errorf("heartbeat %s: %w", c.Task, err)
      }
      if tag.RowsAffected() == 0 {
        return ErrLeaseLost
      }
      c.LeaseUntil = now.Add(s.Lease)
      return nil
    }
    
    SQL: claimsql
    -- The next ready task: higher priority first, then the team furthest below its share, then the
    -- oldest. Each team offers only the head of its queue, read from the index, so a claim never
    -- sorts every ready task. SKIP LOCKED passes over a task another worker is claiming right now.
    WITH load AS (
      SELECT team, count(*) AS running FROM tasks WHERE state = 'running' GROUP BY team
    ), heads AS (
      SELECT h.run_id, h.name, h.priority, h.ready_at,
             coalesce(l.running, 0)::float8 / w.weight AS share
      FROM teams w
      LEFT JOIN load l ON l.team = w.name
      CROSS JOIN LATERAL (
        SELECT run_id, name, priority, ready_at FROM tasks
        WHERE team = w.name AND state = 'ready' AND ready_at <= $1
        ORDER BY priority DESC, ready_at, run_id, name
        LIMIT $4
      ) h
    ), pick AS (
      SELECT t.run_id, t.name
      FROM tasks t JOIN heads h ON h.run_id = t.run_id AND h.name = t.name
      WHERE t.state = 'ready'
      ORDER BY h.priority DESC, h.share, h.ready_at, h.run_id, h.name
      LIMIT 1
      FOR UPDATE OF t SKIP LOCKED
    )
    UPDATE tasks t
    SET state = 'running', attempts = attempts + 1, worker = $2,
        lease_until = $1::timestamptz + $3 * interval '1 millisecond', started_at = $1
    FROM pick
    WHERE t.run_id = pick.run_id AND t.name = pick.name
    RETURNING t.run_id, t.name, t.attempts, t.lease_until;
    
    INSERT INTO attempts (run_id, task, attempt, worker) VALUES ($1, $2, $3, $4);
    sharing workersstatus
    First in, first outOne team floods
    Strict priority onlyLow priority starves
    Priority classes, then weighted share per teamApproved
    A worker pool per teamIdle capacity
    finish a taskpseudo code
    succeed(now, claim):
      BEGIN
        UPDATE task SET state = succeeded
          WHERE attempts = claim.attempt AND worker = claim.worker
                AND state = running          // 0 rows: lease lost1
        FOR EACH child of task:
          child.waiting_on -= 1              // under the child's row lock2
          IF it reaches 0: child.state = ready
        run.tasks_left -= 1                  // at 0 the run succeeded3
      COMMIT
    1. 1The worker lost the task to a later attempt. Its result is dropped, and nothing below changes.
    2. 2Two parents that finish at once update the child one after the other. Exactly one sees 1 and makes it ready.
    3. 3A counter on one row avoids write skew between the last two tasks.
    Tested source Go: succeed · SQL: succeed, release, count down
    Go: succeedgo
    
    // Succeed records a finished attempt, makes ready every child whose last parent this was, and
    // counts the run down. It returns the run's state. A worker that lost its lease gets
    // ErrLeaseLost and changes nothing.
    func (s *Store) Succeed(ctx context.Context, now time.Time, c Claim) (run string, err error) {
      err = pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
        tag, err := tx.Exec(ctx, q["succeed"], c.RunID, c.Task, c.Attempt, c.Worker)
        if err != nil {
          return fmt.Errorf("mark succeeded: %w", err)
        }
        if tag.RowsAffected() == 0 {
          return ErrLeaseLost
        }
        if _, err := tx.Exec(ctx, q["log_end"], c.RunID, c.Task, c.Attempt, "succeeded"); err != nil {
          return fmt.Errorf("log end: %w", err)
        }
        if _, err := tx.Exec(ctx, q["release_children"], c.RunID, c.Task, now); err != nil {
          return fmt.Errorf("release children: %w", err)
        }
        if err := tx.QueryRow(ctx, q["count_down"], c.RunID).Scan(&run); err != nil {
          return fmt.Errorf("count down run: %w", err)
        }
        return nil
      })
      if err != nil {
        return "", fmt.Errorf("succeed %s attempt %d by %s: %w", c.Task, c.Attempt, c.Worker, err)
      }
      return run, nil
    }
    
    SQL: succeed, release, count downsql
    -- Fenced by the attempt number and the worker: a worker whose lease expired changes 0 rows.
    UPDATE tasks SET state = 'succeeded', lease_until = NULL
    WHERE run_id = $1 AND name = $2 AND attempts = $3 AND worker = $4 AND state = 'running';
    
    UPDATE attempts SET end_seq = nextval('attempt_seq'), outcome = $4
    WHERE run_id = $1 AND task = $2 AND attempt = $3;
    
    -- Each child loses one parent to wait on. The child whose count reaches 0 becomes ready. Two
    -- parents that finish at once both take the child's row lock, one after the other.
    UPDATE tasks c
    SET waiting_on = c.waiting_on - 1,
        state      = CASE WHEN c.waiting_on = 1 THEN 'ready' ELSE c.state END,
        ready_at   = CASE WHEN c.waiting_on = 1 THEN $3 ELSE c.ready_at END
    FROM runs r JOIN job_tasks d ON d.job_id = r.job_id
    WHERE r.id = $1 AND c.run_id = $1 AND c.name = d.name AND $2 = ANY (d.parents)
      AND c.state = 'waiting';
    
    -- One counter on the run row. The completion that takes it to 0 ends the run.
    UPDATE runs
    SET tasks_left = tasks_left - 1,
        state = CASE WHEN tasks_left = 1 AND state = 'running' THEN 'succeeded' ELSE state END
    WHERE id = $1
    RETURNING state;
    how a task becomes readystatus
    Count of parents left, updated as each parent finishesApproved
    Scan every waiting task each tickSmall DAGs
    An event per finish to a queueNeeds an outbox
    Check "all tasks done" to end the runWrite skew

    Tested: a random 40-task DAG on 8 worker goroutines with heartbeats and a reaper; two workers die mid-task. Every task succeeded once, no task started before its parents finished, and weights 3 and 1 split 8 claims 6 and 2.

    A claim is one indexed read per team plus SKIP LOCKED. Finishing a task counts down its children in the same transaction, so readiness is never stale.

    I

    Deep dive: leases, retries, at most once

    heartbeats, the reaper, fencing
    +0 s+10 s+20 s+30 s+40 s+50 s+60 s+70 s+80 sw1reaperw2attempt 1lease still heldstopslease endsattempt 1 lostbackoff 10 sattempt 2 ✓✕late completionrefusedheartbeat: lease + 30 s✕ refused: the attempt is stale
    guaranteehowstatus
    At least onceRetries after a lost lease, up to max_attemptsDefault
    Effectively onceAt least once, plus an idempotency key at the targetApproved
    At most oncemax_attempts = 1; a lost attempt fails the runA person decides
    Exactly once with any targetImpossible: a worker can die between the effect and the reportNot approved
    heartbeat and reappseudo code
    heartbeat(now, claim):                 // the worker, every 10 s
      UPDATE task SET lease_until = now + 30 s
        WHERE attempts = claim.attempt AND worker = claim.worker
              AND started_at + timeout >= now1
      0 rows: stop; the task is no longer yours2
    
    reap(now):                              // any node, every few seconds
      FOR EACH running task WHERE lease_until < now3
                               OR started_at + timeout < now
                          FOR UPDATE SKIP LOCKED:
        IF attempts < max_attempts:
          state = ready; ready_at = now + 10 s × 2^(attempts - 1)4
        ELSE:
          state = failed; the run fails; waiting tasks are skipped5
    1. 1A worker that heartbeats but never finishes still loses the task at its timeout.
    2. 2The worker must stop its side effects too. Fencing only protects the scheduler’s rows.
    3. 3The worker stopped heartbeating: dead, paused, or cut off. The scheduler cannot tell which.
    4. 4Exponential backoff: 10 s, then 20 s, capped at 5 minutes. Add jitter in production.
    5. 5Nothing downstream of a failed task runs. A person retries it, and the run resumes.
    Tested source Go: reap · SQL: heartbeat, stuck, retry or fail
    Go: reapgo
    
    // Reap finds running tasks whose lease expired or whose timeout passed, and ends each attempt
    // as lost or timed out: a retry after the backoff, or a failed run when attempts are used up.
    // Any node may reap; SKIP LOCKED keeps two reapers off the same task.
    func (s *Store) Reap(ctx context.Context, now time.Time) ([]Outcome, error) {
      var out []Outcome
      err := pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
        rows, err := tx.Query(ctx, q["stuck"], now)
        if err != nil {
          return fmt.Errorf("find stuck tasks: %w", err)
        }
        type stuck struct {
          c      Claim
          reason string
        }
        found, err := pgx.CollectRows(rows, func(r pgx.CollectableRow) (stuck, error) {
          var x stuck
          err := r.Scan(&x.c.RunID, &x.c.Task, &x.c.Attempt, &x.c.Worker, &x.reason)
          return x, err
        })
        if err != nil {
          return fmt.Errorf("find stuck tasks: %w", err)
        }
        for _, x := range found {
          o, err := s.endBadly(ctx, tx, now, x.c, x.reason)
          if err != nil {
            return err
          }
          out = append(out, o)
        }
        return nil
      })
      if err != nil {
        return nil, fmt.Errorf("reap: %w", err)
      }
      return out, nil
    }
    
    // endBadly ends one attempt as failed, lost or timeout, fenced like Succeed.
    func (s *Store) endBadly(ctx context.Context, tx pgx.Tx, now time.Time, c Claim, reason string) (Outcome, error) {
      o := Outcome{Claim: c, Reason: reason}
      err := tx.QueryRow(ctx, q["retry_or_fail"], c.RunID, c.Task, c.Attempt, c.Worker, now,
        float64(s.Backoff.Milliseconds()), float64(s.MaxBackoff.Milliseconds())).Scan(&o.State, &o.ReadyAt)
      if errors.Is(err, pgx.ErrNoRows) {
        return Outcome{}, ErrLeaseLost
      }
      if err != nil {
        return Outcome{}, fmt.Errorf("retry or fail %s: %w", c.Task, err)
      }
      if _, err := tx.Exec(ctx, q["log_end"], c.RunID, c.Task, c.Attempt, reason); err != nil {
        return Outcome{}, fmt.Errorf("log end: %w", err)
      }
      if o.State == "failed" {
        if _, err := tx.Exec(ctx, q["fail_run"], c.RunID); err != nil {
          return Outcome{}, fmt.Errorf("fail run %d: %w", c.RunID, err)
        }
      }
      return o, nil
    }
    
    SQL: heartbeat, stuck, retry or failsql
    -- Renew the lease only while this worker still holds this attempt and the timeout has not passed.
    UPDATE tasks
    SET lease_until = $5::timestamptz + $6 * interval '1 millisecond'
    WHERE run_id = $1 AND name = $2 AND attempts = $3 AND worker = $4 AND state = 'running'
      AND started_at + timeout >= $5;
    
    -- Running tasks whose lease expired (the worker stopped heartbeating) or that ran past their
    -- timeout (the worker heartbeats but never finishes).
    SELECT run_id, name, attempts, worker,
           CASE WHEN started_at + timeout < $1 THEN 'timeout' ELSE 'lost' END
    FROM tasks
    WHERE state = 'running' AND (lease_until < $1 OR started_at + timeout < $1)
    ORDER BY lease_until, run_id, name
    FOR UPDATE SKIP LOCKED;
    
    -- An attempt ended badly. Retry after an exponential backoff, or fail when attempts are used up.
    UPDATE tasks
    SET state       = CASE WHEN attempts < max_attempts THEN 'ready' ELSE 'failed' END,
        ready_at    = $5::timestamptz + least($6 * power(2, attempts - 1), $7) * interval '1 millisecond',
        worker      = NULL,
        lease_until = NULL
    WHERE run_id = $1 AND name = $2 AND attempts = $3 AND worker = $4 AND state = 'running'
    RETURNING state, ready_at;
    
    -- A task failed for good: the run fails and the tasks still waiting on it are skipped.
    WITH r AS (
      UPDATE runs SET state = 'failed' WHERE id = $1 AND state = 'running' RETURNING id
    )
    UPDATE tasks SET state = 'skipped' WHERE run_id = $1 AND state = 'waiting';
    lease
    30 s; heartbeat every 10 s, so two heartbeats can be lost.
    detection
    At most one lease after the last heartbeat, plus the reaper's interval.
    trade-off
    A shorter lease finds dead workers sooner but takes tasks from slow ones.

    Tested: a lost attempt, then a refused heartbeat and a refused late completion. Backoff of 10 s, then 20 s, then failed after 3 attempts. A task past its timeout. A one-attempt task that failed the run and skipped 4 tasks.

    A lease turns a dead worker into a timeout. The attempt number fences a worker that comes back, and idempotent tasks make the retry safe.

    J

    See it: one run, a worker that stops

    recorded from Postgres; the database after each step
    step 1 of 22

    Database after this step: run 1 is running

    ○ extract_ordersready○ extract_usersready… joinwaits on 2… loadwaits on 1… checkwaits on 1… publishwaits on 2
    taskstatetrylease until
    extract_ordersready··
    extract_usersready··
    joinwaiting··
    loadwaiting··
    checkwaiting··
    publishwaiting··

    Lease 30 s, heartbeat every 10 s, first retry after 10 s.

    extract_orders took 2 attempts and every other task 1. The worker that stopped came back and its completion was refused.

    K

    Failure cases

    what breaks, and why nothing runs twice
    eventresultwhy it is safesaved by
    A scheduler node dies mid-tickIts transaction rolls back.Another node's next tick finds the job still due and fires it.Transaction
    Two nodes fire the same timeThe second insert changes 0 rows.The unique key on (job, fire time).Unique key
    Every scheduler is down for hoursNo runs are created.On restart each job applies its catch-up policy once.next_fire_at
    A worker dies mid-taskHeartbeats stop.The lease ends; the reaper queues a retry after the backoff.Lease
    A paused worker comes backIt reports a stale attempt.The attempt and worker no longer match: 0 rows, refused.Fencing
    A task hangs but heartbeatsIt never finishes.The timeout ends the attempt as lost; the heartbeat is refused.Timeout
    A task fails every timeRetries at 10 s, 20 s, then failed.The run fails, downstream tasks are skipped, and an alert fires.max_attempts
    A worker dies after the side effectThe task runs again.The target dedupes on the run and task key.Idempotency
    Postgres fails overCalls fail for seconds.Workers retry; a lease that ran out meanwhile is retried, and idempotent tasks absorb it.Replica
    Node clocks disagreeA fast clock fires early or reaps early.Use the database's clock for due times and leases.now()
    L

    Scale ladder

    start simple; climb only on a signal
    Each step adds one component1One Postgres, N workers2+ spread fire times3+ partitions by day4+ shards by jobmore load →
    Task claims against demand101001k10k100kDemand, average: 278 tasks per secondDemand, average278Demand, :00 burst in 60 s: 2,000 tasks per secondDemand, :00 burst in 60 s2,000Claim and finish, 1 worker: 440 tasks per secondClaim and finish, 1 worker440Claim and finish, 8 workers: 2,000 tasks per secondClaim and finish, 8 workers2,000Claim and finish, 32 workers: 2,300 tasks per secondClaim and finish, 32 workers2,300tasks per second, log scale
    stepaddit handlesmove up when you see
    1One Postgres; every node ticks; workers claim with SKIP LOCKED.About 2,000 tasks a second with 8 workers; 32 workers add little (2,300).The :00 burst takes over a minute to drain.
    2Spread fire times: hash each job into a minute of its hour.120,000 tasks over 10 minutes is 200 a second.Task history slows vacuum and fills disks.
    3Partitions of tasks and attempts by day.About 12 GB a day; dropping a day is instant.Claims and heartbeats near one primary's write limit.
    4Shards by job; a run never crosses a shard.Each shard adds its own claim rate. Workers claim from every shard.Top of the ladder.

    Demand, derived in panel B. Capacity measured in the lab on one laptop; read it as orders of magnitude.

    One Postgres claims and finishes about 2,000 tasks a second. I spread fire times, partition by day, then shard by job when one primary is not enough.

    M

    Follow-ups

    what the interviewer asks next
    questionanswerdeeper
    You want exactly one scheduler. How?A lease row with a fencing token, renewed by the leader. Fence every write with the token, because a paused leader can wake up.T6
    Which locks does a claim take?A row lock on one task, skipped by others. No lock covers the run, so finishes and reads never wait on claims.T4
    Why SKIP LOCKED and not optimistic retries?Many workers want the same head of the queue. Optimistic writes would collide and retry; SKIP LOCKED hands each one a different row.T5
    Could the ready queue be Kafka or Redis?Yes, for throughput, with Postgres as the record. Publish ready tasks through an outbox, and keep the fenced finish in Postgres.B6
    A task moves money. How is a retry safe?The run and task form an idempotency key at the target. A multi-step task with external effects becomes a saga with compensations.T9, T7
    How do retries avoid a storm after an outage?Exponential backoff with jitter, a cap on attempts, and a limit on concurrent retries per target.O2
    How do you detect dead workers faster?Shorter heartbeats, or a failure detector that adapts to observed delays. Either way a slow worker can be taken for dead.X6
    Whose clock decides when a job is due?The database's. Node clocks drift, and a lease compares two times.X4
    What do you alert on?Runs that start late, ready-queue age, lease expiries and failed runs per team.O3
    How do you shard?By job id, so a run and all its tasks live on one shard. Workers poll every shard.X2
    N

    Drill

    predict, then reveal

    0 of 10 known

    1. Three scheduler nodes tick in the same second. Why does the 02:00 run exist once?

    2. Why not elect one leader that fires every job?

    3. A worker freezes for 55 s in the middle of a task. What happens?

    4. Does each task run exactly once?

    5. Both parents of join finish at the same moment. Can join start twice, or never?

    6. Why count tasks_left on the run row instead of checking that every task succeeded?

    7. No scheduler ran from 03:10 to 07:20. What does an hourly job do at 07:20?

    8. A daily 02:30 job runs in New York. What happens on the spring-forward day?

    9. One team queues 10,000 tasks. Do other teams wait behind them?

    10. Why does a claim read only the head of each team queue?

    O

    Numbers to say

    derived and measured
    claims
    About 440 tasks a second with 1 worker, 2,000 with 8, 2,300 with 32.
    tick
    One run of 5,000 tasks created in about 90 ms.
    storage
    About 500 B per task with its attempt and indexes.
    demand
    24 million tasks a day: 278 a second on average.
    lease
    30 s lease, 10 s heartbeat, 10 s first backoff.
    catch-up
    Down 03:10 to 07:20: all 4 runs, latest 1, none 0.
    runs
    3 nodes, 30 due jobs: 30 runs.

    Postgres 16 on an 8-core laptop shared with other jobs, 5,000 ready tasks in one run. Use the lab numbers as orders of magnitude.