System Design Part 7 Architecture evolution

Sagas and the Outbox Pattern: Keeping a Cross-Service Flow Consistent Without Distributed Transactions

Bill.Lin 17 min read

System Design series Part 7-3 | Previous: Service Discovery | Next: Batch and Stream Processing | Series map

Read first: Part 5-3 Pub/Sub and Delivery Semantics.

Scenario and problem

Once payments are split out into their own service, “sign up and pay” spans three services and three databases:

  1. Sign-up service: reserve a seat and create a sign-up that is “awaiting payment”
  2. Payment service: charge the user through the payment gateway
  3. Sign-up service: mark the sign-up “confirmed”, and the notification service sends the e-ticket

In a monolith, the first two steps can share one database transaction: if the charge fails, the seat reservation rolls back with it. Now they live in different databases, and a local transaction cannot reach another service’s database.

  • The seat is reserved, but the charge fails: the seat has to be given back, or the talk shows as full while seats are actually free
  • The charge succeeds, but the sign-up service crashes before updating the status: the user paid but has no sign-up record
  • The charge request times out: you do not know whether the money was actually taken
Sign-up and payment across three services1 / 6
Sign-up and payment across three servicesSign-upsPaymentsPay gatewaySign-up DBPayment DBSign-upsSign-up DBhold, unpaidSign-upsPaymentsPay gatewayPayment DBchargechargepayment recordSign-upsSign-up DBmark confirmedPaymentsPay gatewaySign-up DBcharge failedSeat still heldSign-upsPayment DBSign-up DBCrashed before updateAlready chargedStill unpaidSign-upsPaymentscharge timeoutCharged or not?
  1. Reserve a seatThe sign-up service reserves a seat and creates a sign-up awaiting payment, written to the sign-up service's own database.
  2. ChargeThe payment service charges through the payment gateway and writes the record to its own database. In a monolith these two steps could share one transaction; now they live in different databases, and a local transaction cannot reach another service's database.
  3. Confirm and send the ticketAfter the charge succeeds, the sign-up service marks the sign-up "confirmed" and the notification service sends the e-ticket. This is the case where everything goes well.
  4. The charge failsThe seat is reserved, but the charge fails. The seat has to be given back, or the talk shows as full while seats are actually free.
  5. Crash before the updateThe charge succeeds, but the sign-up service crashes before updating the status. The user paid but has no confirmed sign-up record.
  6. The charge times outThe charge request times out, and you do not know whether the money was actually taken. Retrying might charge twice; not retrying might lose a payment.

The simplest approach and its limits

Distributed transactions (two-phase commit, 2PC): a coordinator first asks every participant “can you commit?”, and tells them to commit only if all of them agree.

  • Between the two phases, every participant has to lock the data and wait for the coordinator’s decision. If the coordinator crashes at that point, the participants can only keep waiting
  • Participants have to support a protocol such as XA. HTTP APIs, external payment gateways, and most message brokers do not
  • A commit happens only when every participant is healthy, so overall availability is the product of each participant’s availability

Call each step in order in code, and catch failures to clean up:

java
reserveSeat();
try {
    paymentClient.charge(...);
} catch (Exception e) {
    releaseSeat();          // What if the process crashes right before this?
    throw e;
}
confirmRegistration();      // If this step fails, the money is already taken

The state of this code exists only in memory. If the process crashes or is redeployed between any two lines, the cleanup never happens. And a charge that times out and lands in catch may in fact have succeeded.

Core mechanism

Sagas: a chain of local transactions, each with a compensation

Hector Garcia-Molina and Kenneth Salem proposed sagas in 1987: split a long flow into a chain of local transactions T1, T2, …, Tn, each committing on its own. If step k fails, run the compensating transactions of the earlier steps in reverse order: Ck-1, …, C1.

Compensation is a semantic undo, not a database rollback:

Step Compensation
Reserve a seat Release the seat
Charge Refund (not deleting the charge record: the charge did happen, and the books need a record of it)
Send a confirmation email Cannot be recalled; you can only send a correction notice

