Enqueue After Commit with an Outbox Table
Avoid the dual-write failure modes by storing each event in an outbox table in the same transaction as the business change, then relaying it to the broker with at-least-once delivery.
Contentsand lesson path
On this page
- Why it matters
- How the outbox works
- Worked example: an outbox table and a polling publisher
- Cleaning up the table, and change data capture (CDC)
- Check your understanding
- Apply it
- Review prompt
Lessons of Background Jobs & Task Queues
- What Belongs Outside the Request, and Which Broker Fits Concept · 20 min
- Lab: A Worker, a Broker and a Status Endpoint Lab · 30 min
- Designing Jobs for At-Least-Once Delivery Concept · 20 min
- Enqueue After Commit with an Outbox Table Worked example · 25 min
- Scheduled Jobs and Running Workers Day to Day Concept · 15 min
- Check: What Happens When the Worker Dies? Knowledge check · 8 questions
What you will learn
- Enqueue jobs consistently with database writes (transactional outbox or enqueue-after-commit) and run periodic jobs on a schedule.
01. Why it matters
A common defect in backend systems is the dual-write problem. In a workflow such as checkout, a money transfer or an account sign-up, the application must do two separate things:
- Mutate state in a primary relational database (e.g. insert an
Orderor debit anAccount). - Publish an asynchronous event or task into a message broker (e.g. notify RabbitMQ, Redis, or Kafka to trigger email delivery, fraud detection, or fulfilment).
The database and the broker are separate systems. They do not share a transaction coordinator (two-phase commit, or XA), so running the two steps one after the other in an HTTP handler leaves a window where one has happened and the other has not. Two-phase commit across a database and a broker is rarely used in practice: a stalled coordinator blocks both sides, and most brokers do not support it anyway.
Doing the two steps in sequence fails in one of two ways, depending on the order:
- Publish first, then commit: the application publishes the message to RabbitMQ, then the database commit fails (a unique-constraint violation, a serialization conflict, a deadlock or a database restart). It has sent a ghost event: an event about a change that was never saved. Downstream services consume it and try to fulfil, ship or invoice an order that does not exist in the database.
- Commit first, then publish: the application commits, then the process crashes, the network drops or the broker is unreachable during
publish(). The event is lost: the card was charged and the order row exists, but no worker ever gets the job to send the confirmation email, reserve stock or update the accounting system.
The transactional outbox pattern removes that window by turning the two writes into one: the event is stored in the same database transaction as the business change, so both commit or neither does. Sending it to the broker becomes a separate step that can be retried.
02. How the outbox works
Instead of calling the broker while it handles the customer's request, the application writes the event into an outbox table in its own database:
- Both rows in one transaction: between one
BEGINandCOMMIT, the service writes the business rows (orders,customers) and inserts an event row into theoutbox_eventstable. - Both or neither: a transaction is atomic. If it commits, both the domain change and the outbox event are stored durably. If the transaction aborts or encounters an unhandled exception, both records roll back cleanly. Ghost events (published for a change that never committed) are prevented, and an event can no longer be lost between the commit and the publish: it waits in the table until a relay sends it — provided a relay keeps running.
- A separate relay sends the events: a background process, the outbox relay, reads unpublished rows from the outbox table, sends them to the broker, and marks them as published (or deletes them) once the broker has accepted them.
The event is saved first and sent later, by a process that can retry. So every committed event is delivered at least once as long as the relay runs, and the broker is no longer on the request path.
The simpler alternative is to enqueue after commit. Many applications publish straight to the broker from an after-commit hook — SQLAlchemy's after_commit session event, or the transaction.on_commit style hooks of web frameworks — so nothing is sent for a transaction that rolled back. That removes ghost events with no extra table, but it leaves a small loss window: if the process dies, or the broker is unreachable, between the commit and the publish, the event is gone. Choose it when an occasional lost event is acceptable or can be repaired by a periodic reconciliation job (a cache refresh, a non-critical notification); choose the outbox when every event must arrive (payments, inventory, anything another service keeps its own state from).
Ordering is not free. An outbox delivers every event at least once, but not necessarily in order. Two relays using SKIP LOCKED take different batches and race to the broker, and a relay that crashes after publishing re-publishes its batch on restart, so an order.cancelled can overtake the order.placed it follows. When order matters per entity, run a single relay per partition key (for example, all events of one order go through one relay or one Kafka partition), or put a per-aggregate version number in each event and have consumers ignore anything older than what they have already applied.
03. Worked example: an outbox table and a polling publisher
An outbox needs two pieces: a write helper that adds the event in the business transaction, and a polling relay that several processes can run at once. The excerpt below uses SQLAlchemy 2.x async sessions and PostgreSQL row locks. It imports your own app.db (engine, AsyncSessionLocal, Base) and app.models (Order); it was checked against PostgreSQL 17 with SQLAlchemy 2.1.9 and psycopg 3.3.9, including a rollback and two relays running at the same time.
import json
import uuid
from datetime import datetime
from sqlalchemy import BigInteger, DateTime, String, Text, func, select
from sqlalchemy.orm import Mapped, mapped_column
from app.db import AsyncSessionLocal, Base
from app.models import Order
class OutboxEvent(Base):
__tablename__ = "outbox_events"
# Identity key: increases with every insert, so the relay can order by it
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
event_type: Mapped[str] = mapped_column(String(100))
payload: Mapped[str] = mapped_column(Text)
# Evaluated by PostgreSQL for each row (a Python value here would be
# computed once, at import time, and shared by every row)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
published: Mapped[bool] = mapped_column(default=False)
async def create_order_with_outbox(session, customer_id: str, total_cents: int):
"""Insert the order and its event in one transaction: both or neither."""
async with session.begin():
order_id = f"ord_{uuid.uuid4().hex[:10]}"
session.add(Order(id=order_id, customer=customer_id, total=total_cents))
# Same session, same transaction: no broker call on the request path
session.add(OutboxEvent(
event_type="order.placed",
payload=json.dumps({"order_id": order_id, "customer": customer_id}),
))
# Leaving session.begin() commits both rows, or rolls both back on error
return order_id
async def relay_once(broker_client) -> int:
"""Publish up to 50 pending events; return how many were sent."""
async with AsyncSessionLocal() as session, session.begin():
stmt = (
select(OutboxEvent)
.where(OutboxEvent.published.is_(False))
.order_by(OutboxEvent.id)
.limit(50)
.with_for_update(skip_locked=True) # other relays skip these rows
)
events = (await session.scalars(stmt)).all()
for event in events:
await broker_client.publish(topic=event.event_type, message=event.payload)
event.published = True
# Leaving session.begin() commits: a crash before this line means
# the events stay unpublished and are sent again later (duplicates)
return len(events)04. Cleaning up the table, and change data capture (CDC)
A busy outbox table can collect millions of rows a week, which bloats its indexes, adds VACUUM work and slows the relay query. Three operational practices keep it healthy:
- Scheduled purging and partitioning: a scheduled job runs during quiet hours to delete published events older than a reasonable retention window such as 7 days (
DELETE FROM outbox_events WHERE published = true AND created_at < NOW() - INTERVAL '7 days'). At very high volumes, partitioning the table by week or month works better: dropping an old partition withDROP TABLE(or detaching it first) is a quick metadata operation that frees its disk space at once and leaves no dead rows for autovacuum. - Poison-pill handling and retry caps: if a specific outbox event contains malformed JSON or triggers an unrecoverable broker rejection, a naive polling relay could get stuck retrying the same record for ever. A sturdier relay keeps an
attemptscounter and alast_errorcolumn. After exceeding maximum retries (e.g. 5 attempts), the record is marked asfailedor moved to a dead-letter outbox table, accompanied by a PagerDuty or Slack alert. - Change data capture (CDC) with Debezium: polling with
SKIP LOCKEDis simple and is often enough for modest event rates; measure yours. At higher rates, some teams replace polling with transaction log tailing. Tools like Debezium monitor PostgreSQL's Write-Ahead Log (WAL) directly using logical replication slots. When an outbox row is committed, Debezium streams the change event to Kafka or RabbitMQ with low latency and without polling queries. CDC is not free for the database, though: logical decoding uses CPU and I/O on the primary, and the replication slot pins WAL until the connector confirms it. If Debezium stops consuming, PostgreSQL keeps every WAL segment the slot still needs,pg_walgrows until the disk fills, and the primary stops accepting writes. Monitor the slot's lag (pg_replication_slots) and cap the damage withmax_slot_wal_keep_size. CDC also introduces additional operational infrastructure (Kafka Connect clusters and schema registries).
05. Check your understanding
06. Apply it
Inspect your application codebase for instances of the dual-write anti-pattern: places where a database commit() is immediately followed by a message broker publish() call. Create an outbox_events table and refactor the code to insert the event atomically within the domain transaction.
Implement a relay worker using select().with_for_update(skip_locked=True) that polls pending outbox records and publishes them to your message queue. Write automated integration tests that simulate database rollback to verify that no outbox events are persisted when order creation fails.
In the next lesson, you will learn how to run scheduled cron jobs reliably and operate worker pools in production environments.
07. Review prompt
Explain both failure modes of the dual-write problem. Describe how the transactional outbox pattern avoids them with a single database transaction, explain why outbox relay processes still require consumers to be idempotent, and contrast polling relays with Change Data Capture (CDC).
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.