When Payment Succeeds and the Event Disappears: Distributed Transactions and Stream Processing

0
261

The failure every architect should design for first

A customer places an order. The payment service charges their card, commits the payment to its database, and then crashes before it publishes a PaymentCompleted event.

The customer has paid. Inventory never reserves the item. Order management still shows the order as pending. Nobody gets an error, and nothing retries, because as far as the rest of the system knows, nothing happened.

This is the problem modern architectures have to solve. In a monolith, one ACID transaction covered payment, inventory and order status together. Today those live in separate services, each with its own database, connected by events flowing through a platform like Kafka. The challenge is no longer managing a transaction. It’s managing consistency across a business process that no single transaction controls.

Two capabilities do most of that work: distributed transaction patterns that coordinate the process, and stream processing that moves and reacts to the changes. This article walks through both, using that one order, and shows where they meet.

Why not just use a distributed transaction?

The classic answer to cross-system consistency is two-phase commit (2PC), standardized as XA. A coordinator asks every participant to prepare, then tells them all to commit or all to abort. It works, and it gives you real atomicity.

Most service architectures avoid it for three reasons:

  • It blocks. Participants hold locks between prepare and commit. If the coordinator fails at the wrong moment, those locks stay held until it recovers.
  • It couples availability. The transaction succeeds only if every participant is up, so each service’s uptime now depends on all the others.
  • Most of your participants can’t join. Message brokers, SaaS APIs and payment gateways generally don’t speak XA. You can’t enlist Stripe in your transaction.

That doesn’t make strong consistency obsolete. Distributed SQL databases such as Google Spanner and CockroachDB provide genuine ACID transactions across nodes and regions. If two pieces of data must always change together, the best design may be to keep them in the same database rather than split them and compensate. Service boundaries should follow consistency boundaries, not the other way around.

For everything that genuinely spans services, we need a different toolkit.

The toolkit: making each step reliable

Transactional outbox: never lose the event

The lost PaymentCompleted happened because the service did two things, writing to its database and publishing to the broker, and only the first one succeeded. The outbox pattern turns those two writes into one. The service records the payment and the event in the same local database transaction:

BEGIN;

UPDATE payments
   SET status = ‘COMPLETED’
 WHERE payment_id = :payment_id;

INSERT INTO outbox (event_id, aggregate_id, event_type, payload, created_at)
VALUES (gen_random_uuid(), :order_id, ‘PaymentCompleted’, :payload, now());

COMMIT;

Either both rows commit or neither does. A separate relay then reads the outbox and publishes each event to the broker. If the service crashes after the commit, the event is still sitting in the outbox, and the relay will deliver it.

transactional outbox flow · payment to consumers

The payment and its event commit together; everything downstream is built to tolerate a second delivery.

The trade-off: the relay may publish the same event more than once, for example if it crashes after publishing but before marking the row as sent. The outbox guarantees at-least-once delivery, not exactly-once.

Idempotent consumers: survive the duplicate

Because events can arrive twice, every consumer must be safe to run twice. The most reliable way is the mirror image of the outbox, often called the inbox pattern: the consumer records each event_id it has processed in the same transaction as its state change, and skips any ID it has already seen.

A retry that charges a card twice or reserves two units of stock isn’t a retry. It’s a new bug. Idempotency keys on external calls (most payment APIs support them) close the same gap at the edge of your system.

Sagas: coordinate the whole process

Outbox and inbox make each step reliable. A saga makes the sequence reliable. It breaks the business process into local transactions (charge payment, reserve inventory, create shipment), and defines what to do when a later step fails.

There are two ways to run one:

StyleHow it worksStrengthWatch out for
ChoreographyEach service reacts to the previous service’s event; no central coordinatorLoose coupling, simple for 2–3 stepsThe process exists only implicitly; hard to see or change as steps grow
OrchestrationA coordinator tells each service what to do next and tracks stateThe process is explicit, observable and testableThe orchestrator is a component you must make durable

Durable execution engines such as Temporal have become a popular way to implement orchestration, because they persist the workflow’s state and resume it after crashes.

