Reliable Transactional Outbox & Inbox Pattern for Python — PostgreSQL + NATS JetStream
Documentation: ademboukabes.github.io/natsbox
Repository is
natsbox(importnats_outbox, PyPI/CLInats-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 publishingorder.created. - Phantom events:
order.createdis 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_eventscommit in the same PostgreSQL transaction. - Horizontal scaling:
SELECT FOR UPDATE SKIP LOCKEDlets you run multiple relay workers safely with zero duplicate claims. - End-to-end deduplication: sets stable
Nats-Msg-Idheaders for JetStream + providesInboxDeduplicator(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
/metricsHTTP endpoint (nats-outbox[metrics]). - Lightweight: pure Python async worker — no Kafka Connect, Zookeeper, or Debezium cluster required.
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
pip install "nats-outbox[cli]"
# With Prometheus metrics:
pip install "nats-outbox[cli,metrics]"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)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",
)export OUTBOX_DATABASE_URL="postgresql+asyncpg://user:pass@localhost:5432/myapp"
export OUTBOX_NATS_URL="nats://localhost:4222"
nats-outbox relay startOperational 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 cleanupfrom 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 ...| 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).
- V1 (Current):
PollingRelaywithSKIP 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 (
WALRelayviapgoutput) for sub-millisecond latency and strict LSN ordering.
See docs/roadmap.md for details.
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!