Skip to main content

Transactional Outbox

1. Executive Summary​

The transactional outbox pattern solves the dual-write problem: an application must atomically update a database and publish a message to a broker, but these are two different systems that cannot share a single local ACID transaction without brittle XA/2PC. The pattern writes the message to an outbox table in the same database transaction as the business data change. A separate message relay process reads the outbox and publishes to the message broker, marking rows as dispatched.

This guarantees no message without a database commit and no lost messages for committed business state (assuming relay eventually runs). Delivery to consumers remains at-least-once—consumers must be idempotent. Relay implementations include polling the outbox table, transaction log tailing (CDC via Debezium), and database triggers (less common at scale).

The transactional outbox is a foundational pattern for event-driven microservices, CQRS projections, saga choreography, and cache invalidation. It pairs naturally with Sagas and replaces risky "write DB then publish to Kafka" ordering.

2. Why This Topic Matters​

Principal interviews often ask: "How do you reliably publish events when you update the database?" Weak answers propose distributed transactions or hope for the best. Strong answers describe the outbox.

Failure modes without outbox:

  • DB commits, message publish fails → downstream never notified (orphan state).
  • Message publishes, DB rolls back → ghost events (consumers act on nonexistent data).
  • Retry duplicates → double processing without idempotency.

Production systems that "just write to Kafka after INSERT" cause inventory drift, missing search index updates, and billing discrepancies. The outbox is operationally visible—relay lag becomes a metric; stuck rows trigger alerts.

3. Problems Being Solved​

ProblemNaive dual-writeTransactional outbox
Atomicity DB + eventNot guaranteedSame local transaction
Lost event after commitPossibleOutbox row durable with commit
Event without DB recordPossible if publish firstPrevented (outbox only on commit)
Cross-service 2PCBlocking, complexAvoided
Ordering per aggregateAd hocRelay can preserve order per key

The outbox solves reliable publication of side effects from a local transaction. It does not provide exactly-once end-to-end processing without idempotent consumers and deduplication. It does not coordinate multi-database atomicity—that remains saga or 2PC territory.

4. Assumptions and System Model​

Assume single relational (or transactional) database per service and a message broker (Kafka, SQS, RabbitMQ):

  • Application opens local transaction.
  • Business row(s) and outbox row inserted/updated together.
  • Relay is a separate process with at-least-once publish semantics.
  • Broker may duplicate; consumers dedupe via event id or idempotency store.
  • Failures: App crash after commit (outbox row exists—relay picks up); relay crash mid-publish (retry safe with idempotent publish or transactional outbox status).

Not assumed: Global ordering across aggregates unless relay partitions by key. Instant delivery—relay introduces latency. Broker exactly-once without consumer cooperation.

5. Essential Terminology​

TermDefinition
Outbox tableTable storing pending messages (id, payload, topic, created_at, dispatched_at).
Dual-write problemTwo writes without shared atomicity.
Message relayProcess publishing outbox rows to broker.
Polling relaySELECT ... FOR UPDATE SKIP LOCKED loop.
CDC relayChange Data Capture from WAL/binlog (Debezium).
Inbox patternConsumer-side dedup table for processed message ids.
At-least-once deliveryMessage may arrive multiple times.
Effectively-onceAt-least-once + idempotent consumer.
Ordering keyPartition key for ordered delivery per aggregate.
Poison messageUndeliverable outbox row—DLQ or skip policy.

Mnemonic: Outbox = One transaction, two writes in one DB, relay later.

6. Core Mechanism​

Atomic write in application transaction​

Figure 1: Business data and outbox message commit together—no orphan publish possible.

Polling relay​

Figure 2: Relay claims rows, publishes, marks dispatched—retry-safe if mark fails after publish (duplicate risk → idempotent consumers).

CDC-based relay (Debezium)​

Figure 3: WAL tailing captures outbox inserts without polling load on primary—ordering follows log.

7. Step-by-Step Walkthrough​

Scenario: Order service creates order and emits OrderCreated.

