Skip to main content

Transactional Outbox & CDC

Learning objectives
  • Explain the dual-write problem and the failure orderings that make it lose or invent events
  • Implement a transactional outbox with a polling publisher in Go and PostgreSQL
  • Compare polling with log-tailing CDC (Debezium) on latency, load, ordering and operational risk
  • Design consumer-side deduplication (inbox), per-aggregate ordering and safe event schema evolution

TL;DR​

  • Dual write — commit to the database, then publish to Kafka (or call another service) — has no atomicity. A crash or error between the two loses events or publishes events for data that never committed.
  • Transactional outbox: in the same local transaction as the business change, insert a row into an outbox table. A separate relay publishes outbox rows to the broker. The event exists if and only if the change committed.
  • Relay options: a polling publisher (SELECT … FOR UPDATE SKIP LOCKED, simple, adds DB load and latency) or log tailing / CDC (Debezium reading the WAL or binlog: low latency, commit order, but replication slots and connectors to operate).
  • Delivery is at-least-once. Consumers must deduplicate with an inbox (processed-message table written in the same transaction as their side effects) or be naturally idempotent.
  • Ordering holds only per key: use the aggregate ID as the message key, avoid parallel relays reordering one aggregate, and include a per-aggregate sequence so consumers can detect gaps.
  • Treat events as a public contract: publish intentional domain events from an outbox rather than raw table changes, and evolve schemas with a registry and compatibility rules.

Why it matters​

A payment service captures a card payment and must tell the order service, the ledger and the notification service. The obvious code is:

  1. UPDATE payments SET status = 'CAPTURED' and commit.
  2. producer.Publish("payment.captured", ...).

If the process crashes, is redeployed, or Kafka is briefly unavailable between steps 1 and 2, the payment is captured but nobody downstream knows: the order stays "awaiting payment", the ledger has no entry, and the customer gets no receipt — until reconciliation finds it, if it does. Reverse the steps and a failed commit leaves downstream systems shipping goods for a payment that doesn't exist.

This bug is invisible in testing and appears at a low, steady rate in production, often worst during deploys and incidents — exactly when you can least afford it. The outbox pattern is the standard fix, and in bank and e-commerce interviews "how do you reliably publish the event?" is one of the most common follow-up questions to any event-driven design.

Core concepts​

The dual-write problem​

Variants of the same problem:

  • Publish first, then commit: the commit fails (constraint violation, deadlock, failover) after the event is out. Consumers act on a phantom.
  • Publish inside the transaction: the broker call succeeds, then the transaction rolls back. Still a phantom — and the transaction held locks during a network call.
  • Ordering race: two concurrent requests commit in order A, B but publish in order B, A, so consumers see a stale final state.
  • Calling another service's API instead of a broker has exactly the same problem.

There is no atomic commit across your database and Kafka (Kafka's transactions cover Kafka only, and it is not an XA resource). So you make the database the single source of truth for both the change and the intent to publish.

Transactional outbox​

Outbox table:

CREATE TABLE outbox (
id uuid PRIMARY KEY, -- event ID, used for dedup downstream
aggregate_type text NOT NULL, -- 'payment'
aggregate_id text NOT NULL, -- 'pay_7Hq2...' -> message key
aggregate_seq bigint NOT NULL, -- per-aggregate version
event_type text NOT NULL, -- 'payment.captured.v1'
payload jsonb NOT NULL,
headers jsonb NOT NULL DEFAULT '{}', -- traceparent, schema id
created_at timestamptz NOT NULL DEFAULT now(),
published_at timestamptz
);

CREATE INDEX outbox_unpublished ON outbox (created_at) WHERE published_at IS NULL;

Writing the event in the same transaction:

func (s *PaymentService) Capture(ctx context.Context, paymentID string, amountMinor int64) error {
tx, err := s.db.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx) // no-op after Commit

var seq int64
err = tx.QueryRow(ctx, `
UPDATE payments
SET status = 'CAPTURED', captured_minor = $2, version = version + 1
WHERE id = $1 AND status = 'AUTHORIZED'
RETURNING version`, paymentID, amountMinor).Scan(&seq)
if errors.Is(err, pgx.ErrNoRows) {
return ErrInvalidTransition
}
if err != nil {
return err
}

payload, err := json.Marshal(PaymentCaptured{PaymentID: paymentID, AmountMinor: amountMinor})
if err != nil {
return err
}
_, err = tx.Exec(ctx, `
INSERT INTO outbox (id, aggregate_type, aggregate_id, aggregate_seq, event_type, payload, headers)
VALUES ($1, 'payment', $2, $3, 'payment.captured.v1', $4, $5)`,
uuid.New(), paymentID, seq, payload, traceHeaders(ctx))
if err != nil {
return err
}
return tx.Commit(ctx)
}

