The problem
Two kinds of email were sent inside the web request: the welcome message, and the notice to subscribers when an article was published.
- Publishing opened a new mail connection for each subscriber, inside a request with a 30-second limit. More subscribers meant a slower, riskier publish button.
- The “sent” mark was written after the whole loop, so an interruption left no record of who had been emailed.
- Nothing was retried, and there was no record per person.
- Publishing from the admin site sent nothing at all.
I went looking because I suspected subscribers had missed an article. The mail server had accepted those messages, so I can’t call it a failed delivery. What I could say was that the system had no good way to answer the question.
Constraints
- An account and its welcome message must be created together or not at all.
- A problem with email must never stop an article from being published.
- A worker can be stopped at any point, including halfway through sending.
- Older articles must never notify anyone by surprise.
- The queue must not become a store of message bodies, links or addresses in logs.
How it works now
A sign-up inserts its email in the same transaction as the account. Publishing queues one row for each subscriber just after the publish commits. A systemd timer starts a worker every 15 seconds. It claims rows that are due, builds each message from current data, sends it and records what happened.
Claiming is the part that makes it safe:
with transaction.atomic():
rows = list(
OutboundEmail.objects
.select_for_update(skip_locked=True)
.filter(
Q(status=PENDING,
next_attempt_at__lte=now) |
Q(status=SENDING,
lease_expires_at__lte=now)
)
.order_by('next_attempt_at', 'id')
[:limit]
)
for row in rows:
row.status = SENDING
row.attempts += 1
row.lease_expires_at = now + LEASE
row.save(update_fields=[...])
skip_locked lets two workers run together without taking the same row. The second condition picks up rows whose worker never came back: a claim is a ten-minute lease, and an expired lease is available again.
- Worker 1 claims the email. The claim is a lease that lasts ten minutes.
- It is stopped before sending anything.
- Another worker looks for due email, sees a live lease and leaves the row alone.
- The lease runs out, so the row can be claimed again.
- The message is sent and the row is marked sent.
A slow worker can’t rewrite history
A worker might only look dead. If it returns after its lease has expired and another has taken over, its result has to be ignored:
def _finish(row, **fields):
"""Record an outcome unless another
worker re-claimed the row meanwhile."""
return OutboundEmail.objects.filter(
pk=row.pk,
status=SENDING,
attempts=row.attempts,
).update(**fields)
Every claim raises the attempt number, so it works as a receipt. An update from an old attempt matches no rows and changes nothing.
Decisions and tradeoffs
- At least once, not exactly once
- If the worker dies after the mail server accepts a message and before the row is marked sent, the message goes out again. No queue can close that gap alone. Each message keeps the same Message-ID across retries so mail clients can recognize the copy.
- Build the message at send time
- Rows hold a reference, not a body. If the article was unpublished or the reader unsubscribed in the meantime, the message is cancelled.
- Sort failures before retrying
- Timeouts and temporary errors are retried after 1, 5 and 30 minutes, then 2 and 6 hours. A refused recipient fails at once, because asking again can’t help.
- Publishing isn’t tied to the queue
- If queuing fails after an article is saved, the publish still succeeds. The failure is logged and counted, and a command queues the missing messages without repeating any.
- PostgreSQL as the queue
- At this volume a table is enough, and it lets an account and its email commit together. A message broker would add a service and take that away.
How it was tested
The tests interrupt workers between claiming and sending, expire leases, return results late, and run two workers against one queue to check they never claim the same row.
| Suite | Covers | Result |
|---|---|---|
| Queue and worker, backend | Interrupted workers, leases, retries, parallel claims, cancellation | 17 of 17 passed |
| Publication email, backend | First publish only, one row per reader, historical articles, admin publishing | 29 of 29 passed |
| Welcome email, backend | Queued with the account, deduplicated, no sending in the request | 17 of 17 passed |
Outcome and limits
Publishing no longer depends on how many people subscribe, and each message has its own record of attempts and failures. A “sent” row still means the mail server accepted the message. It doesn’t prove that anyone received it, and the system doesn’t claim to know.