StackPractices
advanced By Mathias Paulenko

Implement the Transactional Outbox Pattern with Python

Use the transactional outbox pattern to reliably publish domain events alongside database changes, with a relay processor, polling and CDC strategies, and at-least-once delivery.

Overview

Your service needs to update a database and publish an event to a broker. Those are two writes against two systems, and no transaction covers both. If the DB commits and the publish fails, the event is gone. If the publish goes out and the DB rolls back, downstream sees an event for something that never happened.

The fix: write the event to an outbox_events table inside the same database transaction as the business data, and let a separate relay push unpublished rows to the broker. Below is the full implementation: table schema, the atomic write, three relay styles (polling, Kafka transactions, CDC), ordering, retries, and Debezium.

When to Use This

  • Microservices that must reliably publish events after database changes
  • Event-driven architectures where lost events cause data inconsistency
  • Systems replacing distributed transactions with eventual consistency
  • Any application where database writes and message publishing must be atomic

Prerequisites

  • Python 3.11+
  • PostgreSQL
  • sqlalchemy, psycopg2, and confluent-kafka packages

Solution

1. Outbox Table Schema

CREATE TABLE outbox_events (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    aggregate_id VARCHAR(255) NOT NULL,
    aggregate_type VARCHAR(100) NOT NULL,
    event_type VARCHAR(100) NOT NULL,
    payload JSONB NOT NULL,
    headers JSONB DEFAULT '{}',
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    published_at TIMESTAMPTZ,
    status VARCHAR(20) NOT NULL DEFAULT 'PENDING',
    retry_count INTEGER NOT NULL DEFAULT 0,
    next_retry_at TIMESTAMPTZ
);

CREATE INDEX idx_outbox_status ON outbox_events (status, created_at);
CREATE INDEX idx_outbox_aggregate ON outbox_events (aggregate_id, created_at);

2. Writing Events to the Outbox

from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker
import json
import uuid
from datetime import datetime

engine = create_engine('postgresql://user:pass@localhost/myapp')
Session = sessionmaker(bind=engine)

class OrderService:
    def __init__(self, session_factory):
        self.Session = session_factory

    def create_order(self, order_data: dict):
        session = self.Session()
        try:
            # Insert the order
            order_id = str(uuid.uuid4())
            session.execute(
                text("""INSERT INTO orders (id, customer_id, total, status)
                        VALUES (:id, :cid, :total, 'PENDING')"""),
                {'id': order_id, 'cid': order_data['customer_id'], 'total': order_data['total']}
            )

            # Insert the outbox event in the SAME transaction
            event_id = str(uuid.uuid4())
            session.execute(
                text("""INSERT INTO outbox_events
                        (id, aggregate_id, aggregate_type, event_type, payload, headers)
                        VALUES (:id, :aid, :atype, :etype, :payload, :headers)"""),
                {
                    'id': event_id,
                    'aid': order_id,
                    'atype': 'Order',
                    'etype': 'OrderCreated',
                    'payload': json.dumps({
                        'orderId': order_id,
                        'customerId': order_data['customer_id'],
                        'total': order_data['total'],
                        'items': order_data.get('items', []),
                    }),
                    'headers': json.dumps({
                        'event_id': event_id,
                        'source': 'order-service',
                    }),
                }
            )

            # Both inserts commit atomically — no dual-write problem
            session.commit()
            return order_id

        except Exception:
            session.rollback()
            raise
        finally:
            session.close()

3. Relay Processor (Polling-Based)

import json
import logging
import time
from confluent_kafka import Producer
from sqlalchemy import create_engine, text
from datetime import datetime, timedelta

logger = logging.getLogger(__name__)

