← Portfolio
Systems, in practice
Jump to the outbox pattern ↓

Distributed systems · A field guide

The transaction ends at the database.

A payment can be correct in PostgreSQL and still disappear from every system that needs to hear about it. The transactional outbox is a practical answer to that uncomfortable gap.

From the payment boundary A visual walk through the decisions behind a reliable event pipeline
9 minute read

Start with two wallets. Alice has ₹8,000; Bob has ₹3,000. Alice sends Bob ₹2,000. The balances should become ₹6,000 and ₹5,000—not ₹6,000 and ₹3,000 because the process died halfway through.

That small story gives us a useful invariant: the transfer must debit one account and credit the other as a single unit. It also exposes a bigger truth about reliable systems: every new boundary creates a new way to be partly successful.

Make the money move atomically

Both account updates belong in one PostgreSQL transaction. If either update fails, neither should become visible. In a real wallet, I would also put the ledger entries, the idempotency record, and the event intent in that same transaction.

-- Keep the debit, credit and ledger entries together.
BEGIN;
  UPDATE accounts
     SET balance = balance - 2000
   WHERE id = 'alice' AND balance >= 2000;
  -- Require exactly one row to be updated.
  UPDATE accounts
     SET balance = balance + 2000
   WHERE id = 'bob';
  INSERT INTO ledger_entries (...);
COMMIT;

The guarded debit matters. Atomicity alone does not stop two concurrent transfers from both spending the same observed balance. PostgreSQL coordinates updates to the row; the balance predicate is checked as part of the update, and the application must reject the transfer unless exactly one Alice row changed. Lock ordering and suitable constraints complete the picture.

Keep the accounting story intact. A ledger records movements; a balance is a convenient current-state projection. Write the debit and credit entries together, and keep the balance update in the same transaction.

A durable commit is not a published event

PostgreSQL has its own durability machinery. Under the configured commit guarantees, it records changes in its write-ahead log before acknowledging a durable commit. After a crash, that log helps PostgreSQL recover committed data. It is not, however, an application event bus. Kafka stores and distributes business events; WAL protects and recovers database state.

Now imagine the payment service needs to notify the recipient, update analytics, feed fraud monitoring, and refresh an activity timeline. Calling those services inline makes the payment request wait on all of them. A slow notification provider can hold up checkout; an unavailable analytics system can turn a successful payment into an HTTP error the client may retry.

Publishing asynchronously is better for isolation, but it introduces a second durable system. The database and Kafka do not share one ordinary atomic commit.

The dual-write failure window The application commits to PostgreSQL and then publishes to Kafka. A crash between those actions leaves the database committed without a Kafka event. Payment serviceone process, two writes PostgreSQLtransfer committed ✓ Kafkaevent not published 1 · COMMIT 2 · PUBLISH · crash can happen here Success in one system, absence in the other
Figure 1. Reordering the writes only reverses the failure: publish first, and Kafka may describe a payment the database later rolls back.

Retries and try/catch do not close this window. A process can stop after either system has accepted its write. The answer is not to make the HTTP handler more hopeful; it is to make the intent to publish part of the database commit.

Put the event intent in the transaction

The outbox is an ordinary database table. The application writes the payment and a record describing the event in one transaction. If the transaction rolls back, neither exists. If it commits, both exist—even if the service disappears before it can talk to Kafka.

Transactional outbox architecture The payment API atomically writes account and ledger state plus an outbox event to PostgreSQL. Debezium reads committed changes from WAL and routes the event to Kafka, which has independent notification, analytics and fraud consumers. Payment APIone DB transaction PostgreSQL accounts + ledger outbox eventsame COMMIT Debeziumreads committedWAL changesOutbox EventRouter Kafkatopic 1 2 3 notifications · analytics · fraud WAL is recovery first; logical decoding makescommitted changes available to CDC.
Figure 2. The database transaction guarantees the business change and its publication intent travel together. CDC delivers that intent beyond the database boundary.

A useful event record usually carries a stable event_id, an aggregate or transfer ID, an event type, a schema version, a creation time, and the payload. Add an aggregate sequence if consumers need to detect ordering gaps. Keep sensitive data out of payloads unless every subscriber is entitled to it.

-- Shape, not a universal schema
BEGIN;
  UPDATE accounts ...;
  INSERT INTO ledger_entries ...;
  INSERT INTO idempotency_records ...;
  INSERT INTO outbox_events
    (event_id, aggregate_id, event_type, payload, created_at)
  VALUES (...);
COMMIT;

Getting committed events out

For a modest system, a polling publisher is often the easiest thing to operate. It selects unpublished rows in batches, claims them safely—commonly with row locks and FOR UPDATE SKIP LOCKED—publishes, then records progress. Polling is not inherently wrong; frequent empty queries, lock contention, table cleanup, and the latency/throughput trade-off are the costs to measure.

When the event stream is already central to the architecture, change data capture is a natural fit. PostgreSQL logical decoding exposes committed changes from WAL. Debezium reads those changes and its Outbox Event Router maps outbox rows to Kafka records. This avoids application-side polling, but it adds operational responsibilities: replication slots, WAL retention, connector health, schema evolution, and replay behavior.

