Skip to content
Visual explainer 3h to learn 4 steps

Distributed transactions, sagas & outbox

Keep data consistent across services without two-phase commit everywhere.

By Invicly Tech, , in System Design Deep Dive. About 11 minutes to read.

Topic 19 of 33

In short

When one business action spans several services, a single database transaction is no longer possible. Two-phase commit locks everyone and blocks on failures, so most systems use sagas with compensations and the outbox pattern for reliable events.

Explained simply

Inside one database, a transaction makes several changes all-or-nothing. But when an action spans several services, each with its own database, there is no single transaction to wrap around them. Placing an order might mean charging a card in one service, reserving stock in another and booking a courier in a third.

One classic answer is two-phase commit: a coordinator asks everyone to prepare, then tells everyone to commit. It works, but it is slow and fragile, because everyone must hold locks and wait, and if the coordinator dies at the wrong moment, they are stuck.

Most modern systems use a saga instead. A saga is a chain of small local transactions, one per service. If a later step fails, the earlier steps are undone by compensations: for example, refund the payment if the stock cannot be reserved. The system is briefly inconsistent, but it always ends up in a correct state.

Sagas need reliable messages between steps. The outbox pattern saves the event in the same database transaction as the change, so neither can happen without the other. Since messages can still arrive twice, every receiver must be able to handle duplicates safely.

Press Play on a diagram to walk through it one step at a time.

SequenceOrder saga with compensation
Order svc
Payment svc
Inventory svc
  1. 1Create order (PENDING)
    Order svc to Order svc: Create order (PENDING)
  2. 2Charge customer
    Order svc to Payment svc: Charge customer
  3. 3Payment succeeded
    Payment svc to Order svc: Payment succeeded
  4. 4Reserve items
    Order svc to Inventory svc: Reserve items
  5. 5Out of stock
    Inventory svc to Order svc: Out of stock
  6. 6Compensate: refund payment
    Order svc to Payment svc: Compensate: refund payment
  7. 7Mark order CANCELLED
    Order svc to Order svc: Mark order CANCELLED
FlowTransactional outbox
  1. 1
    One local transaction

    Write business row and outbox row together

  2. 2
    Relay reads outbox

    Polling or CDC picks up new rows

  3. 3
    Publish to broker

    Event sent to Kafka or a queue

  4. 4
    Mark as sent

    Retries are safe, duplicates possible

  5. 5
    Idempotent consumers

    Dedupe by event ID

FlowA travel booking saga with a pivot
  1. 1
    Hold flight seat

    Compensate: release hold

  2. 2
    Hold hotel room

    Compensate: release hold

  3. 3
    Capture payment

    Pivot: point of no return

  4. 4
    Confirm flight and hotel

    Retry until it succeeds

  5. 5
    Send itinerary

    Retry; idempotent by booking ID

In depth

Why two-phase commit is costly

In two-phase commit (2PC), a coordinator first sends prepare to every participant. Each one makes the change durable but not visible, keeps its locks, and votes yes or no. If all vote yes, the coordinator sends commit; otherwise abort. Once a participant votes yes, it may not decide on its own: it must wait for the coordinator.

That is the problem. Locks are held across at least two network round trips, so throughput drops. If the coordinator crashes after prepare, participants are in doubt and keep their locks until it recovers, blocking other work. Every participant must support the protocol (XA in many databases), and message brokers and third-party APIs usually do not.

2PC still lives inside distributed databases like Spanner and CockroachDB, where each participant is itself a replicated consensus group, so a crashed node does not block the transaction for long.

SequenceTwo-phase commit
Coordinator
Orders DB
Payments DB
  1. 1Prepare
    Coordinator to Orders DB: Prepare
  2. 2Prepare
    Coordinator to Payments DB: Prepare
  3. 3Yes (locks held)
    Orders DB to Coordinator: Yes (locks held)
  4. 4Yes (locks held)
    Payments DB to Coordinator: Yes (locks held)
  5. 5Commit
    Coordinator to Orders DB: Commit
  6. 6Commit
    Coordinator to Payments DB: Commit