Pivot transactions: the step you cannot take back

Not every step can be compensated. An email that has been sent cannot be recalled, and a charge already handed to an external payment gateway cannot always be canceled. Saga steps fall into three kinds:

  • Compensatable steps: can be undone on failure, such as reserving a seat
  • Pivot transaction: once it succeeds, there is no going back, and the whole saga must run forward to completion, such as a successful charge
  • Retriable steps: the steps after the pivot must be guaranteed to eventually succeed; they can only be retried, never fail, such as confirming the sign-up and sending the e-ticket

So the order of the steps matters: compensatable steps first, hard-to-compensate steps later, irreversible steps after the pivot. Reserve the seat first (it can be released), then charge (the pivot), and send the e-ticket last (just retry until it succeeds). If you did it the other way round and sent the ticket before charging, a failed charge would mean sending “your ticket has been voided”.

Choreography and orchestration

flowchart LR
    subgraph CH["Choreography: each service reacts to events"]
        R1[Sign-up service] -->|SeatReserved| P1[Payment service]
        P1 -->|PaymentSucceeded| R1
        P1 -->|PaymentSucceeded| N1[Notification service]
    end
    subgraph OR["Orchestration: a coordinator sends commands"]
        O[Checkout coordinator] -->|ChargePayment| P2[Payment service]
        P2 -->|PaymentResult| O
        O -->|IssueTicket| N2[Notification service]
    end
Choreography Orchestration
How Each service listens for other services’ events, does its own work, then publishes an event One coordinator keeps the flow’s state, sends commands in order, and handles the replies
Pros No center; simple when there are few steps The flow is written in one place: easy to read, easy to test, easy to add timeouts to
Cons The flow is scattered across services, and nobody sees the whole picture; with more steps, cyclic dependencies creep in The coordinator can keep growing and pull in every service’s business logic
Good for Two or three steps whose reactions are independent of each other Flows with many steps, branches, timeouts, and compensations

The coordinator should own only the “flow”: what to do next, and what to compensate on failure. How to charge and how to count seats are still each service’s own business.

Every step must be sent reliably

Each saga step is “update your own database” plus “notify the next step”. If these two happen separately, you are back to the dual-write problem from the Message Queue post: the database commits, the message never goes out, and the saga gets stuck halfway.

The fix is the transactional outbox: write the outgoing message to an outbox table in the same database, committed in the same local transaction as the business data; a separate process then sends the outbox contents to the broker. The two ways of sending them, polling and CDC, are covered in full in Outbox Pattern.

The outbox guarantees at-least-once delivery, so every receiver must be idempotent (Idempotency post): the payment service uses the saga ID as the Idempotency Key, so even if the same charge command arrives twice, it charges only once.

Sagas have no isolation

Local transactions have ACID; a saga has only ACD, no I. Once each step commits, its intermediate state is visible to everyone else:

  • While a seat is reserved but not yet paid for, everyone else already sees one fewer seat remaining. If the payment fails in the end, someone may have left in the meantime because the talk looked “full”
  • Two sagas working on the same data at the same time may overwrite each other

Chris Richardson lists several countermeasures; the most common are:

  • Semantic lock: mark “in progress” with a status column, such as the sign-up’s PENDING_PAYMENT. Other operations that see this status know it is not final yet, and can reject, wait, or handle it according to business rules
  • Commutative updates: remaining = remaining - 1 and remaining = remaining + 1 give the same result in any order, so a compensation can safely interleave with other updates
  • Reread values: before a compensation or the next step runs, reread the data and check that it has not changed (the optimistic locking from the Transactions and Isolation Levels post)

Timeouts and late replies

A saga step may never get a reply: the payment service crashes after receiving the command, the message is stuck in a DLQ, the payment gateway never calls back. So every waiting state needs a deadline:

  • If there is no payment result within 15 minutes, cancel the sign-up and release the seat
  • But the payment result may arrive after the cancellation: the charge actually succeeded. You cannot just ignore it; it has to trigger a compensation: a refund

