Full answer
The dual-write problem: db.commit() then broker.publish() can fail between the calls (event lost), or publishing first then committing can fail (event announced for data that does not exist).
Outbox design:
- Table
outbox(id uuid, aggregate_id, type, payload jsonb, created_at, published_at null). - In the request handler, inside one transaction: change business rows and insert the outbox row. Either both commit or neither.
- Relay process: loop that selects unpublished rows ordered by id (
SELECT ... WHERE published_at IS NULL ORDER BY id LIMIT 100 FOR UPDATE SKIP LOCKEDon PostgreSQL so multiple relays do not collide), publishes each to the broker, then setspublished_at. If the process crashes after publishing but before marking, the event is published again: at-least-once delivery. - Consumers keep a table of processed event IDs (unique constraint) and ignore duplicates, or make handlers naturally idempotent.
- Preserve ordering per aggregate by partitioning (message key = aggregate id) and processing outbox rows in order.
Alternatives for the relay: polling (simple, adds small latency), or change data capture with Debezium reading the write-ahead log (low latency, no polling load, more infrastructure). Some brokers also support transactional publishing, but that rarely spans the database too.
Operational concerns:
- Clean up old published rows (partition by date or delete in batches).
- Monitor the age of the oldest unpublished row, the main health signal.
- Retries with backoff and a poison-message strategy (park failing events after N attempts).
- Payload versioning: include a
schema_versionso consumers evolve safely. - In FastAPI, run the relay as a separate worker process or deployment (not inside the web workers), and keep handlers fast: write the outbox row and return.
- The inbox pattern on the consumer side mirrors this for exactly-once-effect processing.
import json
import uuid
from sqlalchemy import create_engine, select
from sqlalchemy.orm import DeclarativeBase, Mapped, Session, mapped_column
class Base(DeclarativeBase):
pass
class Order(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
item: Mapped[str] = mapped_column(unique=True)
class Outbox(Base):
__tablename__ = "outbox"
id: Mapped[int] = mapped_column(primary_key=True)
event_id: Mapped[str]
type: Mapped[str]
payload: Mapped[str]
published: Mapped[bool] = mapped_column(default=False)
engine = create_engine("sqlite://")
Base.metadata.create_all(engine)
def place_order(item: str):
with Session(engine) as db, db.begin(): # one transaction for both writes
order = Order(item=item)
db.add(order)
db.flush()
db.add(Outbox(event_id=f"evt-{order.id}", type="order.created", payload=json.dumps({"order_id": order.id, "item": item})))
place_order("laptop")
try:
place_order("laptop") # unique violation: nothing is written, no event either
except Exception as exc:
print("second order failed:", type(exc).__name__)
place_order("camera")
with Session(engine) as db:
print("orders:", db.scalars(select(Order.item).order_by(Order.id)).all(), "| outbox rows:", db.scalars(select(Outbox.event_id).order_by(Outbox.id)).all())
delivered: list[str] = []
attempts = {"n": 0}
def publish(row):
attempts["n"] += 1
if attempts["n"] == 2:
raise ConnectionError("broker unavailable") # simulate a failure on the second publish
delivered.append(row.event_id)
def relay_once():
with Session(engine) as db:
for row in db.scalars(select(Outbox).where(Outbox.published.is_(False)).order_by(Outbox.id)):
try:
publish(row)
except ConnectionError:
print("relay: publish failed, will retry", row.event_id)
break # keep order: stop at the first failure
row.published = True
db.commit()
relay_once()
relay_once()
print("delivered:", delivered)
seen: set[str] = set()
for event_id in delivered + ["evt-1"]: # a duplicate delivery
print(event_id, "handled" if event_id not in seen else "duplicate ignored")
seen.add(event_id)
Standalone script. Run it with `python file.py`; it uses an in-memory SQLite database and fakes the broker. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): second order failed: IntegrityError orders: ['laptop', 'camera'] | outbox rows: ['evt-1', 'evt-2'] relay: publish failed, will retry evt-2 delivered: ['evt-1', 'evt-2'] evt-1 handled evt-2 handled evt-1 duplicate ignored
Key points
- Write the event into an outbox table within the same transaction
- A relay publishes unsent rows and marks them
- Delivery is at least once; consumers deduplicate by event ID
- SKIP LOCKED lets several relays work safely; CDC is an alternative
- Monitor the age of the oldest unpublished event
Common mistakes
- Publishing to the broker inside the request before or after commit without an outbox
- Assuming exactly-once delivery from the relay
- Running the relay inside web workers
- Never cleaning up published rows
- Ignoring ordering for events of the same aggregate
Follow-ups
- How does Debezium CDC compare with polling?
- How would you implement an inbox table for consumers?
- How do you handle poison messages?
Tips
- Explain the dual-write problem
- Say at-least-once with idempotent consumers
- Mention monitoring lag