Orchestration vs choreography

A saga can be run two ways. In orchestration, one service (the orchestrator) holds the saga's state and tells each participant what to do next: charge, then reserve, then ship, or compensate on failure. The flow is in one place, easy to read, monitor and change. Workflow engines like Temporal, AWS Step Functions and Camunda are built for this, with durable state and retries.

In choreography, there is no central brain. Each service listens for events and reacts: Orders publishes OrderCreated, Payments hears it and publishes PaymentCaptured, Inventory hears that and reserves stock. It is loosely coupled and simple for two or three steps, but the overall flow is scattered across services, and it is hard to answer where is order 77 right now.

A common rule of thumb: choreography for short, simple flows; orchestration once a saga has more than three or four steps or complex failure handling.

CompareTwo ways to run a saga
Orchestration
  • Central coordinator sends commands
  • Flow visible in one place
  • Easier to add steps and timeouts
  • Temporal, Step Functions
Choreography
  • Services react to events
  • No single coordinator
  • Flow spread across services
  • Good for 2 or 3 steps

Designing compensations

A compensation is a semantic undo, not a database rollback. You cannot unsend an email or un-charge a card, but you can send a correction or issue a refund. Each compensation must itself be idempotent and retryable, because it may run more than once.

Order the steps carefully. Put steps that are easy to undo, or likely to fail, early. Many sagas have a pivot step: the point of no return, such as capturing a payment or shipping a parcel. Steps before the pivot are compensatable; steps after it must be retried until they succeed rather than undone.

Sagas give up isolation: other requests can see the half-done state. Countermeasures include a semantic lock (mark the order PENDING so other flows treat it carefully), reserving rather than taking resources (hold stock, then confirm), and re-reading current values before acting.

  • Compensation = business-level undo (refund, release, cancel)
  • Steps after the pivot are retried, not compensated
  • Use PENDING states so others see work in progress

The outbox relay: polling or CDC

The outbox pattern writes an event row in the same transaction as the business change. A separate relay then publishes those rows to the broker. There are two ways to build the relay.

Polling: a worker repeatedly selects unsent rows, publishes them, and marks them sent. With PostgreSQL, SELECT ... FOR UPDATE SKIP LOCKED lets several workers share the table without taking the same rows. It is simple but adds query load and some delay.

Change data capture (CDC): a tool like Debezium reads the database's change log (the PostgreSQL WAL or MySQL binlog) and turns new outbox rows into Kafka messages, with low latency and no polling queries.

Either way the relay may publish a row, crash before marking it sent, and publish it again, so delivery is at least once. Keep events for the same entity in order by using the entity ID as the Kafka message key, and delete old outbox rows regularly.

Idempotent consumers

Because the outbox, brokers and retries all give at-least-once delivery, a consumer will sometimes see the same event twice. It must apply the effect only once.

The standard technique is a processed-events table with the event ID as its primary key. In one local transaction, the consumer inserts the event ID and applies the change. If the insert hits a duplicate key, the event was already handled, so the consumer skips it and acknowledges the message. Because both writes share one transaction, there is no window where the effect happened but the ID was not recorded.

Some effects are naturally idempotent and need no table: setting status = SHIPPED, or an upsert keyed by order ID. Effects like add 10 points or send an email need the dedupe record. For external calls such as email providers, pass the event ID as their idempotency key too.

Learn it in 4 short steps

About 45m each. Track them with a timer in your plan.

  1. 1
    Explain why 2PC is costly~45m
  2. 2
    Design a saga with compensations~45m
  3. 3
    Use the transactional outbox pattern~45m
  4. 4
    Handle duplicate events idempotently~45m

Key points

  • 2PC blocks participants if the coordinator fails mid-commit.
  • A saga is a chain of local transactions, each with a compensating action.
  • Orchestrated sagas use a coordinator; choreographed sagas react to events.
  • The outbox avoids the dual-write problem between database and broker.
  • Consumers must deduplicate because events can arrive twice.