Timeout handling and a late reply can happen at the same time. Both must go through a conditional state transition (“change it to canceled only if the status is still awaiting payment”) to decide who wins, and the loser acts on the latest state.

Comparing options

Option Consistency Good for Cost
A local transaction in one database Strong consistency Data in the same service and the same database Related data has to live together
2PC / XA Strong consistency Databases in the same data center that all support XA Blocking, long lock times, multiplied availability; unusable across HTTP services
Choreographed saga Eventual consistency Few steps, independent reactions The flow is invisible; timeouts are hard to handle
Orchestrated saga Eventual consistency Many steps, with branches and compensations You have to design the state machine, compensations, and timeouts
Durable execution engine (such as Temporal, Camunda) Eventual consistency Long-running flows with a great many steps One more platform to operate; workflow code has to follow the engine’s constraints

As the Sharding post put it, the best distributed transaction is the one you do not need: if two pieces of data always change together, first ask whether they belong in the same service and the same database.

In Java

This uses an orchestrated saga: the checkout coordinator lives in the sign-up service, because both the seats and the sign-ups belong to it.

1. Tables

sql
CREATE TABLE checkout_saga (
    saga_id         CHAR(36)     PRIMARY KEY,
    registration_id BIGINT       NOT NULL UNIQUE,
    lecture_id      BIGINT       NOT NULL,
    state           VARCHAR(20)  NOT NULL,          -- PAYMENT_PENDING, CONFIRMED, CANCELLED
    deadline        TIMESTAMP(3) NOT NULL,
    updated_at      TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3) ON UPDATE CURRENT_TIMESTAMP(3),
    KEY idx_state_deadline (state, deadline)
);

CREATE TABLE outbox (
    id          BIGINT       AUTO_INCREMENT PRIMARY KEY,
    topic       VARCHAR(100) NOT NULL,
    message_key VARCHAR(100) NOT NULL,
    payload     JSON         NOT NULL,
    created_at  TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP(3)
);

2. Outbox: writes only inside a transaction

java
@Component
public class Outbox {

    private final JdbcClient jdbc;
    private final JsonMapper jsonMapper;

    public Outbox(JdbcClient jdbc, JsonMapper jsonMapper) {
        this.jdbc = jdbc;
        this.jsonMapper = jsonMapper;
    }

    /** MANDATORY: throws right away when the caller has no transaction, instead of opening its own and quietly committing. */
    @Transactional(propagation = Propagation.MANDATORY)
    public void append(String topic, String key, Object message) {
        jdbc.sql("INSERT INTO outbox (topic, message_key, payload) VALUES (:topic, :key, :payload)")
                .param("topic", topic)
                .param("key", key)
                .param("payload", jsonMapper.writeValueAsString(message))
                .update();
    }
}

For the relay that sends the outbox contents to Kafka (polling or Debezium), see Outbox Pattern. The message key is the saga ID, so messages from the same saga go to the same partition and are processed in order (Pub/Sub post).

3. The checkout coordinator

java
@Service
public class CheckoutSaga {

    private static final Duration PAYMENT_DEADLINE = Duration.ofMinutes(15);

    private final JdbcClient jdbc;
    private final Outbox outbox;
    private final LectureCatalog catalog;

    public CheckoutSaga(JdbcClient jdbc, Outbox outbox, LectureCatalog catalog) {
        this.jdbc = jdbc;
        this.outbox = outbox;
        this.catalog = catalog;
    }