StepComponentAction
1API handlerBEGIN
2API handlerINSERT orders (id, status) VALUES ('o1', 'PENDING')
3API handlerINSERT outbox (id, aggregate_id, type, payload) VALUES ('e1', 'o1', 'OrderCreated', '{...}')
4API handlerCOMMIT
5RelayReads e1, publishes to orders topic with key o1
6RelayUPDATE outbox SET dispatched_at=now() WHERE id='e1'
7Inventory consumerReceives event, idempotent reserve; stores e1 in inbox

Failure: relay crashes after Kafka ACK, before UPDATE:

StateMitigation
Outbox row still undispatchedRelay republishes duplicate
Consumer inbox dedupes on e1Effectively-once processing

Failure: publish before commit (anti-pattern):

StateWhy outbox wins
Consumers see event; DB rolls backOutbox prevents—event only after commit

8. Invariants and Guarantees​

PropertyTypeStatement
Atomicity (local)SafetyBusiness row and outbox row commit together
No lost committed eventsSafetyCommitted outbox row eventually relayed (liveness of relay)
No pre-commit eventsSafetyUncommitted outbox rolled back with txn
Exactly-once broker deliveryNot guaranteedAt-least-once typical
Relay progressLivenessRequires healthy relay; monitor lag
Global orderingNot unless keyed partition + single relay shard

End-to-end exactly-once is an application property: outbox + idempotent consumer + inbox (or broker idempotence where supported).

9. Failure Scenarios​

Scenario 1: Relay stopped 6 hours​

Effect: Downstream stale; inventory not reserved.

Mitigation: Alert on max(created_at) WHERE dispatched IS NULL age; auto-restart relay.

Scenario 2: Outbox table bloat​

Effect: Poll queries slow; disk growth.

Mitigation: Archive/delete dispatched rows; partition by date; retention job.

Scenario 3: Poison payload​

Effect: Relay or consumer infinite fail loop.

Mitigation: DLQ after N tries; schema validation; quarantine row.

Scenario 4: CDC slot lag (PostgreSQL)​

Effect: WAL retention grows; disk fill on primary.

Mitigation: Monitor replication slot; scale consumer; separate outbox topic.

Scenario 5: Ordering violation​

Effect: OrderCancelled processed before OrderCreated on different partitions.

Mitigation: Same partition key (order_id) for all events of aggregate.

10. Performance Characteristics​

FactorImpact
Extra INSERT per eventSmall OLTP overhead—indexed outbox
PollingSKIP LOCKED reduces contention; tune batch size and interval
CDCLower primary query load; WAL read overhead; operational complexity
Transaction sizeLarge payloads in outbox bloat txn—store reference to blob if needed
Relay throughputBottleneck at high event rates—horizontal relay workers with SKIP LOCKED

Latency: Event visible downstream after commit + relay delay—typically tens to hundreds of ms; not synchronous.

11. Scalability Limits​

  • Outbox table hot spot on single partition—partition table by time.
  • Polling at 10k events/sec may stress DB—prefer CDC.
  • Ordering per key limits parallel relay for same aggregate.
  • Large messages in outbox—use claim check pattern (S3 pointer in payload).

12. Operational Considerations​

  • Metrics: outbox lag (oldest undispatched), relay throughput, dispatch failures.
  • Schema migrations: outbox table versioned payloads (upcasters).
  • Multi-region: outbox per region; global ordering not automatic.
  • Replay: Re-process from outbox archive or Kafka retention for disaster recovery.
  • Testing: Integration test asserts event after commit; chaos-kill relay.

Runbook: outbox lag alert

  1. Check relay process health (pods, Lambda errors, Debezium connector state).
  2. Query SELECT count(*), min(created_at) FROM outbox WHERE dispatched_at IS NULL.
  3. If DB load high—polling may starve; consider CDC or dedicated relay instance.
  4. If Kafka down—relay backs up; do not delete undispatched rows.
  5. After recovery, expect duplicate delivery burst—confirm consumer inbox capacity.
  6. Post-incident: measure lag SLA breach duration; reconcile downstream if needed.