class OutboxRelay:
    def __init__(self, database_url: str, kafka_config: dict, batch_size: int = 100):
        self.engine = create_engine(database_url)
        self.producer = Producer(kafka_config)
        self.batch_size = batch_size
        self._running = True

    def run(self, poll_interval: float = 1.0):
        logger.info("Starting outbox relay...")
        while self._running:
            try:
                processed = self._process_batch()
                if processed == 0:
                    time.sleep(poll_interval)
            except Exception as e:
                logger.error(f"Relay error: {e}")
                time.sleep(5)

    def _process_batch(self) -> int:
        with self.engine.connect() as conn:
            # Select unpublished events with row-level locking
            events = conn.execute(
                text("""SELECT id, aggregate_id, aggregate_type, event_type, payload, headers
                        FROM outbox_events
                        WHERE status = 'PENDING'
                        ORDER BY created_at ASC
                        LIMIT :batch_size
                        FOR UPDATE SKIP LOCKED"""),
                {'batch_size': self.batch_size}
            ).fetchall()

            if not events:
                return 0

            for event in events:
                event_id, agg_id, agg_type, event_type, payload, headers = event

                topic = f'{agg_type.lower()}.events'
                key = agg_id.encode('utf-8')

                self.producer.produce(
                    topic=topic,
                    key=key,
                    value=payload.encode('utf-8') if isinstance(payload, str) else json.dumps(payload).encode('utf-8'),
                    headers=[(k, v.encode('utf-8')) for k, v in json.loads(headers).items()],
                    on_delivery=self._delivery_callback(event_id, conn),
                )

            self.producer.flush(timeout=10)
            conn.commit()
            return len(events)

    def _delivery_callback(self, event_id, conn):
        def callback(err, msg):
            if err:
                logger.error(f"Failed to publish event {event_id}: {err}")
                conn.execute(
                    text("""UPDATE outbox_events
                            SET retry_count = retry_count + 1,
                                next_retry_at = NOW() + INTERVAL '30 seconds'
                            WHERE id = :id"""),
                    {'id': event_id}
                )
            else:
                conn.execute(
                    text("""UPDATE outbox_events
                            SET status = 'PUBLISHED', published_at = NOW()
                            WHERE id = :id"""),
                    {'id': event_id}
                )
        return callback

    def stop(self):
        self._running = False

# Run the relay
relay = OutboxRelay(
    'postgresql://user:pass@localhost/myapp',
    {'bootstrap.servers': 'localhost:9092'},
    batch_size=100,
)
relay.run()

4. Relay with Kafka Transactions (Fewer Duplicates)

Kafka transactions make a whole batch publish atomically: either every event in the batch lands on the topic or none does. That removes partial-batch publishes: without them, a crash mid-batch leaves some rows published on the broker but still PENDING in the table, so they get sent again on the next poll.

It doesn’t give you end-to-end exactly-once. The DB update still happens after the Kafka commit, so a crash in that window re-publishes. Idempotent consumers remain the real dedup point; the transaction just shrinks the duplicate window.

class TransactionalOutboxRelay:
    """Publishes each batch inside one Kafka transaction to avoid partial publishes."""

    def __init__(self, database_url: str, kafka_config: dict, batch_size: int = 100):
        self.engine = create_engine(database_url)
        self.kafka_config = {**kafka_config, 'transactional.id': 'outbox-relay-txn'}
        self.producer = Producer(self.kafka_config)
        self.producer.init_transactions()
        self.batch_size = batch_size

    def process_batch(self) -> int:
        with self.engine.connect() as conn:
            events = conn.execute(
                text("""SELECT id, aggregate_id, aggregate_type, event_type, payload, headers
                        FROM outbox_events
                        WHERE status = 'PENDING'
                        ORDER BY created_at ASC
                        LIMIT :batch_size
                        FOR UPDATE SKIP LOCKED"""),
                {'batch_size': self.batch_size}
            ).fetchall()

            if not events:
                return 0

            # One transaction per batch, not per event — per-event txns kill throughput
            self.producer.begin_transaction()
            try:
                for event in events:
                    event_id, agg_id, agg_type, event_type, payload, headers = event
                    self.producer.produce(
                        topic=f'{agg_type.lower()}.events',
                        key=agg_id.encode('utf-8'),
                        value=payload.encode('utf-8') if isinstance(payload, str) else json.dumps(payload).encode('utf-8'),
                    )
                self.producer.commit_transaction()
            except Exception as e:
                logger.error(f"Kafka transaction failed: {e}")
                self.producer.abort_transaction()
                return 0

            # Mark the batch published after the Kafka commit succeeds
            for event in events:
                conn.execute(
                    text("""UPDATE outbox_events
                            SET status = 'PUBLISHED', published_at = NOW()
                            WHERE id = :id"""),
                    {'id': event[0]}
                )
            conn.commit()
            return len(events)

5. Relay with Change Data Capture (CDC)

"""Using PostgreSQL logical replication for CDC-based outbox relay.
This avoids polling and provides near-real-time event publishing."""

import psycopg2
from psycopg2.extras import LogicalReplicationConnection