WAL, CDC and Kafka are different layers. WAL supports database recovery. Logical decoding exposes committed changes. Debezium turns those changes into a stream. Kafka retains and distributes the resulting application events.

Try the failure, don't just read about it

Where does the event go missing?

Choose a design, then inject a crash at a specific point. The boxes show what is durable after the process stops.

Design
01 / DATABASEPaymentNot committed
02 / OUTBOXEvent intentNo record
03 / BROKERKafka eventNot published
04 / CONSUMERBusiness effectNot processed
Ready. Pick a failure point or run the successful path.
A simplified model, not a timing or throughput benchmark. In outbox mode, the relay can resume from durable database state; a crash after Kafka accepts an event may still cause a duplicate.

The simulator makes the key distinction visible: the outbox does not make a network call atomic with a database commit. It makes the need to publish durable and recoverable. A relay can resume after failure because the event intent was committed with the payment.

Assume duplicates; make effects idempotent

At-least-once delivery is the practical contract for many pipelines: a message should not silently vanish, but retries can deliver it more than once. For example, a CDC connector may publish an event and fail before its own progress is durably recorded. On recovery, it may publish that event again.

Consumers should therefore treat event_id as a stable deduplication key. If a consumer updates its own database, insert that ID into a processed-events table in the same transaction as the business effect. A unique constraint turns a replay into a harmless no-op.

-- The event receipt and business update commit together.
BEGIN;
  INSERT INTO processed_events (event_id)
  VALUES (:event_id)
  ON CONFLICT DO NOTHING;

  -- Apply the effect only if the insert was new.
  UPDATE customer_activity ...;
COMMIT;

That transaction works when the consumer's effect is in its own database. An email or SMS provider is another boundary: if the provider accepts the send but the consumer crashes before recording success, a retry can send twice. Use provider idempotency support or a stable delivery key where available; otherwise, be honest that exactly-once external side effects are not guaranteed.

“Exactly once” needs a boundary. Kafka transactions can coordinate Kafka records and offsets in Kafka workflows. They do not automatically include a PostgreSQL commit or an external provider's side effect. End-to-end correctness still depends on application-level idempotency.

The decisions worth writing down

The outbox is a small table with a meaningful operational footprint. These are the choices I would make explicit before calling the design done.

01 / COMMIT BOUNDARY
What belongs in the transaction?

Payment state, ledger entries, idempotency result, and the outbox record. Not Kafka publication, HTTP notification, or another service call.

02 / RELAY
Polling or CDC?

Start with polling when it meets volume and operational needs. Prefer CDC when low-latency change streaming justifies connector and WAL-slot operations.

03 / ORDER
What ordering do consumers need?

Partition by aggregate ID when per-account or per-transfer order matters. Define sequence numbers and gap handling; a global total order is expensive and rarely necessary.

04 / RETENTION
How long do records stay?

Set a cleanup policy for published rows, preserve enough history for diagnosis, and monitor table growth, replication lag, and WAL retention.

05 / RETRY
What happens to poison events?

Bound retries, alert on repeated failures, and define a quarantine or dead-letter workflow that supports safe replay—not silent deletion.

06 / CLIENT RETRIES
Can a payment request repeat?

Persist idempotency keys with a request fingerprint and result. Reusing the key with different payment details should fail clearly.

Why not put everything in Kafka transactions?

Kafka's producer idempotence and transactions are useful inside Kafka's own boundary. A payment must also commit to PostgreSQL, where the balances and ledger live. Without distributed transaction coordination across both systems—and all the complexity that entails—Kafka cannot make those two commits one indivisible action. The outbox keeps the source-of-truth transaction local, then relies on replay and idempotent consumers.

And the rest of the payment platform?

Client idempotency protects against the familiar timeout-after-commit retry. Guarded updates and database constraints protect the balance invariant under concurrency. A shared rate limiter such as Redis can protect the database from abusive traffic, but it should not decide whether a transfer happened or whether a balance is valid. Those correctness decisions stay with PostgreSQL.

Failure or pressureDesign responseWhat it does not replace
Partial transferOne database transaction; ledger debit and credit togetherConcurrency controls and balance constraints
Crash after commitPostgreSQL durability and WAL recoveryApplication event publication
Commit succeeds, event missingTransactional outbox plus recoverable relayConsumer idempotency
Duplicate deliveryStable event ID and idempotent effectExactly-once external provider behavior
Client retries transferPersisted idempotency key and request resultEvent deduplication at consumers

Reliable systems are explicit about what can fail

The path from a balance update to a Kafka consumer is not one giant transaction. It is a sequence of smaller guarantees: PostgreSQL protects the payment and event intent together; CDC or a poller carries that intent forward; Kafka makes it available to independent consumers; consumers guard their own effects against replay.

That is the value of the outbox. It does not erase failure, and it does not promise that every external side effect happens once. It gives the system a durable place to remember work that still needs doing—and a way to try again without losing the payment that started it.

Commit the fact. Persist the intent. Deliver it at least once. Make the effect safe to repeat.