Either both rows commit or neither does. The relay may publish an event more than once (it crashes after publishing but before marking it), so the guarantee is at-least-once, never "exactly once" by itself.

Relay option 1: polling publisher​

A background worker repeatedly claims a batch of unpublished rows, publishes them, and marks them.

func (r *Relay) publishBatch(ctx context.Context) (int, error) {
tx, err := r.db.Begin(ctx)
if err != nil {
return 0, err
}
defer tx.Rollback(ctx)

rows, err := tx.Query(ctx, `
SELECT id, aggregate_id, event_type, payload, headers
FROM outbox
WHERE published_at IS NULL
ORDER BY created_at
LIMIT 200
FOR UPDATE SKIP LOCKED`)
if err != nil {
return 0, err
}
events, err := pgx.CollectRows(rows, pgx.RowToStructByPos[OutboxEvent])
if err != nil {
return 0, err
}
if len(events) == 0 {
return 0, nil
}

// Synchronous, acknowledged produce (acks=all). Key = aggregate ID for per-key order.
if err := r.producer.PublishBatch(ctx, events); err != nil {
return 0, err // rows stay unpublished; the next poll retries
}

ids := make([]uuid.UUID, len(events))
for i, e := range events {
ids[i] = e.ID
}
if _, err := tx.Exec(ctx,
`UPDATE outbox SET published_at = now() WHERE id = ANY($1)`, ids); err != nil {
return 0, err
}
return len(events), tx.Commit(ctx)
}

Notes:

  • Use a status column, not "id greater than last seen". With sequences or timestamps, a transaction that started earlier can commit after one with a higher value, so a cursor-based poller silently skips it.
  • SKIP LOCKED lets several relay instances run without blocking each other — but then two instances may publish different events of the same aggregate out of order. If per-aggregate order matters, shard relays by hash(aggregate_id) or run a single active relay (leader-elected).
  • Delete or archive published rows on a schedule (or partition the table by day and drop old partitions) so the table and its index stay small.
  • Latency ≈ the polling interval (100 ms–1 s is typical); load is one indexed query per poll per relay.

Relay option 2: log tailing (CDC)​

Instead of querying, read the database's replication log. Debezium (running on Kafka Connect, or standalone as Debezium Server) reads PostgreSQL's WAL via logical decoding (the pgoutput plugin) or MySQL's row-based binlog, and emits each committed change in commit order.

Debezium ships an outbox event router transformation that turns inserts into the outbox table into clean domain events: topic chosen from aggregate_type, key from aggregate_id, value from payload. Since the WAL already has the insert, the outbox row can be deleted right away (or never kept) — the log is the queue.

Strengths: low latency (typically sub-second, rough), no polling load, exact commit order, no "skipped row" class of bugs. Risks you must operate:

  • Replication slots retain WAL until the connector confirms it. A stopped connector makes WAL pile up until the disk fills and the primary goes down. Set max_slot_wal_keep_size (PostgreSQL 13+) and alert on slot lag.
  • Failover: logical slots live on the primary. Recent PostgreSQL versions (17+) can synchronize logical slots to standbys; on older versions, a failover may force the connector to re-snapshot or lose position. Know your version's behavior.
  • Snapshots: on first start, Debezium snapshots existing data; plan for its load on large tables.
  • Schema changes on captured tables must be coordinated with the connector.

CDC of raw tables vs outbox events​

Debezium can also stream every change to your business tables directly. That is excellent for data replication (feeding a search index, a data warehouse, a cache) where consumers want the row. It is risky as an integration contract between services: consumers become coupled to your internal schema, every column rename is a breaking change, and a "status changed" row update doesn't say why. For service-to-service events, publish intentional, versioned domain events via an outbox.

Inbox: deduplication on the consumer​

At-least-once delivery means duplicates are guaranteed eventually (relay retries, consumer rebalances, redelivery after a crash). The consumer records each processed event ID in the same transaction as its side effect:

CREATE TABLE inbox (
consumer text NOT NULL,
event_id uuid NOT NULL,
processed_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (consumer, event_id)
);
func (h *LedgerHandler) Handle(ctx context.Context, ev Event) error {
return pgx.BeginFunc(ctx, h.db, func(tx pgx.Tx) error {
tag, err := tx.Exec(ctx,
`INSERT INTO inbox (consumer, event_id) VALUES ('ledger', $1)
ON CONFLICT DO NOTHING`, ev.ID)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return nil // duplicate: already applied, ack and move on
}
return h.postEntries(ctx, tx, ev) // ledger entries in the same tx
})
}