class CDCOutboxRelay:
    def __init__(self, dsn: str, slot_name: str = 'outbox_slot'):
        self.conn = psycopg2.connect(
            dsn,
            connection_factory=LogicalReplicationConnection,
        )
        self.slot_name = slot_name

    def start(self):
        cur = self.conn.cursor()
        try:
            cur.create_replication_slot(self.slot_name, output_plugin='wal2json')
        except psycopg2.errors.DuplicateObject:
            pass  # Slot already exists

        cur.start_replication(
            slot_name=self.slot_name,
            options={'table-names': 'public.outbox_events'},
        )

        def process_msg(msg):
            import json
            changes = json.loads(msg.payload)
            for change in changes.get('change', []):
                if change['table'] == 'outbox_events' and change['kind'] == 'insert':
                    row = {col['name']: col['value'] for col in change['columnvalues']}
                    publish_to_kafka(row)
            msg.cursor.send_feedback(flush_lsn=msg.data_start)

        cur.consume_stream(process_msg)

6. Event Ordering with Partitioning

class OrderedOutboxRelay(OutboxRelay):
    """Publishes events ordered by aggregate_id using Kafka key-based partitioning."""

    def _process_batch(self) -> int:
        with self.engine.connect() as conn:
            # Group by aggregate_id to maintain ordering
            events = conn.execute(
                text("""SELECT id, aggregate_id, aggregate_type, event_type, payload, headers
                        FROM outbox_events
                        WHERE status = 'PENDING'
                        ORDER BY aggregate_id, created_at ASC
                        LIMIT :batch_size
                        FOR UPDATE SKIP LOCKED"""),
                {'batch_size': self.batch_size}
            ).fetchall()

            if not events:
                return 0

            for event in events:
                event_id, agg_id, agg_type, event_type, payload, headers = event

                # Use aggregate_id as Kafka key — same aggregate goes to same partition
                self.producer.produce(
                    topic=f'{agg_type.lower()}.events',
                    key=agg_id.encode('utf-8'),  # Key ensures ordering per aggregate
                    value=payload.encode('utf-8') if isinstance(payload, str) else json.dumps(payload).encode('utf-8'),
                )

                conn.execute(
                    text("""UPDATE outbox_events
                            SET status = 'PUBLISHED', published_at = NOW()
                            WHERE id = :id"""),
                    {'id': event_id}
                )

            self.producer.flush()
            conn.commit()
            return len(events)

7. Retry and Error Handling

class ResilientOutboxRelay(OutboxRelay):
    def _process_batch(self) -> int:
        with self.engine.connect() as conn:
            # Include retry-eligible events
            events = conn.execute(
                text("""SELECT id, aggregate_id, aggregate_type, event_type, payload, headers, retry_count
                        FROM outbox_events
                        WHERE status = 'PENDING'
                          AND (next_retry_at IS NULL OR next_retry_at <= NOW())
                          AND retry_count < 5
                        ORDER BY created_at ASC
                        LIMIT :batch_size
                        FOR UPDATE SKIP LOCKED"""),
                {'batch_size': self.batch_size}
            ).fetchall()

            if not events:
                return 0

            for event in events:
                event_id, agg_id, agg_type, event_type, payload, headers, retry_count = event

                try:
                    self.producer.produce(
                        topic=f'{agg_type.lower()}.events',
                        key=agg_id.encode('utf-8'),
                        value=payload.encode('utf-8') if isinstance(payload, str) else json.dumps(payload).encode('utf-8'),
                    )
                    self.producer.flush(timeout=10)

                    conn.execute(
                        text("""UPDATE outbox_events
                                SET status = 'PUBLISHED', published_at = NOW()
                                WHERE id = :id"""),
                        {'id': event_id}
                    )

                except Exception as e:
                    logger.error(f"Failed to publish {event_id}: {e}")
                    backoff = min(30 * (2 ** retry_count), 3600)  # Exponential backoff, max 1 hour
                    conn.execute(
                        text("""UPDATE outbox_events
                                SET retry_count = retry_count + 1,
                                    next_retry_at = NOW() + :backoff * INTERVAL '1 second'
                                WHERE id = :id"""),
                        {'id': event_id, 'backoff': backoff}
                    )

                    if retry_count >= 4:
                        conn.execute(
                            text("""UPDATE outbox_events SET status = 'FAILED' WHERE id = :id"""),
                            {'id': event_id}
                        )
                        logger.error(f"Event {event_id} moved to FAILED status")

            conn.commit()
            return len(events)

How It Works

The pipeline has one rule: the broker isn’t touched inside the business transaction.

sequenceDiagram diagram: participant S as Order Service
  • The business write and the outbox insert commit together, so there is no state where one exists without the other.
  • FOR UPDATE SKIP LOCKED lets you run several relay replicas; each grabs a different set of pending rows instead of blocking on the same ones.
  • The relay marks PUBLISHED only after the broker confirms. A crash between publish and mark means a redelivery, which is why the contract is at-least-once and consumers dedupe by event_id.
  • status + retry_count + next_retry_at give you a dead-letter path for free: events that exhaust retries surface as FAILED instead of silently dropping.