Key terms

Tap a card to flip it. 0/5 known

Examples

sql
BEGIN;
INSERT INTO orders (id, user_id, status)
  VALUES ('o-77', 42, 'PENDING');
INSERT INTO outbox (event_id, topic, payload)
  VALUES ('e-901', 'order.created',
          '{"orderId":"o-77","userId":42}');
COMMIT;
-- A relay later publishes outbox rows and marks them sent

Order row and event committed atomically.

A food order saga with a failure

Step 1: Orders creates order 77 as PENDING and writes OrderCreated to its outbox in the same transaction. Step 2: the orchestrator tells Payments to authorise 25 dollars; it succeeds. Step 3: it tells Restaurant to accept the order; the restaurant is closed and replies rejected. Step 4: the orchestrator runs compensations in reverse: void the payment authorisation, then mark the order CANCELLED. Step 5: the customer sees a clear message. At no point were locks held across services, and every step and compensation can be retried safely because each uses the order ID as an idempotency key.

Deduplicating events in a consumer

A loyalty service gives 10 points per paid order. Kafka redelivers event e-901 after a consumer restart. Step 1: the consumer begins a transaction. Step 2: it inserts e-901 into processed_events; the first time this succeeds. Step 3: it adds the points. Step 4: it commits, then acknowledges the message. On redelivery, the insert does nothing, the consumer sees zero rows inserted, skips the points, and acknowledges. The customer gets 10 points, not 20.

sql
BEGIN;
INSERT INTO processed_events (event_id)
VALUES ('e-901')
ON CONFLICT (event_id) DO NOTHING;
-- if 0 rows were inserted: ROLLBACK and acknowledge the message
UPDATE loyalty SET points = points + 10
 WHERE user_id = 42;
COMMIT;

Quick reference

  • 2PC: prepare, then commit; participants hold locks and block if the coordinator dies
  • Saga: local transactions plus compensations, eventually consistent
  • Orchestration: one coordinator (Temporal, Step Functions); choreography: services react to events
  • Pivot step = point of no return; later steps are retried, not undone
  • Outbox: business row + event row in one transaction; a relay publishes later
  • Relay options: polling with FOR UPDATE SKIP LOCKED, or CDC with Debezium
  • Consumers dedupe with a processed_events table in the same transaction as the effect
  • Use the entity ID as the Kafka key to keep its events in order

Common mistakes

  • Writing to the database then publishing to Kafka without an outbox.
  • Compensations that are not idempotent.
  • Forgetting that saga intermediate states are visible to other readers.

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1What happens in 2PC if the coordinator crashes after all participants voted yes?

Question 2

2What is a compensation in a saga?

Question 3

3What problem does the outbox pattern solve?

Question 4

4Why must saga consumers be idempotent?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    For a hotel booking saga (reserve room, charge card, send confirmation email), write the compensation for each step, or say why there is none.

  2. Exercise 2medium

    Write the SQL a polling outbox relay runs to safely claim up to 100 unsent events when several relay workers run at once.

  3. Exercise 3hard

    Design an orchestrated saga for 'transfer money between two banks' (debit at bank A, credit at bank B). Cover the steps, the pivot, compensations, and what happens if the orchestrator crashes mid-way.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Is a saga the same as eventual consistency?
A saga produces eventual consistency: for a short time other readers can see a half-finished state, but the saga always ends either fully done or fully compensated.
Can Kafka transactions replace sagas?
No. Kafka transactions make reading from and writing to Kafka atomic within Kafka. They do not cover your service databases or external APIs, which is what a saga coordinates.
When is 2PC still acceptable?
Inside a single distributed database that implements it on replicated nodes, such as Spanner or CockroachDB, or between a few tightly coupled systems with low latency where blocking on failure is acceptable.

Go deeper

ShareXLinkedInWhatsApp