The first version of the scheduler used RabbitMQ's delayed-message support as its calendar. A task was created, a message was published with a time-to-live, and the broker delivered it when the clock ran out.

It was elegant for about a week. Then the broker restarted during a failure drill, and the schedule went with it.

The lesson was not that RabbitMQ is unreliable. It is that a delivery mechanism is not a calendar. A broker is very good at moving messages from one process to another. It is not designed to be the durable, queryable record of what should happen at 14:05 next Thursday.

Diagram showing a task and an outbox row committed in one PostgreSQL transaction, a relay materializing a scheduled event, a due-timer poller publishing to RabbitMQ, and a coordinator dispatching to workers.
Figure 1 — The timer path. PostgreSQL owns the deadline; RabbitMQ only carries the wakeup after it becomes due.

Put the deadline in the database

The replacement design starts with a boring table:

CREATE TABLE scheduled_events (
  id             bigserial PRIMARY KEY,
  aggregate_id   uuid NOT NULL,
  kind           text NOT NULL CHECK (kind IN ('wakeup', 'retry')),
  destination    text NOT NULL,
  dedupe_key     text NOT NULL UNIQUE,
  payload        jsonb NOT NULL,
  headers        jsonb NOT NULL DEFAULT '{}'::jsonb,
  status         text NOT NULL DEFAULT 'pending',
  attempts       integer NOT NULL DEFAULT 0,
  available_at   timestamptz NOT NULL,
  published_at   timestamptz,
  last_error     text
);

CREATE INDEX scheduled_events_due
  ON scheduled_events (available_at, id)
  WHERE status = 'pending';

A due timer is now a row. It can be listed, counted, delayed, inspected, and repaired with SQL. If the broker disappears, the row remains. If the coordinator crashes, the row remains. If a deploy goes wrong at 2 a.m., the row remains.

The dedupe_key is what makes the timer safe to recreate. A wakeup for a specific task and scheduled instant can only exist once. A retry for a specific execution attempt can only exist once. Replaying the producer does not produce two timers.

The outbox is a transaction, not a queue

The task creation path originally wrote the task and published a message. That is a dual write. One of the two operations can succeed while the other fails, and no amount of retrying makes the pair atomic.

The scheduler commits both facts in one PostgreSQL transaction:

BEGIN;

INSERT INTO tasks (id, user_id, schedule, dispatch_at, status)
VALUES ($1, $2, $3, $4, 'scheduled');

INSERT INTO outbox (aggregate_type, aggregate_id, event_type, payload)
VALUES ('task', $1, 'task.scheduled', $5);

COMMIT;

No message is published inside that transaction. The transaction only records the intent to publish. A relay process reads committed outbox rows, publishes them, and marks them delivered.

For schedule and retry events, the relay does something slightly different: it materialises a scheduled_events row in the same transaction that marks the outbox row published. The outbox is a bridge from "this transaction committed" to "this event is now represented in the timer table."

That distinction matters. The outbox is not the calendar either. It is the durable handoff between the write that created the obligation and the timer that will eventually satisfy it.

The relay: publish, then mark

The relay claims committed outbox rows with FOR UPDATE SKIP LOCKED, publishes with publisher confirms and mandatory=True, then marks the row published. If the publish fails, it records the error and retries with backoff.

The order is deliberate. Marking the row before the publish would turn a crash into a lost event. Publishing before the mark can duplicate an event if the process dies in between. The system chooses the duplicate, because duplicates are recoverable and losses are not.

Every consumer has to be ready for that duplicate. The dispatch path is idempotent: it checks dispatch_at against database time and inserts at most one execution per (task_id, scheduled_for). A repeated wakeup finds the execution already present and does nothing.

Polling without a thundering herd

The timer poller runs on an interval, claims due rows with FOR UPDATE SKIP LOCKED, publishes them to scheduler.due, and marks them published. Multiple coordinator replicas can run the poller at the same time without handing the same timer to two publishers.

The query is intentionally narrow:

SELECT id, destination, payload, headers
FROM scheduled_events
WHERE status = 'pending'
  AND available_at <= now()
ORDER BY available_at, id
LIMIT $1
FOR UPDATE SKIP LOCKED;

The available_at index keeps the scan proportional to the number of due rows, not the total number of timers. The partial predicate keeps published history out of the hot path.

This is a polling design, and polling has a cost. The scheduler accepts that cost because it buys inspectability. A five-second poll interval is a visible, tunable property. A broker's internal timer wheel is not.

The poller also has a retry policy. A publish failure increments attempts, stores last_error, and pushes available_at forward with backoff. The timer is never silently dropped. After the maximum number of attempts it becomes visible as failed, which is exactly the kind of state an operator can act on.

Late is not lost

No timer system fires exactly on time. The useful guarantee is that a late timer still fires.

The scheduler's dispatch path checks the task's dispatch_at against now() from PostgreSQL. A wakeup that arrives late still produces an execution if the task is still pending. A wakeup that arrives after the task was cancelled is ignored. The timer is a hint that the deadline may have passed; the database decides whether work is still owed.

A separate reconciliation pass runs every two minutes with jitter. It scans for scheduled tasks whose dispatch_at is in the past and republishes them. This is the final safety net for broker restarts, poller lag, and rollback edge cases. It is allowed to be slow because it is not the primary path.

This layered design is repetitive on purpose. The timer poller handles the normal case. Reconciliation handles the abnormal case. The reaper handles expired leases. Each layer is simple enough to test on its own, and no layer is the only thing standing between a task and oblivion.

Backpressure is part of the timer design

A timer system that ignores overload turns a traffic spike into a queue full of work that is already late.

The coordinator samples queue depth and database utilisation with hysteresis. In enforce mode it can pause the due, result, outbox, and reconciliation consumers while keeping heartbeats alive. Admission control rejects new task creation with a 503 or 429 when the database pool or task queue is saturated.

The important word is hysteresis. A system that pauses at 80% and resumes at 79% will oscillate. The scheduler uses separate thresholds so a paused consumer stays paused until there is real headroom.

Backpressure is observable. The current state is exported as a metric, not inferred from logs. When a load test saturates the pool, the dashboard shows the pause and the recovery instead of a mysterious gap in throughput.

What the load test actually showed

The benchmark scheduled ten thousand tasks for the same instant. RabbitMQ peaked at 8,562 messages. The system drained the burst at roughly 50–61 tasks per second, with no task loss, no dead-letter messages, and no worker crashes. The p95 latency recovered from a 160 ms spike to a 76 ms floor.

Those numbers are useful, but the more important result was the shape of the recovery. The queue grew, the consumers paused, the timer table remained queryable, and the system caught up. Nothing depended on the broker remembering a deadline.

The benchmark is in the repository because a claim about fault tolerance without evidence is just a preference. The failure drills are there for the same reason.

The tradeoff, stated plainly

Database-backed timers are not free. They add a table, a poller, an index, and a retention policy. They put more read load on PostgreSQL. They introduce a delay equal to the poll interval. They require a reconciliation pass to cover the cases the poller misses.

The alternative — broker TTL — is simpler on the happy path and worse at the moment the broker restarts. For a scheduler whose entire purpose is to remember what should happen later, that trade is not close.

The rule that came out of the project is simple: the component that owns the truth should own the deadline. Everything else can be rebuilt from it.