Build notes

Idempotent Scheduled Notifications in Postgres: A Scheduler That Must Never Send Twice

Batdorj Byambadorj · · 5 min read

The alerts on my site are simple to describe. A trader picks a time, or a market session such as the London open, writes a line of text, and gets it as a Telegram message at that moment. It can repeat up to five times, one to sixty minutes apart.

Two failures end a trader's trust in a tool like this. The message does not come. Or it comes twice. This article is about preventing the second, and about how the thing that prevents it nearly caused the first.

A table and a 15 second worker

There is no setTimeout anywhere. An alert set for an hour from now has to outlive the process that accepted it, and it has to survive a restart. So alerts live in a Postgres table, and a worker wakes every 15 seconds and asks what is due.

That design has an obvious hole. Two things can see the same due alert: a process that restarts in the middle of its work, or two workers that happen to run at once.

One row decides who sends

Before anything is sent, the send is claimed in a second table. That table has a unique constraint on the alert and its occurrence number.

INSERT INTO web_fires (alert_id, occurrence_n)
VALUES ($1, $2)
ON CONFLICT DO NOTHING;

If the insert adds a row, this worker owns that send. If it adds nothing, the send is already claimed and the worker moves on.

The decision to send rests on the result of that one statement, and on nothing the worker remembers. The database will not hold two rows for the same occurrence, so no path through the code can send it twice.

What Telegram cannot tell you

Claimed is not the same as sent. Between the claim and Telegram's answer the process can die, and a row is left marked sending. Should the next run retry it?

Telegram's send call has no idempotency key. If the first attempt did arrive, a retry is a certain duplicate. So the rules are these:

  • A leftover sending row is never sent again. It becomes missed.
  • A retry happens only when the failure is unambiguous: a 4xx or 5xx answer, or a connection that was never established. Up to three times.
  • A timeout says nothing either way, so there is no retry.

Lateness has its own rule. An alert more than five minutes late is not sent at all. If the server is down for ten minutes, the trader does not get a burst of messages about moments that have passed. The alert is marked missed and the list shows it as "Not delivered".

The two reasons for missed, too late and left in sending, are counted separately. If the second count ever leaves zero, my assumption about that case was wrong, and I want to know.

The counter that worked for one day

The occurrence number began as a plain counter: 1, 2, 3 for an alert that repeats three times. For a one-off alert that is correct.

Then came session alerts, which fire every trading day. Monday's first repetition is (alert, 1). Tuesday's first repetition is (alert, 1) as well. The unique constraint, doing exactly its job, would have blocked the whole second day. The alert would have worked once and then stopped, with a clean log and the service showing online.

The constraint was right and the number was wrong. The fix was to give the occurrence number a single meaning: one scheduled moment, one value. For a session alert it is now the minute the message is due, counted from the Unix epoch. One-off alerts keep their 1 to n, because their moments are fixed by the time the trader entered.

That number is about 30 million. The column was a smallint, which ends at 32,767. Had I opened the feature without widening it, a trader would have created an alert, seen it in the list, and at firing time the insert would have overflowed inside a try/catch. I made the column bigint and not integer: if anyone ever changes the precision to seconds or milliseconds, integer overflows again.

I ran the new test against the old counter before trusting it. Day two's sends, (1/2) and (2/2), silently disappeared. The live proof came on 10 November, when the same Sydney alert fired for the second day in a row.

The Set that broke and failed no test

Widening the column had a side effect. The Postgres driver for Node returns bigint values as strings. The scheduler keeps a Set of the occurrences already claimed, so that it can skip them before trying the insert. Now it was holding one type and being asked about the other, and it never matched again.

Nothing was sent twice, because the decision sits on the insert, not on the Set. For the same reason no test failed: with or without a working Set, the end result was identical.

The fix is Number(r.occurrence_n), in one place. I left the driver's global type parser alone. Chat ids are bigint too, and turning every one of them into a number would have quietly broken string comparisons elsewhere.

The new test measures the Set's effect directly: on a second tick, no insert is attempted. It was also run against a deliberately broken version, to watch it fail.

What the earlier tests caught

The first scheduler tests, 35 of them, found a mistake in an SQL parameter that would have thrown on every tick in production. Not one alert would ever have fired. The code compiled cleanly and the service would have shown online.

If you build a scheduler like this

  • Keep schedules in the database and poll. Do not hold them in process memory.
  • Put a unique key on alert and occurrence, and let the insert decide who sends.
  • Define the occurrence as the scheduled moment itself, not as a counter that starts again, and check the column can hold that number.
  • When delivery is uncertain, do not resend. Mark it missed and show it.
  • Run every new test against the broken version first.

Batdorj Byambadorj

Batdorj Byambadorj has been trading forex for his own account since 2007, mostly gold. He is the sole developer of fx-alert and writes every article on this site himself.

About the author

← All articles