Commit the Kafka offset after the database transaction commits. If you crash in between, the event is redelivered and the inbox makes it a no-op. Keep inbox rows at least as long as duplicates can plausibly arrive (days to weeks), then purge. Natural idempotency — INSERT ... ON CONFLICT keyed by payment_id, or a unique constraint on (payment_id, entry_type) in the ledger — is an even stronger guard. See Idempotency & Exactly-Once.

Ordering​

  • Kafka preserves order within a partition. Use the aggregate ID as the key so all events for pay_123 land in one partition.
  • Producers must not reorder retries: with the idempotent producer enabled (default in modern Kafka clients), retries preserve order per partition.
  • Relays must not reorder a single aggregate (see the SKIP LOCKED note above). CDC preserves commit order naturally.
  • Consumers that process in parallel must keep per-key ordering (worker pool sharded by key, not a free-for-all).
  • Retries and DLQs break ordering. If payment.captured for pay_123 fails and goes to a dead-letter queue, payment.refunded for the same payment may be processed first. Options: block the key until the failure is resolved, or make handlers tolerant (use aggregate_seq to detect gaps, park out-of-order events, or re-fetch current state).
  • There is no global order across aggregates; don't design consumers that need one.

Schema evolution​

Events outlive the code that produced them (replays, long retention, slow consumers). Rules that keep you safe:

  • Use a schema format with explicit evolution rules (Avro, Protobuf, or JSON Schema) and a schema registry that enforces compatibility on publish. Confluent Schema Registry, for example, defaults to BACKWARD compatibility.
  • Additive changes only for a given event version: add optional fields with defaults; never remove or rename required fields; in Protobuf, never reuse field numbers.
  • For breaking changes, publish a new event type/version (payment.captured.v2) alongside the old one until all consumers migrate, then retire v1.
  • Consumers follow the tolerant reader rule: ignore unknown fields, don't fail on new enum values (map to "unknown" and alert).
  • Carry an envelope: event_id, event_type, schema_version, aggregate_id, aggregate_seq, occurred_at, and trace context (traceparent) so you can follow one payment across services — see Observability & SLOs.
  • Money in events: integer minor units plus ISO 4217 currency code, never floats — see Schema Patterns: Money, Audit, Multi-tenancy.

Trade-offs​

OptionStrengthsWeaknessesChoose when
Dual writeTrivial codeLoses or invents events; races reorder themNever for anything that matters
Outbox + polling relaySimple, any database, easy to reason aboutPolling load and latency; must avoid cursor gaps and same-key reordering; table cleanupModerate volume, team without CDC experience, sub-second latency not required
Outbox + CDC (Debezium)Low latency, commit order, no polling loadKafka Connect and replication slots to operate; WAL retention risk; failover handlingHigh volume, many event types, Kafka already central
Raw table CDCNo app changes; full row historyCouples consumers to internal schema; no business intentReplicating data to search, cache, warehouse
Event-first ("listen to yourself")No outbox table; log is the source of truthService reads its own writes asynchronously; harder read-your-writesEvent-sourced services (see event-driven architecture)
Broker transactional messages (e.g., RocketMQ half messages)Broker-assisted; check-back resolves unknown local outcomesTies you to one broker's semanticsAlready standardized on such a broker

In practice​

  • Publish with acks=all and idempotence enabled; treat a produce timeout as "unknown" and let the next poll retry — duplicates are expected and handled downstream.
  • Monitor outbox lag: age of the oldest unpublished row (polling) or replication slot lag in bytes/time (CDC). Alert well before customers notice (e.g., oldest unpublished event older than ≈ 30 s for payment events — pick a number from your SLO).
  • Size of the outbox: at 500 payments per second with 3 events each, that is 1,500 rows/s, ≈ 130 million rows/day. Partition the outbox by day and drop old partitions instead of DELETE-ing, or delete immediately when using CDC.
  • One outbox per service database. Never share an outbox across services' databases; that reintroduces coupling.
  • Trace context in headers lets traces cross the async hop: the consumer's span links to the producer's.
  • Replays: keeping published events (or Kafka retention) lets you rebuild a consumer's state, but only if handlers are idempotent and schemas are still readable.

Common pitfalls​

  • Publishing from inside the DB transaction. Holds locks during a network call and still publishes phantoms on rollback.
  • Cursor-based polling (WHERE id > $last). Symptom: a small fraction of events never published; found weeks later in reconciliation.
  • Parallel relays with SKIP LOCKED and per-aggregate ordering assumptions. Symptom: consumers occasionally see refunded before captured.
  • Forgetting the replication slot. Symptom: primary disk fills up over a weekend because the Debezium connector was paused.
  • Committing the Kafka offset before the side effect. Symptom: lost events after consumer crashes.
  • Inbox in a different database than the side effect. The dedup record and the effect are no longer atomic — you have a dual write again.
  • Breaking schema changes in place. Symptom: consumers crash-loop on deserialization after a producer deploy; lag grows across the platform.