    /** Compensatable step: reserve the seat, create the sign-up awaiting payment, and send the charge command, all in one local transaction. */
    @Transactional
    public UUID start(long lectureId, long memberId) {
        int reserved = jdbc.sql("UPDATE lecture SET remaining = remaining - 1 WHERE id = :id AND remaining > 0")
                .param("id", lectureId)
                .update();
        if (reserved == 0) {
            throw new SoldOutException(lectureId);
        }
        KeyHolder keys = new GeneratedKeyHolder();
        jdbc.sql("""
                        INSERT INTO registration (lecture_id, member_id, status)
                        VALUES (:lectureId, :memberId, 'PENDING_PAYMENT')
                        """)
                .param("lectureId", lectureId)
                .param("memberId", memberId)
                .update(keys, "id");
        long registrationId = keys.getKey().longValue();

        UUID sagaId = UUID.randomUUID();
        jdbc.sql("""
                        INSERT INTO checkout_saga (saga_id, registration_id, lecture_id, state, deadline)
                        VALUES (:sagaId, :registrationId, :lectureId, 'PAYMENT_PENDING', :deadline)
                        """)
                .param("sagaId", sagaId.toString())
                .param("registrationId", registrationId)
                .param("lectureId", lectureId)
                .param("deadline", Timestamp.from(Instant.now().plus(PAYMENT_DEADLINE)))
                .update();

        // The server sets the amount from the talk; never use a number sent by the client
        long amount = catalog.priceOf(lectureId);
        outbox.append("payment-commands", sagaId.toString(), new ChargePayment(sagaId, memberId, amount));
        return sagaId;
    }

    /** The payment service replies with the result through its own outbox. */
    @KafkaListener(topics = "payment-results", groupId = "checkout-saga")
    @Transactional
    public void onPaymentResult(PaymentResult result) {
        SagaRow saga = find(result.sagaId());
        String target = result.succeeded() ? "CONFIRMED" : "CANCELLED";
        if (!transition(result.sagaId(), "PAYMENT_PENDING", target)) {
            handleLateOrDuplicate(saga, result);
            return;
        }
        if (result.succeeded()) {
            // After the pivot: everything below can only be retried until it succeeds; it must not fail
            updateRegistration(saga.registrationId(), "CONFIRMED");
            outbox.append("registration-events", result.sagaId().toString(),
                    new RegistrationConfirmed(saga.registrationId(), saga.lectureId()));
        } else {
            compensateSeat(saga);
        }
    }

    /** Timeout: no payment result before the deadline, so cancel and release the seat, and ask the payment service to void the charge. */
    @Scheduled(fixedDelay = 60_000)
    @Transactional
    public void expireOverdue() {
        List<SagaRow> overdue = jdbc.sql("""
                        SELECT saga_id AS sagaId, registration_id AS registrationId, lecture_id AS lectureId
                          FROM checkout_saga
                         WHERE state = 'PAYMENT_PENDING' AND deadline < NOW(3)
                         LIMIT 100
                        """)
                .query(SagaRow.class)
                .list();
        for (SagaRow saga : overdue) {
            if (transition(saga.sagaId(), "PAYMENT_PENDING", "CANCELLED")) {
                compensateSeat(saga);
                outbox.append("payment-commands", saga.sagaId().toString(), new VoidPayment(saga.sagaId()));
            }
        }
    }

    /** Ignore duplicate replies; a "charge succeeded" that arrives after the timeout cancellation gets refunded. */
    private void handleLateOrDuplicate(SagaRow saga, PaymentResult result) {
        if (result.succeeded() && "CANCELLED".equals(currentState(saga.sagaId()))) {
            outbox.append("payment-commands", saga.sagaId().toString(),
                    new RefundPayment(saga.sagaId(), result.paymentId()));
        }
    }

    /** Conditional transition: when timeout handling and a payment reply arrive at the same time, only one of them succeeds. */
    private boolean transition(UUID sagaId, String from, String to) {
        return jdbc.sql("UPDATE checkout_saga SET state = :to WHERE saga_id = :id AND state = :from")
                .param("to", to)
                .param("id", sagaId.toString())
                .param("from", from)
                .update() == 1;
    }

    private void compensateSeat(SagaRow saga) {
        jdbc.sql("UPDATE lecture SET remaining = remaining + 1 WHERE id = :id")
                .param("id", saga.lectureId())
                .update();
        updateRegistration(saga.registrationId(), "CANCELLED");
    }

