Skip to content
ademboukabesPublic

About

Reliable transactional outbox pattern for Postgres + NATS JetStream in Python

Topics

Resources

Code of conduct

Contributing

Stars

30 stars

Watchers

0 watching

Forks

Repository files navigation

natsbox (nats-outbox)

Reliable Transactional Outbox & Inbox Pattern for Python — PostgreSQL + NATS JetStream

CI Docs PyPI version Python License: MIT Typed: mypy strict

Documentation: ademboukabes.github.io/natsbox

Repository is natsbox (import nats_outbox, PyPI/CLI nats-outbox).


Why nats-outbox?

In event-driven services, saving to PostgreSQL and publishing to NATS JetStream are two separate network calls. Without a distributed transaction, a crash or rollback leaves your system silently out of sync:

  • Lost events: the DB commits Order, then the process crashes before publishing order.created.
  • Phantom events: order.created is published, then the DB transaction rolls back.

nats-outbox implements the Transactional Outbox Pattern for async Python (SQLAlchemy 2.0 + asyncpg + nats-py):

  • Atomic writes: domain rows and outbox_events commit in the same PostgreSQL transaction.
  • Horizontal scaling: SELECT FOR UPDATE SKIP LOCKED lets you run multiple relay workers safely with zero duplicate claims.
  • End-to-end deduplication: sets stable Nats-Msg-Id headers for JetStream + provides InboxDeduplicator (INSERT ... ON CONFLICT DO NOTHING) for idempotent consumers.
  • Resilience & DLQ: exponential backoff on failures, dead-lettering after max_retries, and CLI commands (cleanup, requeue --dry-run) for operations.
  • Observability: optional Prometheus /metrics HTTP endpoint (nats-outbox[metrics]).
  • Lightweight: pure Python async worker — no Kafka Connect, Zookeeper, or Debezium cluster required.

How It Works

sequenceDiagram
    participant App as Application (FastAPI / Service)
    participant DB as PostgreSQL
    participant Relay as nats-outbox Relay
    participant NATS as NATS JetStream

    Note over App,DB: 1. Atomic Transaction (outbox_transaction)
    App->>DB: BEGIN
    App->>DB: INSERT INTO orders (...)
    App->>DB: INSERT INTO outbox_events (status='pending')
    App->>DB: COMMIT

    Note over DB,NATS: 2. Asynchronous Delivery (PollingRelay)
    loop Polling tick (or immediate drain)
        Relay->>DB: SELECT ... FOR UPDATE SKIP LOCKED
        DB-->>Relay: pending batch
        Relay->>NATS: Publish (Nats-Msg-Id = event_id)
        NATS-->>Relay: PubAck
        Relay->>DB: UPDATE status='published'
    end
Loading

Quick Start

1. Install

pip install "nats-outbox[cli]"
# With Prometheus metrics:
pip install "nats-outbox[cli,metrics]"

2. Create the Outbox Table

Apply migrations/001_create_outbox_events.sql (or integrate with Alembic — see the Alembic guide), or bootstrap tables in dev:

from sqlalchemy.ext.asyncio import create_async_engine
from nats_outbox.core.models import create_tables

engine = create_async_engine("postgresql+asyncpg://user:pass@localhost:5432/myapp")
await create_tables(engine)

3. Publish Events Atomically (Producer)

from sqlalchemy.ext.asyncio import AsyncSession
from nats_outbox.core.outbox import outbox_transaction

async def create_order(session: AsyncSession, user_id: int, amount: float) -> None:
    # Commits your domain model + outbox event in one PostgreSQL transaction
    async with outbox_transaction(session) as tx:
        order = Order(user_id=user_id, amount=amount)
        tx.add(order)
        await session.flush()

        tx.publish_event(
            subject="order.created",
            payload={"order_id": str(order.id), "amount": amount},
            aggregate_id=str(order.id),
            aggregate_type="Order",
        )

4. Start the Relay Worker

export OUTBOX_DATABASE_URL="postgresql+asyncpg://user:pass@localhost:5432/myapp"
export OUTBOX_NATS_URL="nats://localhost:4222"

nats-outbox relay start

Operational CLI commands:

# Inspect failed (dead-lettered) events before requeuing
nats-outbox relay requeue --dry-run
nats-outbox relay requeue

# Delete published events older than OUTBOX_RETENTION_DAYS (e.g. from cron)
nats-outbox relay cleanup

5. Deduplicate on the Consumer Side (Optional Inbox Pattern)

from nats_outbox.core.inbox import InboxDeduplicator

async with session.begin():
    dedup = InboxDeduplicator(session, consumer_group="billing")
    if await dedup.is_duplicate(event_id):
        return  # already processed

    # ... execute side effects atomically with the inbox insert ...

Comparison

Approach Operational Overhead Event Format Scaling & Safety
Rolling your own loop Low initially Custom Easy to miss SKIP LOCKED, backoff, Nats-Msg-Id, DLQ
Debezium + Kafka Connect High (JVM, Connect, Kafka) Raw DB CDC rows (before/after) Strong ordering, targets Kafka
nats-outbox Single Python worker Explicit business events SKIP LOCKED, backoff, DLQ, JetStream dedup

See docs/comparisons.md for trade-offs (including strict FIFO vs multi-replica SKIP LOCKED).


Roadmap

  • V1 (Current): PollingRelay with SKIP LOCKED, exponential backoff, DLQ + CLI recovery, InboxDeduplicator, Prometheus metrics.
  • V1.x: FastAPI Depends() helpers, interactive DLQ inspection in CLI, OpenTelemetry trace propagation in NATS headers.
  • V2: PostgreSQL Logical Replication (WALRelay via pgoutput) for sub-millisecond latency and strict LSN ordering.

See docs/roadmap.md for details.


Contributing & License

Contributions, bug reports, and feature ideas are welcome! Please read CONTRIBUTING.md and our Code of Conduct before opening a PR.

Licensed under the MIT License. If nats-outbox saves you time in production, consider giving the repo a star!

About

Reliable transactional outbox pattern for Postgres + NATS JetStream in Python

Topics

Resources

Code of conduct

Contributing

Stars

30 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages