Transaction Outbox Pattern: Reliable Messaging in Distributed Systems with FastAPI & SQLAlchemy
Backend / Distributed Systems

Transaction Outbox Pattern: Reliable Messaging in Distributed Systems with FastAPI & SQLAlchemy

Guarantee zero lost events in microservices without 2PC using atomic database transactions and background relays.

August 2026Updated Aug 20, 202610 min read
By Diwash BhandariRead on Medium

In distributed architectures and microservices, one of the most common failure modes is the **dual-write problem**. When a service must persist business data to an ACID database and emit an event to a message broker (such as RabbitMQ or Kafka), executing them sequentially is inherently unreliable.

If your database write succeeds but your network fails before publishing the event to RabbitMQ, downstream services never discover what happened. Conversely, if you publish first and your database transaction rolls back, your event consumers process ghost data that never existed.

The **Transaction Outbox Pattern** solves this without requiring complex, slow two-phase commits (2PC).

The Dual-Write Vulnerability

Consider this naive implementation:

```python
@app.post("/orders")
async def create_order(payload: OrderCreate, db: AsyncSession = Depends(get_db)):
    # 1. Database write
    order = Order(**payload.model_dump())
    db.add(order)
    await db.commit()

2. Network call to message broker # If the process crashes or network drops here, the event is permanently lost! await broker.publish("order.created", {"order_id": str(order.id)}) return order ```

If an error or network partition occurs right after `await db.commit()`, your database has recorded the customer's payment, but the shipping service and notification system never hear about it.

How the Transaction Outbox Pattern Works

Instead of publishing to the external message broker inside the HTTP request handler, you write the event payload to an `outbox` table **within the exact same database transaction** that creates the business record.

Because both rows belong to the same local ACID transaction, PostgreSQL guarantees that either **both rows are saved or both are rolled back**.

```
Client Request
      │
      ▼
FastAPI Service
      │
      ├───────────────────────┬───────────────────────┐
      ▼                       ▼                       ▼
Primary Table (orders)  Outbox Table (events)   (Atomic Commit)
                              │
                              ▼
                        Relay Worker (Polling or Debezium CDC)
                              │
                              ▼
                    Message Broker (RabbitMQ / Kafka)
```

1. Defining the Outbox Table Model

In SQLAlchemy async:

```python
from datetime import datetime
import uuid
from sqlalchemy import String, DateTime, JSON, Index
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import Mapped, mapped_column

class OutboxEvent(Base): __tablename__ = "outbox_events"

id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4) event_type: Mapped[str] = mapped_column(String(100), nullable=False) aggregate_type: Mapped[str] = mapped_column(String(50), nullable=False) aggregate_id: Mapped[str] = mapped_column(String(100), nullable=False) payload: Mapped[dict] = mapped_column(JSON, nullable=False) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=datetime.utcnow) dispatched_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)

__table_args__ = ( Index("ix_outbox_pending", "created_at", postgresql_where=(dispatched_at.is_(None))), ) ```

The partial index on `dispatched_at IS NULL` keeps polling queries sub-millisecond fast even when millions of historical events accumulate.

2. Writing Atomically in FastAPI

```python
@app.post("/orders", status_code=201)
async def create_order(payload: OrderCreate, db: AsyncSession = Depends(get_db)):
    async with db.begin():
        # Step 1: Create Order entity
        order = Order(
            id=uuid.uuid4(),
            customer_id=payload.customer_id,
            total_amount=payload.total_amount,
            status="PENDING",
        )
        db.add(order)

Step 2: Stage Outbox record in SAME transaction outbox_entry = OutboxEvent( event_type="OrderCreated", aggregate_type="Order", aggregate_id=str(order.id), payload={ "order_id": str(order.id), "customer_id": str(payload.customer_id), "total_amount": float(payload.total_amount), }, ) db.add(outbox_entry)

Transaction committed atomically here return {"order_id": order.id, "status": "PENDING"} ```

3. The Relay Worker

A separate background relay worker polls pending outbox rows, pushes them to the broker, and flags them as dispatched:

```python
async def run_outbox_relay(db_factory, broker):
    while True:
        async with db_factory() as session:
            stmt = (
                select(OutboxEvent)
                .where(OutboxEvent.dispatched_at.is_(None))
                .order_by(OutboxEvent.created_at)
                .limit(100)
                .with_for_update(skip_locked=True)
            )
            events = (await session.execute(stmt)).scalars().all()

for event in events: await broker.publish(event.event_type, event.payload) event.dispatched_at = datetime.utcnow()

await session.commit() await asyncio.sleep(0.5) ```

Using `with_for_update(skip_locked=True)` allows you to run multiple horizontal relay workers without race conditions or duplicate deliveries.

Bottom Line

The Transaction Outbox Pattern is the enterprise standard for decoupling service communication while guaranteeing zero lost events. By pairing PostgreSQL partial indexes with `SKIP LOCKED` async workers, your distributed pipeline achieves bulletproof reliability.

Need help building reliable microservice architectures? [Get in touch](/contact).

Related articles

Want similar work?

I build RAG systems, FastAPI backends, AI agents, and licensing systems for teams worldwide. Let’s discuss your project.

Get in touch