Subscribe

Designing a job scheduler that runs each job exactly once in practice

Exactly once is not something a scheduler can promise, but you can get very close. A Go and Postgres scheduler with one row per run, leases that expire, a fencing check and idempotent jobs, tested with three replicas, a stalled worker and missed runs.

Designing a job scheduler that runs each job exactly once in practice

Every app grows recurring jobs. Send the daily digest at 8, sync prices every 10 minutes, expire old links at midnight. On one server cron is quite enough. Then you run three copies of the service for availability, and now the digest goes out three times. Or you deploy at 7:59, and it goes out zero times.

This post is advanced level. You should know Go and be comfortable with Postgres transactions. I built a small scheduler in Go 1.27.3 with pgx v5.13 on Postgres 18.7, and tested it with three replicas, a stalled worker and a long outage. All the output below is from real runs.

💻 The full code for this tutorial is on GitHub: FenixAra/tutorials/System-Design/designing-a-job-scheduler-that-runs-each-job-exactly-once-in-practice. Clone it and run each step yourself.

What "exactly once" means here

Strictly, a distributed system can't promise a job runs exactly once. A worker can do the work and die a millisecond before it records that it did. Someone has to decide whether to run it again, and they can't know.

So the practical goal is this:

  • every scheduled slot gets exactly one run record, no matter how many schedulers are up
  • a run is retried if its worker disappears (at-least-once execution)
  • the job itself is idempotent, so a retry does no harm

At-least-once plus idempotency looks like exactly once from outside. That's the whole design in one line.

Requirements and the shape of it

  • Many instances of the app, any of them can die at any time, no special "scheduler box".
  • Jobs every few seconds up to once a day.
  • After downtime, each job decides what to do about the runs it missed.
  • Postgres is already there. I didn't want another moving part.
schedules (name, every, next_run_at, catch_up)
     |
     |  Tick: any instance, FOR UPDATE SKIP LOCKED
     v
job_runs (name, scheduled_for) UNIQUE   <- one row per slot
     |
     |  Claim: any instance, lease with locked_until
     v
worker runs the job + marks done in one transaction, guarded by attempt number

Two steps. Turning a schedule into run rows, and executing run rows. Splitting them is basically what makes the rest simple.

The tables

CREATE TABLE schedules (
    name        text PRIMARY KEY,
    every       interval    NOT NULL,
    next_run_at timestamptz NOT NULL,
    catch_up    text        NOT NULL DEFAULT 'latest'
                CHECK (catch_up IN ('all', 'latest'))
);

CREATE TABLE job_runs (
    id            bigserial PRIMARY KEY,
    name          text        NOT NULL REFERENCES schedules (name),
    scheduled_for timestamptz NOT NULL,
    status        text        NOT NULL DEFAULT 'pending'
                  CHECK (status IN ('pending', 'running', 'done', 'failed')),
    attempts      int         NOT NULL DEFAULT 0,
    locked_by     text,
    locked_until  timestamptz,
    finished_at   timestamptz,
    UNIQUE (name, scheduled_for)
);

CREATE INDEX job_runs_claimable ON job_runs (scheduled_for)
    WHERE status IN ('pending', 'running');

UNIQUE (name, scheduled_for) is the most important line in this post. Whatever goes wrong upstream, a slot can only become one row.

Leader election or row locks

There are two common ways to stop three instances from all firing the same job.

The first is to elect one leader and only let it schedule. In Postgres that's a session advisory lock on a connection you keep open.

func TryLead(ctx context.Context, conn *pgx.Conn) (bool, error) {
    var ok bool
    err := conn.QueryRow(ctx, `SELECT pg_try_advisory_lock($1)`, schedulerLockID).Scan(&ok)
    return ok, err
}

It works. When I ran it instance a got the lock, b didn't, and when a's connection closed, b took over straight away.

a leader=true b leader=false
after a disconnects: b leader=true

But the leader is a single point of slowness, and the lock is tied to a TCP connection. A leader whose connection drops but whose process keeps going will think it's still the leader for a while. You are back to needing a second safety net anyway.

The second way, which I prefer, is to let every instance do everything and let row locks and the unique key sort it out. No election. That's what the rest of this post builds. If you've read Postgres job queues in golang, the claim step will look familiar.

Tick: turning schedules into runs

Every instance calls Tick every 200 ms. It locks the due schedule rows with SKIP LOCKED, so two instances never wait on each other, inserts the run rows and moves next_run_at forward.

rows, err := tx.Query(ctx, `
    SELECT name, extract(epoch FROM every)::float8, next_run_at, catch_up, now()
    FROM schedules
    WHERE next_run_at <= now()
    FOR UPDATE SKIP LOCKED`)
// ... scan into due ...
for _, d := range all {
    slots, newNext := dueSlots(d.next, d.every, d.now, d.policy)
    for _, s := range slots {
        tag, err := tx.Exec(ctx, `
            INSERT INTO job_runs (name, scheduled_for) VALUES ($1, $2)
            ON CONFLICT (name, scheduled_for) DO NOTHING`, d.name, s)
        // ...
    }
    _, err := tx.Exec(ctx, `UPDATE schedules SET next_run_at = $2 WHERE name = $1`, d.name, newNext)
    // ...
}
return created, tx.Commit(ctx)

