Scheduled jobs that run once

Queues, Kafka and event-driven systems Mid-level Python 3.13+ PostgreSQL 17+ Reviewed By Best Latest Apps

Predict the output

Two replicas try to claim tonight's billing run. What does the final SELECT print?

SQL · PostgreSQL 17
CREATE TABLE runs (period date PRIMARY KEY, status text);
INSERT INTO runs VALUES ('2026-10-31', 'running')
  ON CONFLICT DO NOTHING;
INSERT INTO runs VALUES ('2026-10-31', 'running')
  ON CONFLICT DO NOTHING;
SELECT count(*) FROM runs;

Options
Hint 1 of 1

What's the primary key?

Choose an answer, then open Show answer below to check it.

Show answer

Answer: A 1

Correct. The second claim conflicts and does nothing, so only one replica runs it.

The primary key on period makes 'claim this run' a single atomic insert. Whichever replica inserts first wins, and the other's insert does nothing, so one row exists.

Why not the others?
  • B 2. The primary key on period rejects the second row.
  • C A unique violation. ON CONFLICT DO NOTHING absorbs it.
  • D 0. The first insert succeeds.
Result on PostgreSQL 17 (psql)
count
1

(1 row)

30-second answer

Cron in every replica runs the job once per replica. Run scheduling in one place (a Kubernetes CronJob, a cloud scheduler, or one scheduler process) and still guard the job itself: take a lock (PostgreSQL advisory lock or a lease) so overlapping runs can't happen, and make it idempotent by recording which periods are done. Schedules in UTC avoid daylight-saving surprises.

Practise saying it · 30 s. No recording, just a timer

Schedule jobs safely.

Say your answer out loud, then check which of these points you covered:

  • One scheduler
  • Lock against overlap
  • Idempotent per period
  • UTC
  • Catch-up

Deep dive

Kubernetes CronJob concurrencyPolicy: Forbid prevents overlapping runs.

Record each run (period, status) so a failed night can be re-run safely.

Spread jobs off the hour; everyone schedules at 00:00.

Long jobs should checkpoint progress.

Common mistakes

  • In-process schedulers in every replica.
  • Local-time schedules that run twice or skip on DST changes.
  • No record of which periods were processed.

Senior take & follow-ups

One scheduler, a lock, idempotency by period, UTC.

Follow-up questions

Think of your answer first, then open the hint.

  1. What if the scheduler misses a run?

    Show hint

    A catch-up check for unprocessed periods.

  2. Why UTC?

    Show hint

    Local times repeat or vanish at DST transitions.

Similar on Android: Exact alarms Android's alarms schedule work on one phone; here one scheduler must win across many servers.

Suggest a fix if something here is wrong or out of date.