Compensation is not rollback

When inventory reservation fails after payment succeeded, the saga can’t undo the charge the way a database undoes an uncommitted row. It issues a compensating action: a refund. That’s a new business event, visible to the customer and the ledger, and it can fail too, so it needs its own retries.

Some steps can’t be compensated at all. Once a package leaves the warehouse, you can’t un-ship it. Good saga design orders the steps so that the irreversible one (the pivot step) comes after everything likely to fail. Reserve inventory and confirm payment first; ship last.

Where stream processing comes in

Business data isn’t just something we store and query. It changes continuously, and stream processing lets systems react as those changes arrive instead of waiting for a nightly batch. In our order flow, streaming isn’t a separate concern from the transaction patterns. It’s where they connect.

Change data capture: where the transaction becomes the stream

The outbox relay doesn’t have to poll a table. Change data capture (CDC) tools such as Debezium read the database’s own commit log and publish each committed outbox row as a Kafka event. The database transaction log becomes the event stream. This is the literal meeting point of transactional consistency and stream processing: nothing reaches the stream that didn’t commit, and nothing that committed is lost.

Exactly-once, and where it stops

Kafka offers exactly-once semantics through idempotent producers and transactions that atomically consume an input, write the output and commit the offset. In effect, it’s a distributed transaction inside the streaming platform.

The guarantee ends at Kafka’s boundary. When a stream processor calls a payment API, sends an email or writes to an external database, those side effects can still happen twice. The idempotency rules from the previous section still apply.

Ordering: partition by the business key

Kafka guarantees order only within a partition. If PaymentCompleted and OrderCancelled for the same order land in different partitions, a consumer can see them in the wrong order. Use the order ID as the message key so every event for one order lands in the same partition and arrives in sequence. Ordering across different orders is rarely needed, and that’s what lets the system scale.

Late data and replay

Events don’t always arrive when they happened. A mobile client reconnects, a relay restarts, a partition rebalances. Stream processors handle this with event-time windows and watermarks, which decide how long to wait for stragglers before closing a window.

Replay is the other side of this. Because Kafka retains events, you can rebuild a read model or reprocess after a bug fix by replaying the log. That only works safely if every consumer is idempotent, which is one more reason idempotency is the foundation everything else stands on.

Watching the saga from the stream

Streaming can also make the business process observable. A stream processor can join PaymentCompleted with InventoryReserved on the order ID inside a time window. A payment with no matching reservation after the window closes is a stuck saga. The processor can raise an alert, open an incident or trigger compensation automatically. The failure from the opening of this article no longer goes unnoticed; it becomes an event the system acts on.

The questions that matter

Patterns are the easy part. The architecture is in the answers to these questions, asked for every business process that crosses a service boundary:

  1. What is the source of truth for each business state? One owner per fact. If two services both believe they own order status, no pattern will save you.
  2. Where do we require strong consistency, and where is eventual consistency acceptable? Account balances and stock counts usually need the former. Recommendations and dashboards rarely do. Draw the line deliberately.
  3. How do we prevent duplicate actions? Name the idempotency key for every consumer and every external call.
  4. What happens when an event is delayed, lost or replayed? Trace each one through the flow before production does it for you.
  5. How do we recover when only part of a workflow succeeds? Define the compensating action for every step, and know which step is the pivot.
  6. How will we know a process is stuck? If the answer is “a customer will call us,” the design isn’t finished.

Designing for recovery

Modern architecture isn’t microservices plus Kafka. It’s the deliberate design of consistency, communication and recovery across the entire business process: transactions where data must change together, outbox and idempotency where it crosses boundaries, sagas to coordinate the sequence, and streams to carry the changes and watch for failure.

The real measure of a distributed system isn’t whether everything works when the network is healthy. It’s whether the system recovers correctly when things inevitably go wrong.

Which of these patterns has saved you in production, and which one bit you? Share your experience in the comments, and subscribe to the Design and Execute newsletter for more on enterprise data architecture.