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.
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.
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.
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.
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.
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.
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.
Payment state, ledger entries, idempotency result, and the outbox record. Not Kafka publication, HTTP notification, or another service call.
Start with polling when it meets volume and operational needs. Prefer CDC when low-latency change streaming justifies connector and WAL-slot operations.
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.
Set a cleanup policy for published rows, preserve enough history for diagnosis, and monitor table growth, replication lag, and WAL retention.
Bound retries, alert on repeated failures, and define a quarantine or dead-letter workflow that supports safe replay—not silent deletion.
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 pressure | Design response | What it does not replace |
|---|---|---|
| Partial transfer | One database transaction; ledger debit and credit together | Concurrency controls and balance constraints |
| Crash after commit | PostgreSQL durability and WAL recovery | Application event publication |
| Commit succeeds, event missing | Transactional outbox plus recoverable relay | Consumer idempotency |
| Duplicate delivery | Stable event ID and idempotent effect | Exactly-once external provider behavior |
| Client retries transfer | Persisted idempotency key and request result | Event 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.