Index design: Composite index on (dispatched_at, created_at) where dispatched_at IS NULL partial index (PostgreSQL) speeds polling queries. Without index, relay full-scans bloat table—CPU spike on primary during peak checkout.

Transactional outbox vs inbox symmetry: Outbox guarantees publish intent; inbox on consumer guarantees process-once semantics. Both tables share design patterns (id, processed_at, payload hash)—operations teams can reuse monitoring dashboards.

Exactly-once Kafka producer misconception: Idempotent Kafka producer prevents duplicate broker writes from producer retries—it does not couple to your RDS commit. You still need outbox (or accept dual-write risk) at the database boundary.

Sample outbox DDL (PostgreSQL):

CREATE TABLE outbox (
id UUID PRIMARY KEY,
aggregate_id TEXT NOT NULL,
event_type TEXT NOT NULL,
payload JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
dispatched_at TIMESTAMPTZ
);
CREATE INDEX outbox_pending_idx ON outbox (created_at)
WHERE dispatched_at IS NULL;

Relay query pattern: SELECT ... FROM outbox WHERE dispatched_at IS NULL ORDER BY created_at LIMIT 100 FOR UPDATE SKIP LOCKED.

13. Security Considerations​

  • PII in outbox payload — encrypt at rest; minimize fields; GDPR delete propagates to outbox archives.
  • Relay credentials — least privilege to outbox SELECT and broker publish.
  • Tampering — sign event payloads if downstream trust boundary requires.
  • Access control — outbox table not exposed to reporting tools without scrubbing.

14. Cost Considerations​

  • Storage: Undispatched + archived rows; CDC WAL retention.
  • Compute: Relay workers, Debezium connectors, Kafka partitions.
  • Engineering: Simpler than XA; more moving parts than monolith triggers.
  • Saved incidents: Avoids dual-write reconciliation teams.

FinOps angle: Outbox lag during incidents forces manual reconciliation teams—model cost of N engineers × hours against relay infrastructure ($hundreds/month). At scale, CDC connector HA (multiple tasks, monitoring) is cheaper than quarterly dual-write incident response.

Payload size costs: Storing 50KB JSON per outbox row at 10M orders/day is terabytes/year—use claim check to S3 for large attachments; outbox carries pointer only. Kafka message size limits (default 1MB) also constrain design.

Comparison to nightly batch reconciliation: Batch jobs compare DB to downstream and repair drift—cheaper infra but longer inconsistency window and higher support cost. Outbox is near-real-time insurance; many systems use both (outbox for happy path, reconciliation for audit).

15. Production Implementations​

Debezium + Kafka​

Industry-standard CDC from PostgreSQL/MySQL outbox table to Kafka—implementation choice for high throughput.

Maxwell's daemon / AWS DMS​

Alternative CDC tools—evaluate operational fit.

Framework support​

  • Microservices.io pattern reference
  • Eventuate — outbox as productized pattern
  • Axon Framework — event sourcing with outbox
  • Spring — various outbox libraries (evaluate maturity)
  • Prisma / custom — polling relay in worker process

Uber / Netflix engineering blogs​

Document outbox-style reliable publishing at scale—anecdotal operational experience; validate against your stack.

AWS Lambda + RDS outbox​

Short-lived Lambda functions are poor XA participants but effective polling relays on schedule (EventBridge) or triggered post-commit via separate worker tier. Avoid running relay in the same Lambda as request handler without durable dispatch marker—function freeze after response can lose in-memory publish.

Multi-tenant SaaS​

Include tenant_id in outbox rows and propagate to message headers for downstream authorization. Relay must not cross-publish tenant events to wrong topics—partition outbox polling by tenant for noisy-neighbor isolation at extreme scale.

Schema evolution​

Outbox payloads should carry schema_version and use upcasting on consumers when fields are added. Breaking changes require dual-write period or new event type (OrderCreatedV2) with consumers subscribing to both during migration.

Relay implementation checklist:

ConcernPollingCDC
Primary DB loadSELECT every N msWAL read
OrderingApplication batch orderLog order
Ops complexityLowConnector HA, slots
LatencyPoll interval floorNear real-time
Duplicate on failureYesYes

16. Alternatives and Tradeoffs​

ApproachAtomicityComplexityWhen
Transactional outboxDB + intent atomicRelay opsDefault for microservices
XA/2PCFull distributedHigh, blockingLegacy enterprise
Change Data Capture on main tableNo separate outboxCouples event schema to tableSimple domains
Event sourcingEvents are source of truthHighEvent-native domains
Publish then DBUnsafeLowNever for critical paths
In-process onlyN/ALowestMonolith, no async

17. Common Misconceptions​

MisconceptionReality
"Outbox = exactly-once"At-least-once to broker; consumer idempotency required.
"Kafka transactions replace outbox"Kafka txn doesn't atomically commit your Postgres row.
"Polling doesn't scale"SKIP LOCKED + batching works to moderate scale; CDC at high scale.
"Delete outbox row after insert to Kafka"Keep dispatched audit or archive; replay needs.
"CDC removes need for outbox table"CDC still needs outbox or clear change semantics on business table.
"Synchronous REST instead of outbox"Couples availability; no durability if callee down.

18. Principal Architect Perspective​

  1. Mandate outbox for any event that must match DB state.
  2. Standardize envelope (event_id, type, aggregate_id, occurred_at, schema version).
  3. Monitor lag as tier-1 metric—inventory and search depend on it.
  4. Pair with inbox on consumers for money paths.
  5. Document replay procedure before you need disaster recovery.

19. Architecture Review Exercise​

Scenario: Team publishes to SQS after commit() in application code with try/catch retry.

Review prompts:

  1. Crash between commit and publish?
  2. Publish succeeds, commit fails?
  3. Retry duplicates on consumer?
  4. Redesign with outbox + relay?
  5. CDC vs polling for 2k events/sec?

Expected findings: Replace with outbox; idempotent consumer; alert on lag; CDC if polling hot.

20. Whiteboard Explanation​

90-second version:

"Dual-write is writing the database and publishing a message as two separate steps—you can commit and fail to publish, or publish and roll back. Transactional outbox fixes this by inserting the message into an outbox table in the same database transaction as the business write. A relay process polls undispatched rows or CDC tails the WAL and publishes to Kafka, then marks rows sent. Delivery is at-least-once, so consumers need idempotency keys or an inbox table. Order events per aggregate with the same partition key. Monitor outbox lag. It's the standard replacement for XA between DB and broker and pairs with sagas for cross-service workflows."

21. Interview Questions​

  1. What problem does outbox solve?

    • Signals: Dual-write; atomic DB + message intent.
  2. How is atomicity achieved?

    • Signals: Same local ACID transaction for business + outbox row.
  3. Polling vs CDC relay?

    • Signals: SKIP LOCKED poll vs Debezium WAL; scale tradeoffs.
  4. Is delivery exactly-once?

    • Signals: No—at-least-once; idempotent consumer.
  5. Relay crashes after publish, before mark?

    • Signals: Duplicate publish; consumer dedupes.
  6. Outbox vs Kafka transactions?

    • Signals: Kafka can't join your DB commit atomically.
  7. What columns in outbox table?

    • Signals: id, payload, topic, created_at, dispatched_at, aggregate_id.
  8. Ordering guarantees?

    • Signals: Partition by aggregate_id; single-threaded relay per key.
  9. Outbox bloat mitigation?

    • Signals: Archive dispatched, partition, retention job.
  10. Pair with saga how?

    • Signals: Local step commits + event triggers next saga step.
  11. Inbox pattern purpose?

    • Signals: Consumer-side processed message dedup.
  12. When skip outbox?

    • Signals: Fire-and-forget analytics, monolith synchronous only.
  13. WAL slot lag risk?

    • Signals: Disk fill; monitor Debezium lag.
  14. Claim check pattern?

    • Signals: Large payload in object store; pointer in outbox.
  15. How does outbox support saga choreography?

    • Signals: Local commit + reliable event triggers next service.
  16. What if relay publishes but mark fails?

    • Signals: Duplicate; consumer idempotency; safe to retry mark.

Anti-patterns to flag in reviews:

Anti-patternWhy it fails
Outbox in separate DBBreaks atomicity with business data
Delete row before Kafka ACKLose message on crash
No dispatched_at columnCan't distinguish pending vs failed relay
Synchronous publish in HTTP handlerCouples availability; no crash safety

22. Interview Follow-Ups​

  1. Design search index update on product change.

    • Signals: Outbox from catalog DB, indexer consumer, idempotent upsert.
  2. Global active-active—one outbox?

    • Signals: Per-region outbox; conflict resolution; not single global order.
  3. Replay all events after bug—steps?

    • Signals: Kafka retention, outbox archive, idempotent reprocess, caution on compensations.

22A. Production Low-Level Design (Interview + Game Day)​

Transactional outbox poller/CDC relay — not dual-write. Production LLD and Game Day Standard.

Schema​

outbox(id, aggregate_id, topic, payload, created_at, dispatched_at, attempts)
-- same DB transaction as business row

Step-by-step flow:

StepFailureMitigation
1Crash before commitNothing published (good)
3Publish OK, mark failsDuplicate publish → consumer dedupe
5–6RedeliveryIdempotent consumer / inbox

Ops LLD​

  • Metric: outbox_oldest_pending_age, relay lag.
  • Archive dispatched rows; claim-check large payloads.
  • SLO: outbox→Kafka publish lag p99 < 5s (tune to product).

22B. Game Day Playbooks​

#DrillInjectDetectMitigateVerify
GD-1Dual-write lag classicCompare naive dual-write vs outboxLost events on crashUse outbox onlyCrash mid-handler: event still published
GD-2Relay stallStop polleroldest_pending_ageScale/fix relayLag drains; no loss
GD-3Poison payloadBad JSON in outboxattempts↑ / DLQQuarantine rowDownstream unblocked

GD-2 — Relay / dual-write lag​

23. Strong Answer Example​

Question: "How do you keep MySQL and Kafka in sync when an order is placed?"

Answer this as a 45-minute design discussion using the PRACTICE framework. Below is how a strong student sounds aloud—transactional outbox, not dual-write, and not XA.

PRACTICE interview answer map for MySQL–Kafka sync via outbox

Figure A: PRACTICE map — Problem → Requirements → Assumptions → Capacity → Topology → Invariants → Constraints → Evolution.


Student interview script (PRACTICE)​

P — Problem framing​

"When an order is placed we must update MySQL and notify downstream via Kafka. Those are two systems—they don't share one local ACID transaction without brittle XA.

Naive dual-write fails in two ways: commit order then crash before publish → lost event; publish then fail the DB → orphan event. Either way inventory/search/billing drifts.

Transactional outbox: in the same MySQL transaction, insert the order and an outbox row (the intent to publish). A relay (poll or CDC) publishes to Kafka afterward. Committed orders always have a durable publish intent; rolled-back orders never emit.

Short answer: Outbox in MySQL + relay to Kafka + idempotent consumers. End-to-end is effectively-once, not broker magic alone."

R — Requirements​

RequirementHow outbox addresses it
No lost event after order commitOutbox row commits with order
No event if order rolls backOutbox row rolls back too
Downstream can retry safelyAt-least-once + idempotency / inbox
Per-order orderingPartition key = order_id
Ops visibilityOutbox lag metric / oldest pending

"I'd ask: polling vs Debezium? Multi-region? Payload size? Who consumes—inventory saga step?"

A — Assumptions (state aloud)​

AssumptionWhy it matters
Order service owns MySQLOutbox lives in that DB
Kafka is the integration busRelay is the bridge
Consumers are at-least-onceMust dedupe by event_id
Idempotent Kafka producer ≠ DB couplingStill need outbox at the DB boundary
Eventual sync OK (seconds)Not XA synchronous commit to Kafka

"I'd say: Kafka transactions don't atomically commit your MySQL row—outbox still required."

C — Capacity​

Low/moderate event rate → polling relay + SKIP LOCKED is fine
High throughput / busy OLTP → Debezium CDC on outbox (less primary poll load)
Large payloads → claim-check (S3 pointer in outbox)
Undispatched growth → archive/delete after dispatch; alert on lag

