Concept
Work after commit
Why emails and other network work start only after the database commits, and what that does and does not guarantee.
A database transaction can undo its own writes. It cannot unsend an email, cancel a payment request or take back a file it uploaded. So the application keeps network work out of transactions: it commits first, then queues the work for a separate process.
This page shows what goes wrong otherwise, and how the code keeps the rule.
Rule: no network calls inside a transaction
Email, uploads and any other network request run after the commit, from a queue, never between
BEGIN and COMMIT.
Two places to send an email
Registration writes three things in one transaction: the stock hold, the order and its audit row. The buyer also needs an email with the payment details. Choose where that email is sent, then break something.
Illustration · one registration
- doneBegin the transaction
- doneReserve two tickets (conditional UPDATE)
- doneInsert the order
- doneInsert the audit row
- commitEnd the transaction
- doneQueue the payment email (after the commit)
- doneThe worker sends it
- Order
- pending_payment
- Stock
- Held
- Sent by the worker
The transaction held its locks only for database work; the email went out on its own time.
Sent inside the transaction, the email goes wrong both ways. If the audit insert fails after the email went out, the rollback removes the order but not the email: the buyer is told to pay for an order that does not exist. If the email service is down, the send fails and takes the order with it, so an email outage stops every registration. Even when nothing fails, the ticket type's row stays locked while the email service answers, and every other buyer of that ticket type waits behind a network call.
Sent after the commit, each failure stays in its own lane. A failed insert rolls back before any email is queued, so there is nothing to undo. A down email service delays the email, not the order: the worker retries it.
How the code keeps the rule
Services never send. After the transaction returns, the order service runs a hook, and a hook that fails is logged rather than allowed to undo a committed order:
async function afterCommit(hook: () => Promise<void>, what: string, orderId: string) {
try {
await hook();
} catch (err: unknown) {
logger.error({ orderId, err }, `orders.service: ${what} hook failed`);
}
}The hook only queues a job. Queuing waits at most three seconds, so a Redis outage cannot hang the buyer's request, and the job ID is made from the email kind and the order, so a repeated hook queues one job, not two:
export async function enqueueEmail(
kind: EmailKind,
orderId: string,
opts: { resend?: boolean; queue?: EmailQueue; timeoutMs?: number } = {},
): Promise<void> {
const jobId = emailJobId(kind, orderId, opts.resend ? Date.now() : undefined);
const q = opts.queue ?? getQueue();
let timer: NodeJS.Timeout | undefined;
const timeout = new Promise<never>((_, reject) => {
timer = setTimeout(
() => reject(new Error(`enqueue ${jobId} timed out`)),
opts.timeoutMs ?? ENQUEUE_TIMEOUT_MS,
);
});
try {
await Promise.race([
q.add(emailJobName(kind), { orderId }, { ...EMAIL_JOB_OPTIONS, jobId }),
timeout,
]);
} finally {
clearTimeout(timer);
}
logger.debug({ kind, orderId, jobId }, 'email job enqueued');
}The worker sends with five attempts and growing waits between them:
export const EMAIL_JOB_OPTIONS = {
attempts: 5,
// Four waits between five attempts — 30 s, 60 s, 2 min, 4 min (~7.5 min in
// all): a throttled provider clears well within that.
backoff: { type: 'exponential' as const, delay: 30_000 },
removeOnComplete: 500,
removeOnFail: 1000,
};A job carries only the order's ID. The worker reads the order again when it runs, and the email dispatcher skips a job whose order has moved on, so payment instructions are never sent for an order whose hold has already run out.
What it does not guarantee
Not an outbox
If the queue is unreachable at the moment of the commit, the job is lost: the failure is logged and nothing replays it. The order still stands, and its page shows the payment details. A transactional outbox, which stores the job in the same transaction, would close that gap at the cost of another table and a relay process.
The evidence:
- The producer tests check the timeout, the job ID and the retry options.
- The dispatcher tests cover failed hooks and stale jobs.
- The transactional email decision records why services never send.
Read next
Source revision: 4da5b5f · View this page's source