    // find, currentState, and updateRegistration are ordinary queries and updates, omitted
}
  • Every state transition is one local transaction that writes both the business data and the outbox. Whenever the process crashes, the state in the database is consistent, and no message in the outbox is lost
  • The conditional UPDATE ... WHERE state = :from is the coordinator’s entire concurrency control: when the same payment result is delivered twice, or timeout handling and a late reply happen at the same time, only the first transition succeeds
  • VoidPayment and RefundPayment must both be idempotent on the payment service side, identified by the saga ID. Voiding a charge command that never arrived should be a safe no-op
  • The coordinator’s state is stored in the database, not in memory. Through deploys, crashes, and scaling out to several instances, sagas keep going
  • When @KafkaListener and @Transactional are used together, the offset is committed only after the database transaction commits; if the transaction rolls back, the message is redelivered, and the conditional transition handles the duplicate

The code above is written from the official Spring Framework 7 and Spring for Apache Kafka documentation and has not been compiled or run. The SQL uses MySQL.

Pitfalls and gotchas

  • Treating compensation as rollback: a compensation is a new business operation; it leaves a record, and it can fail too. Compensations must also be idempotent and retriable, and when one keeps failing, you need a way to hand it to a human
  • Steps in the wrong order: an irreversible action placed before a step that can fail
  • No timeout: the saga sits in “awaiting payment” forever, and the seat stays taken forever
  • Ignoring late replies: a successful charge arrives after the timeout cancellation and no refund goes out; the user paid but has no sign-up
  • Keeping the coordinator’s state in memory: on a redeploy, every saga in progress disappears
  • Compensation and the original operation arriving out of order: “cancel the reservation” arrives before “reserve”. The receiver has to cope: record “this reservation has been canceled”, and reject the reservation when it arrives later
  • Ignoring the effects of missing isolation: reports and search read a sign-up that is awaiting payment and treat it as confirmed
  • A choreographed flow nobody understands: five services listen to each other’s events, and when something goes wrong, nobody knows where the flow is stuck. At the very least, you need to tie the whole flow together with a trace ID (Observability post)
  • Putting business logic in the coordinator: the coordinator starts calculating discounts and checking membership tiers, and becomes a new monolith

Security

  • Forged replies: if any service can write to payment-results, an attacker only has to send one PaymentSucceeded to confirm a sign-up for free. Restrict topics like this with ACLs so that only the payment service can write to them (Pub/Sub post), and have the coordinator check that the reply’s amount, member, and saga match
  • The server decides the amount: the amount in the charge command comes from the talk’s price, not from the client’s request. Otherwise an attacker could turn a NT$2,000 talk into a NT$1 one
  • Seat hoarding: reserving a seat requires no payment, so an attacker can use many accounts to reserve every seat without paying, locking real users out, and do it all again 15 minutes later. Limit how many reservations each account can hold at once, shorten the deadline, and add rate limiting and CAPTCHAs (Rate Limiting post)
  • Refunds are high-value operations: commands that trigger refunds need strict limits on who can send them, and idempotency protection. Replaying the same RefundPayment must not refund twice, and the payment service has to check that the refund amount does not exceed the original charge
  • Audit logs for state transitions: when a user disputes “I paid but I’m not signed up”, you need to answer when each step happened and which message caused it. Write every saga transition to the audit log (Observability post)
  • The outbox is data too: the outbox table and the messages on the broker may contain personal data and amounts. Encrypt them and restrict access just like business data, and clean them up after sending according to the retention period

When to use it, and when not to

  • Use a saga: the flow spans several services or external systems, cannot fit in one local transaction, and the business can accept a brief intermediate state
  • Use orchestration: many steps, with timeouts and compensations, and you need to see the state of the whole flow
  • Use choreography: two or three independent reactions, such as notifications, settlement, and recommendations each handling a confirmed sign-up on their own
  • Don’t use it: when the data could in fact live in the same database, first consider adjusting the service boundaries; when the business requires strict, immediate consistency and cannot accept even a brief intermediate state, a saga is not the answer, and you need to rethink who owns the data

References

Comments