Variants

Debezium CDC (No Polling)

# Debezium connector config — streams outbox changes to Kafka
{
  "name": "outbox-connector",
  "config": {
    "connector.class": "io.debezium.connector.postgresql.PostgresConnector",
    "database.hostname": "localhost",
    "database.port": "5432",
    "database.user": "user",
    "database.password": "pass",
    "database.dbname": "myapp",
    "table.include.list": "public.outbox_events",
    "transforms": "outbox",
    "transforms.outbox.type": "io.debezium.transforms.outbox.EventRouter",
    "transforms.outbox.table.field.event.id": "id",
    "transforms.outbox.table.field.event.key": "aggregate_id",
    "transforms.outbox.table.field.event.type": "event_type",
    "transforms.outbox.table.field.event.payload": "payload"
  }
}

Multi-Tenant Outbox

-- Add tenant_id for multi-tenant isolation
ALTER TABLE outbox_events ADD COLUMN tenant_id VARCHAR(100) NOT NULL;
CREATE INDEX idx_outbox_tenant ON outbox_events (tenant_id, status, created_at);
# Relay processes events per tenant
events = conn.execute(
    text("""SELECT * FROM outbox_events
            WHERE status = 'PENDING' AND tenant_id = :tenant
            ORDER BY created_at ASC LIMIT 100 FOR UPDATE SKIP LOCKED"""),
    {'tenant': tenant_id}
).fetchall()

Best Practices

  • Use FOR UPDATE SKIP LOCKED: without it, relay replicas serialize on the same rows and you lose all the parallelism you set them up for.
  • Order by created_at and key messages by aggregate_id; every event for one aggregate lands on the same partition and stays in order.
  • Make consumers idempotent: at-least-once means the same event can arrive twice. Dedupe on event_id or make the side effect an upsert.
  • Set a retry limit with backoff: transient broker failures should retry, but after ~5 attempts move the row to FAILED so it stops blocking the queue.
  • Monitor outbox growth: alert on pending count and the age of the oldest PENDING row. A growing table means the relay is behind or dead.
  • Use CDC when latency matters: polling adds 1–5 seconds by design; Debezium streams the WAL in near-real-time. Start with polling, upgrade when the lag hurts.

Common Mistakes

  • Publishing outside the transaction: if you publish to the broker before the DB commits, a rollback leaves a phantom event. The outbox insert must live in the same transaction as the business write.
  • Not using SKIP LOCKED: without it, relay instances block each other instead of partitioning the work.
  • No retry strategy: a transient broker failure leaves events PENDING forever. Backoff plus a max retry limit, then FAILED for manual review.
  • Claiming exactly-once from the relay: Kafka transactions shrink the duplicate window but don’t close it; the DB mark still comes after the publish. Exactly-once lives in the consumer.
  • Polling too aggressively: a 10ms poll on an empty table just burns connections. Poll fast when there’s work, back off when idle.
  • Per-event Kafka transactions: one begin_transaction per event adds a full coordinator round-trip each time. Batch it.

See Also

Companion code: outbox relay implementations: the schema, the polling relay, Kafka transaction and CDC relays, and the Debezium config from this page.

Frequently Asked Questions

What is the dual-write problem?

Updating a database and publishing to a broker are two operations no transaction can cover. Whichever order you pick, a failure between them loses an event or emits a phantom one. The outbox turns it into one atomic DB transaction plus an asynchronous publish.

How does FOR UPDATE SKIP LOCKED work?

SELECT ... FOR UPDATE locks the rows it returns; SKIP LOCKED tells Postgres to skip rows another transaction already holds. Two relay replicas asking for 100 pending events get disjoint sets: parallel processing without a coordinator.

Can the outbox pattern guarantee exactly-once delivery?

No; it guarantees at-least-once. The relay can crash after publishing but before marking the row, which causes a redelivery. Kafka transactions reduce partial-batch duplicates but the DB mark still happens after the publish. Real deduplication belongs to the consumer: store processed event_ids or make handlers idempotent.

Should I use polling or CDC?

Polling first: it's a scheduled query and nothing else, at the cost of 1–5 seconds of latency. Move to CDC (Debezium, wal2json) when that lag matters or the outbox table sees heavy volume; the WAL becomes the delivery log and the table can be truncated aggressively.

How do I handle events that never publish?

Give the schema retry_count and next_retry_at, apply exponential backoff, and mark the row FAILED after the limit. Alert on FAILED rows: they need manual inspection, not another blind retry.