Send transactional emails through an outbox table
Database · PostgreSQL · advanced · greenfield
Adds an outbox for transactional email (receipts, signup confirmations), so that once the handlers use it a provider outage no longer fails the request and an email is never sent for an order that rolled back. `0014_email_outbox.sql` adds the `email_outbox` table with a partial index on the due rows. `outbox.enqueue` inserts on the caller's connection, inside the caller's transaction. `outbox_worker.run_batch` opens a transaction, claims up to 20 due emails with `FOR UPDATE SKIP LOCKED`, sends each one with `outbox-<id>` as the provider's idempotency key, records `sent` or a failed attempt with backoff, and commits; `main()` starts the threads through the existing `run_threads` supervisor and runs when the module is executed. The handlers switch to `enqueue` in a follow-up PR. Adds worker tests in `tests/test_outbox_worker.py`.
Shop backend, Python 3.12 with psycopg 3.2 and psycopg-pool 3.2 (plain SQL, no ORM) against one PostgreSQL 16 primary at the default isolation level, READ COMMITTED. Request handlers use `app.db.pool` (`with pool.connection() as conn:` commits the block's transaction on success and rolls it back on an exception). `app.db.worker_connection()` (existing) returns a dedicated `psycopg.connect(DATABASE_URL, autocommit=True)` connection; every worker in this codebase uses one per thread, and `conn.transaction()` on it opens an explicit transaction. `app.supervisor.run_threads(target, count, stop)` (existing) runs `target(stop)` in `count` threads and starts a call again after logging it when it raises. `app.mailer.send(to, subject, body, idempotency_key)` (existing) posts one email to the provider's HTTP API with a 10-second total timeout, returns the provider's message id, and raises `mailer.SendError` when the provider rejects the email, answers an error or does not answer in time; it does not touch the database. The provider records an idempotency key when the request arrives. A send whose key is still being handled or was accepted in the last 24 hours waits for the first request and returns that request's message id without delivering again; a rejected send frees the key. Keys are scoped to the provider API key, and each environment has its own API key (workers down for longer than 24 hours are out of scope). The provider usually answers in under 300 ms; the shop sends up to about 40,000 emails a day. The deployment runs the worker as its own process on each of the 3 pods with `python -m app.outbox_worker`. Nothing but the worker updates `email_outbox` rows. The worker database role has `idle_in_transaction_session_timeout = '1min'`, and the team accepts one open transaction per busy worker thread (at most 6). Migrations are plain SQL files applied in order by the existing runner, each in its own transaction unless its first line is `-- migrate: no-transaction`; `email_outbox` is a new table. The test suite (`tests/conftest.py`, existing) builds a fresh test database from the migrations and provides `fetch_one(sql, params)`.
Requirements
- This PR adds the outbox: the `email_outbox` table, `outbox.enqueue(conn, recipient, subject, body)` and the worker that sends the queue. `enqueue` queues an email on the caller's connection, inside the caller's transaction, so an email exists only if the change that caused it (an order, a signup) commits. Switching the request handlers from calling the mail provider directly to `enqueue` is a follow-up PR.
- An outbox worker sends the queued emails. It runs `OUTBOX_WORKER_CONCURRENCY` threads per pod (default 2) on 3 pods, all reading the same table. Two workers never send the same email at the same time while a worker holds it, and a worker busy with a batch does not hold up the others: they move on to emails nobody holds. Emails may be delivered in any order.
- A recipient gets each email once. A worker can die at any point (pod killed, connection lost); the emails it was handling then go back to the queue and are sent again, and the provider must not deliver them a second time.
- A failed send (the provider rejects it or times out, or `mailer.send` raises anything else) counts as one failed attempt for that email only: the other emails in the batch are still sent. The next attempt waits 1, 2, 4, then 8 minutes after the failed one; the fifth failed attempt marks the email `failed` and it is not tried again, even when that attempt timed out after the provider may have accepted the email (support checks the provider's log and resends it if needed). The last error is kept, at most 500 characters.
- An email whose send succeeds is marked `sent` with the time it was sent.
Files touched
- migrations/0014_email_outbox.sql
- app/outbox.py
- app/outbox_worker.py
- tests/test_outbox_worker.py