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.
- 1Every scheduler node ticks. A unique key on (job, fire time) makes a repeated fire a no-op, so no leader is needed.
- 2A run is a DAG of task rows. A task becomes ready in the transaction that marks its last parent succeeded.
- 3Workers claim tasks with SKIP LOCKED and hold a lease they renew by heartbeat. The attempt number fences a worker that lost its lease.
- 4Execution is at least once, so tasks are idempotent. A task that must never repeat gets one attempt, and a person decides.
"Design a scheduler that runs jobs on a schedule and in dependency order, at most once, across a cluster."
| question | answer 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. |
| requirement | target |
|---|---|
| Fire on time | run created within 5 s of its fire time |
| Runs per job and fire time | exactly 1, with any number of nodes |
| Recorded successes per task and run | exactly 1 |
| Dependency order | no task starts before all its parents succeed |
| Dead worker's task restarts | within lease + backoff: 40 s |
| Scheduler outage | catch 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.
- 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.
| call | result |
|---|---|
| PUT /jobs/:name | 200 with the next fire time. 422 for a bad cron line or a cycle. |
| POST /jobs/:name/runs | Trigger or backfill a fire time. 201, or 409 if that run exists. |
| PATCH /jobs/:name | Pause or resume. 200. |
| GET /runs/:id | Run state, every task, every attempt. |
| POST /runs/:id/tasks/:t/retry | 202 for a failed task; 409 otherwise. |
| POST /tasks/claim | Worker: 200 with run, task, attempt, lease end; 204 if nothing is ready. |
| POST /tasks/:id/heartbeat | 200 with the new lease end; 409 when the lease is lost. |
| POST /tasks/:id/complete | Body: 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.
- 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.
-- 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)
);- 1What a job does with fire times missed while no scheduler ran.
- 2One attempt means at most once: a lost attempt fails the run instead of running again.
- 3One run per fire time. Any node may fire; a second insert does nothing.
- 4Parents not yet succeeded. The task is ready when it reaches 0.
- 5The ready queue: one index ordered per team, so a claim reads the head of each team.
- 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.
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.
| tool | capability | what it gives this design | also used for |
|---|---|---|---|
| Postgres | FOR UPDATE SKIP LOCKED | Nodes split due jobs; workers split ready tasks; reapers split stuck tasks. Nobody waits. | Job queues, payroll batches |
| Postgres | Unique key and ON CONFLICT DO NOTHING | One run per job and fire time, from any number of nodes. | Idempotent APIs |
| Postgres | Conditional UPDATE and its row count | Heartbeat and finish only while the attempt and worker match: a fencing token. | State machines, leases |
| Postgres | Counters updated under the row lock | waiting_on releases a child once; tasks_left ends the run once. | Stock, seat counts |
| Postgres | Partial indexes on state | The ready queue per team and the running tasks by lease end stay small. | Outboxes, soft deletes |
| Postgres | Transactions | A tick creates the run, its tasks and the next fire time together, or none of them. | Every multi-row change |
| Postgres | Sequences inside transactions | The attempt log follows commit order, so dependency order can be checked. | Audit logs |
| Service | Cron parser and next-fire search in UTC | Fire times without a timer per job; catch-up walks them. | Billing cycles, reports |
| Service | Lease, heartbeat and backoff timers | A dead worker is noticed in one lease; retries wait longer each time. | Locks, client retries |
| Targets | Idempotency keys | A 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.
| who fires | where | status |
|---|---|---|
| Every node ticks; SKIP LOCKED; unique (job, fire time) | Postgres | Approved |
| One leader with a lease (T6) | Postgres | Fence its writes |
| One cron daemon on one machine | cron | Single point |
| An in-memory timer per job | Service | Lost on restart |
| Fire with no unique key, trust the lock | Postgres | Duplicates |
| policy | after the outage | use it for |
|---|---|---|
| all | 4 runs: 04:00, 05:00, 06:00, 07:00 | Each period's data matters: hourly rollups |
| latest | 1 run: 07:00 | Only fresh state matters: a cache rebuild |
| none | no run; next at 08:00 | A missed run has no value: a reminder |
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- 1Two nodes never wait for each other: each takes the due jobs the other has not locked.
- 2A fire time older than a 1-minute grace counts as missed. all keeps up to 24 of them.
- 3The unique key on (job, fire time). A node with a stale view fires again and inserts nothing.
- 4From now, not from the last fire time, so a long outage does not fire every missed minute.
- 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
// 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
}
// 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)
}
// 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
}
}
-- 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.
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- 1Read from an index per team. Sorting every ready task per claim measured 2.6 times slower with 5,000 ready.
- 2Fair share: the team furthest below its weight goes next. Priority classes still go first.
- 3Concurrent workers get different tasks and never block each other.
- 4Every later call carries it. A stale attempt changes 0 rows.
Tested source Go: claim and heartbeat · SQL: claim
// 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
}
-- 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 workers | status |
|---|---|
| First in, first out | One team floods |
| Strict priority only | Low priority starves |
| Priority classes, then weighted share per team | Approved |
| A worker pool per team | Idle capacity |
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- 1The worker lost the task to a later attempt. Its result is dropped, and nothing below changes.
- 2Two parents that finish at once update the child one after the other. Exactly one sees 1 and makes it ready.
- 3A counter on one row avoids write skew between the last two tasks.
Tested source Go: succeed · SQL: succeed, release, count down
// 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
}
-- 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 ready | status |
|---|---|
| Count of parents left, updated as each parent finishes | Approved |
| Scan every waiting task each tick | Small DAGs |
| An event per finish to a queue | Needs an outbox |
| Check "all tasks done" to end the run | Write 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.
| guarantee | how | status |
|---|---|---|
| At least once | Retries after a lost lease, up to max_attempts | Default |
| Effectively once | At least once, plus an idempotency key at the target | Approved |
| At most once | max_attempts = 1; a lost attempt fails the run | A person decides |
| Exactly once with any target | Impossible: a worker can die between the effect and the report | Not approved |
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- 1A worker that heartbeats but never finishes still loses the task at its timeout.
- 2The worker must stop its side effects too. Fencing only protects the scheduler’s rows.
- 3The worker stopped heartbeating: dead, paused, or cut off. The scheduler cannot tell which.
- 4Exponential backoff: 10 s, then 20 s, capped at 5 minutes. Add jitter in production.
- 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
// 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
}
-- 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.
Database after this step: run 1 is running
| task | state | try | lease until |
|---|---|---|---|
| extract_orders | ready | · | · |
| extract_users | ready | · | · |
| join | waiting | · | · |
| load | waiting | · | · |
| check | waiting | · | · |
| publish | waiting | · | · |
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.
| event | result | why it is safe | saved by |
|---|---|---|---|
| A scheduler node dies mid-tick | Its transaction rolls back. | Another node's next tick finds the job still due and fires it. | Transaction |
| Two nodes fire the same time | The second insert changes 0 rows. | The unique key on (job, fire time). | Unique key |
| Every scheduler is down for hours | No runs are created. | On restart each job applies its catch-up policy once. | next_fire_at |
| A worker dies mid-task | Heartbeats stop. | The lease ends; the reaper queues a retry after the backoff. | Lease |
| A paused worker comes back | It reports a stale attempt. | The attempt and worker no longer match: 0 rows, refused. | Fencing |
| A task hangs but heartbeats | It never finishes. | The timeout ends the attempt as lost; the heartbeat is refused. | Timeout |
| A task fails every time | Retries 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 effect | The task runs again. | The target dedupes on the run and task key. | Idempotency |
| Postgres fails over | Calls fail for seconds. | Workers retry; a lease that ran out meanwhile is retried, and idempotent tasks absorb it. | Replica |
| Node clocks disagree | A fast clock fires early or reaps early. | Use the database's clock for due times and leases. | now() |
| step | add | it handles | move up when you see |
|---|---|---|---|
| 1 | One 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. |
| 2 | Spread 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. |
| 3 | Partitions 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. |
| 4 | Shards 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.
| question | answer | deeper |
|---|---|---|
| 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 |
0 of 10 known
Three scheduler nodes tick in the same second. Why does the 02:00 run exist once?
Why not elect one leader that fires every job?
A worker freezes for 55 s in the middle of a task. What happens?
Does each task run exactly once?
Both parents of join finish at the same moment. Can join start twice, or never?
Why count tasks_left on the run row instead of checking that every task succeeded?
No scheduler ran from 03:10 to 07:20. What does an hourly job do at 07:20?
A daily 02:30 job runs in New York. What happens on the spring-forward day?
One team queues 10,000 tasks. Do other teams wait behind them?
Why does a claim read only the head of each team queue?
- 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.