// notes · distributed systems

Sending every message once with Postgres leases and fencing tokens

How a messaging service with retries, broker redeliveries and a recovery sweeper stops two workers from sending the same SMS, email, WhatsApp or push. Only Postgres and Celery; no extra lock service.

The problem

I built a customer engagement platform that sends Email, SMS, WhatsApp and Push through third-party providers. Sends run as Celery tasks. The same send can be attempted more than once for ordinary reasons:

All three are on purpose: they are how messages survive crashes. But each one is a chance to send twice, and a duplicate is not harmless. The customer gets the same OTP or offer twice, and the business pays the SMS provider twice.

A precise claim. Exactly-once delivery to an external API that is not transactional with your database is impossible in general. This design makes sure only one attempt holds the right to send a message at any time, and only that attempt can record the result. One narrow duplicate window remains, and it is logged, not hidden. That window gets its own section below.

Step 0: write the message before you queue it

Every send starts as a row, not as a task payload. The caller writes the message as pending with a unique idempotency key that names the intent, for example campaign:<campaign>:<recipient> or journey:<enrollment>:<step>, and only then enqueues a task carrying the row ID.

INSERT INTO message (idempotency_key, channel, recipient, body, status)
VALUES (:key, :channel, :recipient, :body, 'pending')
ON CONFLICT (idempotency_key) DO NOTHING
RETURNING id;                 -- no row back: this send already exists

This gives two things. The unique key collapses duplicate intents: a campaign that resumes after a crash cannot create a second message for the same recipient. And the broker never holds a rendered body or a phone number, only an ID, which matters when the recipient columns are encrypted personal data.

Step 1: claim the row with a lease and a fencing token

Before calling the provider, the worker tries to claim the row. Three columns do the work: lease_expires_at, claimed_at and claim_generation, a counter that goes up by one on every successful claim. That counter is the fencing token.

UPDATE message
SET    status           = 'sending',
       claimed_at       = now(),
       lease_expires_at = now() + interval '300 seconds',
       claim_generation = claim_generation + 1
WHERE  id = :id
  AND  (status IN ('pending', 'failed')
        OR (status = 'sending' AND lease_expires_at < now()))
RETURNING claim_generation;

Postgres row locking makes this safe under concurrency: of any number of workers running it at once for the same row, exactly one gets a row back. The others get nothing and return without calling the provider. A row that is already sent, or sending under a live lease, is never claimed.

The winner keeps the claim_generation it got back. That number is its proof of ownership for every write that follows.

Step 2: size the lease against the hard time limit

A lease is only safe if it cannot expire while its owner is still working. Clocks and network timeouts are not enough for that: a worker cannot tell that it stalled. So the lease is tied to something that actually ends the worker.

SettingValueRole
Send task hard time limit120 sCelery kills the worker process
Journey step hard time limit180 sSame, for sends made inside a journey step
Send lease300 sLonger than every hard limit

With the lease above the longest hard limit, a lease expires only after the process that held it has been killed. A slow provider call cannot lose its lease to a second worker.

Step 3: write the result only with the current token

-- success or recorded failure
UPDATE message
SET    status = :sent_or_failed, provider_message_id = :pid, sent_at = now(),
       lease_expires_at = NULL
WHERE  id = :id AND claim_generation = :g AND status = 'sending';

-- provider call raised: hand the row back so a retry can claim it at once
UPDATE message
SET    status = :prior_status, lease_expires_at = NULL   -- 'pending', or 'failed' if it already was
WHERE  id = :id AND claim_generation = :g AND status = 'sending';

If either update matches 0 rows, a newer claimant owns the message. The stale worker must not overwrite its result, bump campaign counters or fire events. It logs a warning with the provider message ID and stops.

Two attempts at the same message Attempt A claims the message with generation 7 and calls the provider. Attempt B arrives while A's lease is live; its claim matches zero rows and it returns without sending. A's process is killed by the 120 second hard time limit. At 300 seconds the lease expires. The sweeper claims with generation 8, sends, and records the result with generation 8. attempt A attempt B sweeper time → claim g=7 provider call hangs ✕ killed at 120 s claim → 0 rows, no send lease expires (300 s) claim g=8 send, finish g=8
B arrives while A's lease is live and backs off without sending. A cannot outlive its lease because the hard time limit kills it first. Only after the lease ends does the sweeper claim with a new generation.

Step 4: a sweeper for work that got lost

Two things can strand a message: a task lost after its row was written (the row stays pending), or a worker killed mid-send (the row stays sending until the lease ends). A periodic sweeper resends campaign messages that match all of these:

The sweeper goes through the same claim in step 1, so it can never race a live attempt.

The one window that stays open

A worker calls the provider, the provider accepts the message, and the worker dies before step 3. The row stays sending; after the lease ends, the next attempt sends again. That is a real duplicate, and no amount of locking in Postgres can prevent it, because the provider call is not part of the database transaction.

What you can do is keep it small and visible:

The send path, end to end

def send(message_id):
    g = claim(message_id)                          # step 1: None if someone else holds it
    if g is None:
        return                                     # already sent, or a live attempt owns it
    msg = load(message_id)
    try:
        result = provider.send(msg)
    except ProviderError:
        release(message_id, g)                     # back to pending/failed for the retry
        raise                                      # Celery retries with backoff
    if not finish(message_id, g, result):          # step 3: fenced write
        log.warning("stale send result", extra={"provider_id": result.id})
        return                                     # newer claimant owns counters and events
    bump_counters_and_fire_events(msg)

How it is tested

The bugs here only appear under concurrency, so the tests create the races on purpose:

Why not a queue with built-in guarantees?

Kafka transactions or SQS FIFO deduplication solve parts of this, but they add infrastructure and still stop at the edge of the external provider. The messages already live in Postgres for scheduling, journeys and reporting. Keeping the claim next to the data means one system to run, and the whole state of any send is visible in one SELECT.

Takeaways