"I'd start with polling; move to CDC when lag or primary load hurts."

T — Topology (draw this)​

Dual-write vs transactional outbox

Figure B: Dual-write can lose or orphan events; outbox commits business row + publish intent together.

Outbox relay, CDC, and failure modes

Figure C: Polling or Debezium CDC → Kafka; handle relay crash, duplicates, poison rows; monitor lag.

PieceRole
orders + outbox tablesSame TX on place-order
Polling relaySELECT … FOR UPDATE SKIP LOCKED → Kafka → mark dispatched
CDC (Debezium)Tail binlog/WAL of outbox inserts → Kafka (Outbox Event Router)
Consumer inboxDeduplicate event_id; process once effectively
Lag alertOldest undispatched > SLO (e.g. 30s)

Outbox row sketch: id (event_id), aggregate_id (order_id), type, payload, created_at, dispatched_at.

I — Invariants (safety)​

"Non-negotiable:

  1. Business write + outbox write in one MySQL transaction.
  2. No publish before commit; no silent drop after commit (relay liveness).
  3. At-least-once to Kafka — consumers must be idempotent.
  4. Partition by order_id for per-aggregate order.
  5. Not XA between MySQL and Kafka for this path.
  6. Effectively-once E2E = outbox + idempotent consumer (inbox), not 'Kafka exactly-once' alone."

C — Constraints (second C)​

ConstraintDesign response
Relay crash mid-publishLeave undispatched / retry; consumer dedupes
Poison payloadDLQ; don't block forever; alert
Schema evolutionschema_version / OrderCreatedV2; upcast
PII in eventsMinimize fields; encrypt; retention policy
Multi-region active-activePer-region outbox; no single global order
"Just CDC the orders table"Possible but couples event schema to table; outbox table is cleaner intent

E — Evolution (prove it)​

Phased delivery:

PhaseDeliverable
M1Outbox table + same-TX insert with order
M2Polling relay + lag metrics / alerts
M3Consumer inbox / idempotency by event_id
M4Archive dispatched rows; runbook for lag
M5Optional: Debezium CDC if scale requires
M6Chaos: kill API after commit; kill relay; duplicate publish

Failure modes:

FailureMitigation
Dual-write after commitRejected—use outbox
XA MySQL↔KafkaRejected—blocking/coupling
Lost relayRows stay pending; HA relay; lag alert
Duplicate Kafka messagesIdempotent consumers
Binlog/slot lag (CDC)Monitor connector; scale tasks

Observability: oldest pending age, pending count, relay throughput, dispatch errors, consumer duplicate skips, CDC connector state.


Closing line (interview)​

"So: I don't dual-write MySQL then Kafka, and I don't use XA. On place-order I commit the order and an outbox row in one MySQL transaction. A relay—polling with SKIP LOCKED or Debezium CDC—publishes to Kafka with order_id as the key. Consumers treat delivery as at-least-once and dedupe with an inbox / event_id. I alert on outbox lag and archive dispatched rows. That keeps MySQL and Kafka eventually in sync with no lost committed orders—and that's effectively-once end-to-end, not broker exactly-once alone."

Scoring signals​

StrongWeak / red flag
Outbox in same TX"Insert MySQL then produce to Kafka"
Polling and/or CDCOnly hope / try-catch retry
Idempotent consumers / inboxAssumes exactly-once Kafka fixes DB
Rejects XA for thisProposes distributed TX casually
Lag metrics + archiveNo ops story
Partition key = order_idRandom partitioning / unordered

Compact outline (if time-boxed to 2 minutes)​

"Transactional outbox: same MySQL TX inserts order + outbox row. Relay polls or CDC publishes to Kafka. At-least-once → idempotent consumers. Partition by order_id. Alert on lag. No dual-write, no XA. Effectively-once E2E."

24. Weak Answer Example​

Question: "How do you keep MySQL and Kafka in sync when an order is placed?"

"We insert into MySQL then call Kafka producer in a try/catch. If Kafka fails we log and retry."

