Outbox Pattern Implementation in Python
14-day free trial
Try SeekerPro free for 14 days.
Full access while you try it · then $15.99/mo · cancel anytime
Start your 14-day free SeekerPro trial →30-day money-back guarantee · Cancel anytime
Not checking a site today? Turn this topic into a ready to paste AI prompt, free →
Key Takeaways
- ✓Outbox Pattern runs in O(1) time and O(n) space, in Python as in every other language.
- ✓sqlite3 ships in the standard library with its own transaction handling; for PostgreSQL the ecosystem uses psycopg, now at version 3, or SQLAlchemy.
- ✓Wrap both writes in a single explicit transaction context manager, and have the relay claim rows with SELECT FOR UPDATE SKIP LOCKED so that several relay workers can run at once without ever handing the same row to two of them.
- ✓The Python trap: The driver-level trap is that DB-API connections open a transaction implicitly and do not commit for you, so a forgotten commit rolls everything back when the connection closes.
- ✓SKIP LOCKED is what lets the relay scale horizontally: without it, concurrent workers block on the same rows and throughput is that of a single worker no matter how many you run.
What Outbox Pattern actually is
Outbox Pattern in Python: what you actually reach for
Python implementation
import psycopg
from uuid import UUID, uuid4
DSN = "postgresql:///shop"
def place_order(order_id: UUID, customer_id: UUID, total_cents: int) -> None:
"""The business write and the outbox row commit TOGETHER, or not at all."""
with psycopg.connect(DSN) as conn: # commits on clean exit
with conn.transaction(): # explicit, nested-safe
with conn.cursor() as cur:
cur.execute(
"INSERT INTO orders (id, customer_id, total_cents) VALUES (%s, %s, %s)",
(order_id, customer_id, total_cents),
)
# SAME transaction. This is the entire pattern.
cur.execute(
"""INSERT INTO outbox (id, aggregate_id, event_type, payload)
VALUES (%s, %s, %s, %s::jsonb)""",
(uuid4(), order_id, "OrderPlaced",
f'{{"order_id":"{order_id}","total_cents":{total_cents}}}'),
)
def relay_batch(limit: int = 100) -> int:
"""One relay worker. SKIP LOCKED lets N of these run concurrently."""
with psycopg.connect(DSN) as conn:
with conn.transaction():
with conn.cursor() as cur:
cur.execute(
"""SELECT id, event_type, payload FROM outbox
WHERE published_at IS NULL
ORDER BY created_at
LIMIT %s
FOR UPDATE SKIP LOCKED""", # <- without this, workers
(limit,), # serialise on the same rows
)
rows = cur.fetchall()
if not rows:
return 0
for row_id, event_type, payload in rows:
publish_to_broker(event_type, payload) # at-least-once
cur.execute(
"UPDATE outbox SET published_at = now() WHERE id = ANY(%s)",
([r[0] for r in rows],), # ONE batched update
)
return len(rows)
def publish_to_broker(event_type: str, payload: str) -> None:
...Think Your Code Is Clean? Let NexusBro QA It in 20 Seconds.
Paste your code. Click QA. Get an instant expert-level audit with fixes.
QA My Code FreeThe Python-specific trap
Performance in Python, beyond the O(1)
Real-World Applications
Interview Tips & Practice
Frequently Asked Questions
Which Python type or library should I use for Outbox Pattern?
sqlite3 ships in the standard library with its own transaction handling; for PostgreSQL the ecosystem uses psycopg, now at version 3, or SQLAlchemy. There is no outbox framework and none is needed.
What is the most common Python mistake when implementing Outbox Pattern?
The driver-level trap is that DB-API connections open a transaction implicitly and do not commit for you, so a forgotten commit rolls everything back when the connection closes. That is at least consistent, both writes vanish together, but it presents as the business write mysteriously not happening and sends people hunting in the wrong place. The sqlite3 module compounds this with its own legacy isolation_level attribute, which inserts implicit commits at points that surprise everyone; setting it to None gives you manual control and is what most code actually wants. Use a context manager and never call commit by hand.
How does Outbox Pattern actually perform in Python?
SKIP LOCKED is what lets the relay scale horizontally: without it, concurrent workers block on the same rows and throughput is that of a single worker no matter how many you run. Batch the update that marks rows published rather than issuing one per message. Time complexity is O(1) and space is O(n).
Related Articles
Rather try before you buy?
Get the rest of the vault: every cheat sheet, guide and audit in SeekerPro, free for 14 days, then $15.99/mo. Cancel anytime. Daily usage limits apply.
Start my 14-day SeekerPro trialIf you are a student, see what Devin offers students for free on Noizz.
Is your site built to last?
Run a free QA audit and get your Site Health Score in seconds.
Check Your Site FreeNo signup required
Reader comments
No account needed. Share what worked, what did not, and what you would add.
Add your take below. A concrete tip, a result or a question helps the next reader most.