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:
- a Celery retry after a provider error overlaps a slow first attempt,
- the broker redelivers a task, because tasks are
acks_lateand a worker died before acknowledging, - a recovery sweeper resends messages that look stalled.
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.
| Setting | Value | Role |
|---|---|---|
| Send task hard time limit | 120 s | Celery kills the worker process |
| Journey step hard time limit | 180 s | Same, for sends made inside a journey step |
| Send lease | 300 s | Longer 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.
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:
pendingfor 15 minutes since the last claim, orsendingwith an expired lease,- created less than 6 hours ago, so nobody gets yesterday's offer,
- claimed fewer than 5 times, so a poisoned message cannot loop forever,
- and the recipient has not opted out and is not inside their do-not-disturb window.
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 window is only the length of one provider call plus a crash.
- Every reclaim of an expired lease logs a warning that the previous claimant may already have sent, and every stale result logs its provider message ID, so a suspected duplicate can be traced.
- The next step is to pass the message ID to providers that accept an idempotency key or client reference, so they drop the second request themselves.
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:
- several threads claim the same row at once: exactly one gets a generation,
- several threads create and claim the same idempotency key at once: one row, one claim,
- a
sendingrow with a live lease is not reclaimed; with an expired lease it is, with the next generation, - a stale claimant cannot overwrite a newer claimant's result, and its release leaves the newer claim alone,
- concurrent calls to the email send path reach the fake provider exactly once.
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
- Write the message row, with a unique idempotency key, before you queue the task. Queue the ID, not the content.
- A lease without a fencing token does not protect you from a stale worker; check the token on every write that matters.
- Size the lease against something that really ends the worker, like a hard time limit, not against a network timeout.
- Name the duplicate window that remains, keep it small, and log it.