Why weak / red flags: Classic dual-write—no atomicity with the DB commit; crash window loses events; retry can duplicate without idempotent consumers; no lag monitoring or relay design.

25. Hands-On Exercise​

Lab 009: Transactional Outbox (runnable)​

Full hands-on lab at labs/lab-009-outbox-pattern/ — FastAPI + Swagger on port 8092, in-memory outbox + broker (Kafka stand-in).

cd labs/lab-009-outbox-pattern
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
pytest tests/ -v
python -m src.main --demo
python -m src.main --serve

Docker:

docker compose -p lab009 -f docker/docker-compose.yml up --build -d
curl http://localhost:8092/health
./scripts/demo_outbox.sh

Demo flow (Swagger at http://localhost:8092/docs):

StepEndpointWhat happens
1POST /v1/ordersINSERT order + INSERT outbox — same transaction
2GET /v1/outbox?pending=trueUnpublished OrderCreated event
3POST /v1/relay/runRelay publishes to broker; marks published_at
4POST /v1/consumer/runIdempotent inventory update by event_id
5POST /v1/consumer/run againduplicates: 1 — at-least-once safe

Scenario walkthrough: Shopify Transactional Outbox.

Next lab: Sagas §25 Hands-On — Lab 010 orchestration on :8093 (engineer guide).

Build-from-scratch exercise (optional)​

  1. Create orders and outbox tables in PostgreSQL.
  2. Wrap insert in single transaction.
  3. Write polling relay script (Python/Node) with SKIP LOCKED.
  4. Kill relay mid-batch; verify at-least-once behavior.
  5. Add consumer inbox table with unique event_id.
  6. Measure lag under load.
  7. Optional: sketch Debezium connector config for same schema.

Or complete Lab 009 above — implements steps 1–5 with 9 passing tests.

26. Knowledge Check​

  1. Dual-write problem? (DB and broker without shared atomicity.)
  2. Outbox lives where? (Same DB as business data.)
  3. Delivery semantics to broker? (At-least-once typical.)
  4. SKIP LOCKED purpose? (Concurrent relay workers without double-claim.)
  5. Consumer requirement? (Idempotency or inbox.)

27. Flashcards​

#FrontBack
1Transactional outboxMessage in same DB txn as business write.
2Dual-writeSeparate DB + publish—unsafe.
3Message relayPublishes outbox to broker.
4Polling relaySELECT undispatched FOR UPDATE SKIP LOCKED.
5CDC relayDebezium tails WAL/binlog.
6At-least-onceDuplicates possible—design for it.
7Inbox patternConsumer dedup table.
8Partition keyOrder events per aggregate.
9Outbox lagOldest undispatched—monitor metric.
10vs XAOutbox avoids 2PC blocking.
11Claim checkLarge payload offloaded to blob store.
12Effectively-onceAt-least-once + idempotent consumer.

28. Cheat Sheet​

OUTBOX
Txn: business row + outbox row
Relay: poll or CDC → broker
Mark dispatched after ACK

GUARANTEES
✓ No event without commit
✓ Committed event eventually sent (if relay lives)
✗ Not exactly-once end-to-end

CONSUMER
Idempotency key / inbox table
Same partition key per aggregate

OPS
Alert: undispatched age, relay errors
Archive old dispatched rows
WAL slot lag (CDC)

AVOID
Publish after commit in app code
XA DB + Kafka for microservices

30. References​

Primary sources​

  • Chris Richardson, "Transactional outbox pattern" — pattern catalog.
  • Hohpe, G., & Woolf, B. (2003). Enterprise Integration Patterns — messaging reliability foundations.

Production and engineering​

  • Debezium Documentation — Outbox Event Router — CDC outbox integration.
  • Uber Engineering — reliable event publishing posts — implementation anecdotes; verify for your stack.
  • Martin Kleppmann, DDIA — Chapter 11 stream processing, change capture.

Distinction​

Claim typeSource
Pattern definitionRichardson; Enterprise Integration Patterns
Debezium outbox SMTDebezium official docs
Exactly-once limitsKleppmann; distributed systems consensus