I take now() from database only and not from the Go process. Three containers can have three slightly different clocks; the database has one.

Missed runs after downtime

If every instance was down for an hour, what should happen to the six runs of a ten minute job? It depends on the job, so it's a column. all runs every missed slot, for things like "sync prices for each 10 minute window". latest runs once, for things like a digest where sending six copies is worse than useless.

func dueSlots(next time.Time, every time.Duration, now time.Time, policy string) ([]time.Time, time.Time) {
    var slots []time.Time
    for !next.After(now) {
        slots = append(slots, next)
        next = next.Add(every)
    }
    if policy == "latest" && len(slots) > 1 {
        slots = slots[len(slots)-1:]
    }
    return slots, next
}

My downtime demo sets both jobs' next_run_at to 55 seconds ago with a 10 second interval.

tick created 7 runs
  send-digest  1 runs
  sync-prices  6 runs
second tick created 0 runs

Six for all, one for latest, and nothing again on the next tick. This is the same idea as Persistent=true on the systemd timer that runs the nightly backup for this blog: if the box was off at 20:00, it runs once when it comes back, not once for every night it missed.

Claim with a lease

A worker claims the oldest claimable run. Claimable means pending, or running with a lease that has expired, because its worker probably died.

err := db.QueryRow(ctx, `
    UPDATE job_runs
    SET status = 'running',
        attempts = attempts + 1,
        locked_by = $1,
        locked_until = now() + make_interval(secs => $2)
    WHERE id = (
        SELECT id FROM job_runs
        WHERE scheduled_for <= now()
          AND (status = 'pending'
               OR (status = 'running' AND locked_until < now()))
        ORDER BY scheduled_for
        LIMIT 1
        FOR UPDATE SKIP LOCKED)
    RETURNING id, name, scheduled_for, attempts`,
    worker, lease.Seconds()).Scan(&r.ID, &r.Name, &r.ScheduledFor, &r.Attempt)

I pass the lease as seconds and build the interval with make_interval in SQL, so there's no question about how a Go time.Duration gets encoded. Set the lease well above how long the job normally takes. Too short and healthy jobs get stolen.

Finishing safely

See, here is the case that bites. Worker A claims a run, then stalls: a long GC pause, a slow network call, a laptop lid. Its lease expires and worker B claims the same run. Then A wakes up and finishes too.

The attempts counter fixes it. Every claim bumps it, so it works as a fencing token. A finishes with attempts = 1, but the row now says 2, so A's update matches nothing. And because the job's own write is in the same transaction, A's work is rolled back with it.

runKey := fmt.Sprintf("%s@%s", r.Name, r.ScheduledFor.UTC().Format(time.RFC3339))
if _, err := tx.Exec(ctx, `
    INSERT INTO daily_reports (run_key, created_by) VALUES ($1, $2)
    ON CONFLICT (run_key) DO NOTHING`, runKey, worker); err != nil {
    return err
}

tag, err := tx.Exec(ctx, `
    UPDATE job_runs SET status = 'done', finished_at = now()
    WHERE id = $1 AND status = 'running' AND attempts = $2`, r.ID, r.Attempt)
if err != nil {
    return err
}
if tag.RowsAffected() == 0 {
    return ErrLostLease // rollback undoes the report insert too
}
return tx.Commit(ctx)

The crash demo plays exactly that, with a 1 second lease.

worker-a claimed run 14 attempt 1, then stalls
worker-b: nothing to claim while worker-a holds the lease
worker-b claimed run 14 attempt 2 after the lease expired
worker-b finished
worker-a wakes up and tries to finish: lease lost, another worker owns this run now
reports=1 written by worker-b

One report. That's the result I wanted.

When the job's side effect lives outside the database, like an email or a call to a payment API, you can't put it in the transaction. Then the run key becomes the idempotency key you send to that API, or you record the intent in the database and send it from an outbox. The outbox pattern and idempotent payment webhooks cover both halves.

Three replicas at once

Finally the test that matters. Three instances, each running tick and claim every 200 ms, one job due every second, for 6 seconds.

docker run -d --name sched-pg -e POSTGRES_PASSWORD=dev -p 127.0.0.1:45917:5432 postgres:18-alpine
export DATABASE_URL=postgres://postgres:dev@127.0.0.1:45917/postgres
go run . -demo replicas
go run . -demo downtime
go run . -demo crash
go run . -demo leader
done runs=6 distinct slots=6 reports=6 retries=0
  instance-1 ran 2
  instance-2 ran 3
  instance-3 ran 1

Six slots, six runs, six reports and the work spread over all three instances. No coordination code anywhere besides SQL.

There's also a plain unit test for dueSlots (go test ./...), since the catch-up maths is the bit I'd most likely break later.

What I'd add before production

  • A failed status after N attempts, and an alert on it, so a job that always crashes doesn't retry forever.
  • Delete or archive done rows older than a month. That table only grows.
  • Retries with backoff and jitter instead of retrying the instant the lease ends, see designing for failure.
  • A metric for "oldest pending run". If that number climbs, workers are stuck or too few.

The leader version is less code, I'll admit. But the unique key and the attempt check keep working when everything else is confused, and that's the part I'd want at 3 in the morning.