Interview angle​

  • Typical prompt: any event-driven design — "the order service needs to know when payment completes". Interviewers listen for whether you notice the dual write.
  • Strong answer: outbox in the same transaction; relay via polling or Debezium (with trade-offs); at-least-once delivery; consumer inbox or natural idempotency; key by aggregate ID for ordering; schema registry and versioned events; monitoring of outbox/slot lag.
  • Follow-ups: "Why not Kafka transactions?" (they don't include your database). "What if the relay publishes twice?" (consumers dedupe). "How do you guarantee ordering?" (per key only; relay and consumer must preserve it). "What happens if Debezium is down for a day?" (WAL retention — disk risk).
  • Red flags: "we publish after commit and retry on failure" (the retry dies with the process); "exactly-once delivery" claims without consumer idempotency; CDC of raw tables as the inter-service API.

Self-check​

1. Describe two ways a dual write can go wrong and the business impact in a payment flow.

Commit-then-publish: a crash after commit loses the event, so the payment is captured but the order isn't confirmed and no ledger entry is posted. Publish-then-commit (or publish inside the transaction): the commit fails or rolls back after publishing, so downstream ships goods or posts entries for a payment that doesn't exist. Concurrent writers can also publish in a different order than they committed.

2. Why does the outbox pattern give at-least-once rather than exactly-once delivery?

The relay must publish and then mark the row (or advance its CDC position). If it crashes after the broker acknowledges but before marking, it will publish the same row again on restart. There is no atomic commit across the outbox and the broker, so duplicates are possible and consumers must be idempotent.

3. Why is WHERE id > last_published_id a bug in a polling relay?

IDs (sequences or timestamps) are assigned when a row is inserted, but rows become visible when their transaction commits. A long transaction can commit a row with a lower ID after the poller has already moved its cursor past it, so that row is never published. A published_at IS NULL status with an index avoids this.

4. Compare polling and Debezium-based CDC on three dimensions.

Latency: polling is bounded by the poll interval; CDC is typically sub-second. Load: polling issues queries against the primary; CDC reads the WAL stream with little query load. Operations: polling is just application code; CDC needs Kafka Connect, replication slots, snapshot handling and monitoring of WAL retention, and has failover considerations. CDC also preserves commit order naturally.

5. Scenario: the ledger consumer processes payment.captured, posts entries, and crashes before committing its Kafka offset. What happens and why is it safe?

On restart the event is redelivered. The handler's inbox insert for that event ID conflicts (it committed together with the ledger entries), so the handler skips the side effect and acknowledges. Because the inbox row and the entries are in the same database transaction, they either both exist or neither does.

6. How do you evolve payment.captured to add a mandatory settlement_currency field?

Adding a mandatory field breaks old producers/consumers, so either add it as optional with a sensible default (and make it effectively required in producer code), or publish payment.captured.v2 in parallel with v1, migrate consumers, then retire v1. The schema registry's compatibility check should reject an in-place breaking change.

🧠 Flashcards0/9 learned · 0 retries

Exercise​

Build the outbox end to end:

  1. PostgreSQL with payments, outbox and a consumer database with inbox and ledger_entries. Redpanda or Kafka in Docker.
  2. Implement Capture with the outbox insert, and the polling relay above. Then add a Debezium connector with the outbox event router and run both relays against separate topics.
  3. Chaos: kill the relay between publish and mark; kill the consumer between DB commit and offset commit; pause Debezium for ten minutes and watch slot lag.
  4. Write a checker that compares captured payments to ledger entries.

Done when: after 10,000 captures with random kills, the checker reports zero missing and zero duplicate ledger entries, and you can show the slot-lag alert firing during the Debezium pause.

Further reading​

  • Chris Richardson, Microservices Patterns, ch. 3 (transactional messaging, outbox, polling publisher, transaction log tailing).
  • Martin Kleppmann, Designing Data-Intensive Applications, ch. 11 (change data capture, event logs).
  • Debezium documentation: PostgreSQL connector and "Outbox Event Router".
  • Gunnar Morling, "Reliable Microservices Data Exchange With the Outbox Pattern" (Debezium blog, 2019).
  • PostgreSQL documentation: "Logical Decoding" and replication slots.
  • Confluent documentation: Schema Registry compatibility types.
Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).