Video in progress
How do you design a job scheduler that runs millions of scheduled tasks (reminders, deferred payments, subscription renewals) at exact times?
Tasks are stored in a database indexed by run_at, and several workers pick up the tasks coming due with FOR UPDATE SKIP LOCKED or partitioned ownership and hand them to a queue. Each task is idempotent, with a status and a lease — if a worker dies, the task moves to another one.
📖 Answer
If a single @Scheduled method picks up "those that are due" every minute and runs them, then with several pods it runs twice, and with many tasks it slows down. I start from the requirements: how many tasks per day (say 50 million), how exact the timing must be (seconds or minutes), whether at-least-once is enough.
Storage:
CREATE TABLE jobs (
id BIGINT PRIMARY KEY,
run_at TIMESTAMPTZ NOT NULL,
status VARCHAR(16) NOT NULL, -- SCHEDULED, RUNNING, DONE, FAILED
locked_by VARCHAR(64),
lease_until TIMESTAMPTZ,
attempts INT NOT NULL DEFAULT 0,
type VARCHAR(64) NOT NULL,
payload JSONB NOT NULL
);
CREATE INDEX ON jobs (run_at) WHERE status = 'SCHEDULED';
Picking up. Workers work in parallel:
UPDATE jobs SET status = 'RUNNING', locked_by = :me, lease_until = now() + interval '2 minutes'
WHERE id IN (
SELECT id FROM jobs
WHERE status = 'SCHEDULED' AND run_at <= now()
ORDER BY run_at LIMIT 500
FOR UPDATE SKIP LOCKED)
RETURNING *;
SKIP LOCKED saves workers from waiting on each other. The tasks they pick up are either run or handed to Kafka (a topic per task type) — the scheduler only says "it's time", and other services do the heavy work.
Failures. A worker died — a "reaper" sets RUNNING tasks whose lease_until has passed back to SCHEDULED. That means a task can run twice — every task type has to be idempotent (for example, a unique payment per periodId when renewing a subscription). A failed task: attempts++, run_at = now() + backoff, and after the limit, FAILED and an alert.
Scaling: a single Postgres handles several thousand tasks a second without trouble. Beyond that, the table is split into partitions by id hash and each partition is claimed by one worker with a lease. Tasks far in the future (end of the year) go in a separate "cold" table and move to the hot table as they come due.
There are peaks too: many tasks pile up at the same moment — a million subscription renewals at 00:00. Agree with the business to add a random shift to run_at (say, within an hour) — it also saves the payment provider downstream.
Monitoring: "the number of overdue tasks that haven't been picked up" and the age of the oldest waiting task — if both start to grow, the workers aren't keeping up.
Sign up to mark studied questions and save your progress.