TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

All concepts ยท distributed systems ยท microservices ยท transactions ยท consistency

Sagas and distributed transactions

Keeping data consistent across services that each own their database. Two-phase commit locks everyone until a coordinator decides; a saga runs a chain of local transactions and undoes the finished ones with compensating actions when a later step fails.

15 min6 animations

๐Ÿ“š Builds on๐Ÿ›’ Transactions and isolation

๐Ÿ–จ๏ธ Cheat sheet

One trip, three companies

You're planning a holiday. You need a flight, a hotel and a hire car, and each one comes from a different company. Each company keeps its own booking book, and none of them can see the others' books.

A package holiday from one company is a single booking: you get all of it or none of it. When three separate companies are involved, nobody can promise that. If you book the flight and the hotel, and then find out every car is gone, the flight and the hotel are still booked. You're left with half a trip.

Making several separate companies all agree "together or not at all" is called a distributed transaction, and it's much harder than buying a package holiday from one company.

Why one transaction can't span services

Inside one database, a transaction gives you ACID: the debit and the credit commit together or roll back together. In a microservice system, each service owns its data (database per service), so booking a trip touches three databases owned by three services, reached over the network.

No single database can roll back the others. Each service commits its local transaction on its own, and once the flight service has committed, a later failure in the car service can't undo it. Without extra machinery you end up with a partial update: some services changed, others didn't.

There are two families of answers:

ApproachIdeaConsistency
Two-phase commit (2PC)A coordinator makes every database commit atomicallyAtomic, isolated, but blocking
SagaA sequence of local transactions, with compensating actions to undo finished stepsEventually consistent, no isolation
One trip, three databases4 steps
๐Ÿง‘Youโœˆ๏ธAirline๐ŸจHotel๐Ÿš—Car hire
Press play and watch it happen!

Hold everything, then confirm

One way out: a travel agent phones each company and asks, "Can you hold this for me?" The airline holds a seat, the hotel holds a room, the car company holds a car, and each says "yes, it's held". Only when all three say yes does the agent ring round again: "Confirm it." If anyone says no, the agent says "let it go" to everyone.

This is called two-phase commit. It works, but it has a nasty weak spot. If the agent's phone dies after the holds and before the "confirm", the companies are stuck. They promised to wait, so they can't sell that room to anyone else, and they can't cancel it either, because the agent might have confirmed with the others. They just wait, room locked, until the agent calls back.

Two-phase commit and why it blocks

Two-phase commit (2PC) makes several resource managers commit atomically under a transaction coordinator:

  1. Prepare: the coordinator asks every participant to prepare. Each one makes its already-done work durable in its log, keeps its locks and votes yes or no. A yes vote is a promise to commit if told to.
  2. Commit: if every vote is yes, the coordinator logs the decision and tells everyone to commit; if any vote is no (or times out), it tells everyone to abort.

The weakness is between the phases. A participant that voted yes is in doubt: it can't commit on its own (someone else may have voted no) and can't abort (the others may have committed). If the coordinator crashes there, the participants keep their locks until it recovers and reads its log. 2PC is a blocking protocol; it also needs a round trip to every participant per transaction, and every participant must speak the protocol.

In Java, 2PC across resources uses the X/Open XA standard, driven through JTA (Jakarta Transactions) by a transaction manager. It's still used between databases and message brokers that support XA, but many modern components, including Kafka and most HTTP APIs, don't support it, and the locking makes it a poor fit for long-running business processes. That's why microservices usually reach for sagas instead.

Two-phase commit blocks5 steps
๐Ÿง‘โ€๐Ÿ’ผTravel agentโœˆ๏ธAirline๐ŸจHotel๐Ÿš—Car hire
Press play and watch it happen!

Book one by one, cancel if it goes wrong

The other way is the one most people use for real holidays. Book the flight: done, it's real. Book the hotel: done. Try the car. If the car company says "sorry, none left", you don't pretend nothing happened. You go back and cancel the hotel, then cancel the flight, newest first. Usually a travel agent does this for you, ticking each booking off in a notebook so nothing is forgotten.

A plan like this, with a list of steps and a cancel move for each one, is called a saga. Notice that cancelling isn't the same as never booking. The airline really did book your seat, sent you an email, and now sends a second email and gives your money back. A cancellation is a new action that puts things right, not an eraser.

The saga pattern

A saga (Garcia-Molina and Salem, 1987) splits a business transaction into a sequence of local transactions T1, T2, โ€ฆ Tn, each committed in one service's own database. Every step that might need undoing has a compensating transaction C1, C2, โ€ฆ If step Tk fails, the saga runs Ck-1 โ€ฆ C1 in reverse order. Something must track which steps have committed: typically an orchestrator that records each step in a saga log (see below).

Compensations are semantic undo, not rollback. T1 committed and other parties may already have seen it: an email was sent, a card was charged. C1 is a new forward action (cancel the booking, refund the payment) that brings the system back to an acceptable state, which may not be identical to the original one: a cancellation fee may apply, and the cancelled booking still exists in the history.

Two rules make compensation safe:

  • A compensation must not fail for business reasons. It's retried until it succeeds, so it must be idempotent.
  • Some steps can't be undone at all (a shipped parcel, a sent text message). Put them last.
๐Ÿ”ง Going deeper

Compensatable, pivot and retriable steps

Steps fall into three kinds. Compensatable steps come first and can be undone. The pivot is the go or no-go step: once it commits, the saga must run to the end. Retriable steps come after the pivot; they can't fail for business reasons, so they're simply retried until they succeed. In the trip, reserving the flight and hotel are compensatable, charging the card might be the pivot, and sending the confirmation email is retriable.

A saga undoes with compensations5 steps
Agent's notebook01234๐Ÿง‘โ€๐Ÿ’ผTravel agentโœˆ๏ธAirline๐ŸจHotel๐Ÿš—Car hire
Press play and watch it happen!

A travel agent, or a notice board

Someone has to know what comes next. There are two ways to arrange it.

With a travel agent, one person runs the whole plan. The agent books the flight, waits for "done", books the hotel, then the car, and if anything fails the agent makes the cancel calls. Everything about your trip is in one notebook on the agent's desk.

Without an agent, the companies take turns by themselves using a town notice board. You pin up "trip wanted". The airline sees it, books a seat and pins up "flight booked". The hotel sees that, books a room and pins up "hotel booked". If the car company pins up "no cars", the hotel and the airline see it and cancel. This is called choreography: like dancers who know the routine, nobody gives orders, and each one moves when they see the step before.

Choreography and orchestration

A saga's steps can be coordinated in two ways:

ChoreographyOrchestration
Who decides the next stepEach service, reacting to the previous service's eventOne orchestrator that sends commands and waits for replies
CouplingServices know each other's eventsServices know only their own commands; the orchestrator knows the flow
Where the flow livesSpread across every service's event handlersIn one place, with explicit saga state
Good forShort sagas, few participantsLonger flows, branching, timeouts, visibility
RiskHard to see the whole flow; cyclic dependencies between servicesThe orchestrator becomes a central component to keep simple

Choreographed sagas usually ride on a log or broker such as Kafka: TripRequested, FlightBooked, HotelBooked, CarRejected. Each service subscribes to the events it cares about, does its local transaction and publishes the next event. Some systems go further and keep those events as the source of truth; see event sourcing and CQRS.

An orchestrator is a state machine. It must persist its state after every step, so that after a crash it resumes where it was rather than starting again. A minimal Spring sketch (the clients, SagaRepository and SagaState are illustrative, not a library API):

1@Service2public class TripSaga {3    private final FlightClient flights;4    private final HotelClient hotels;5    private final CarClient cars;6    private final SagaRepository sagas;   // one row per trip: the saga's current state7    // constructor injection omitted for brevity8 9    public void run(Trip trip) {10        SagaState s = sagas.findOrStart(trip.id());11        try {12            if (s.before(FLIGHT_BOOKED)) { flights.book(trip.id(), trip.flight()); s = sagas.save(s.to(FLIGHT_BOOKED)); }13            if (s.before(HOTEL_BOOKED))  { hotels.book(trip.id(), trip.hotel());   s = sagas.save(s.to(HOTEL_BOOKED)); }14            if (s.before(COMPLETED))     { cars.book(trip.id(), trip.car());       s = sagas.save(s.to(COMPLETED)); }15        } catch (BookingRejectedException e) {16            s = sagas.save(s.to(COMPENSATING));17            hotels.cancel(trip.id());     // idempotent: cancelling an unknown or cancelled booking is a no-op18            flights.cancel(trip.id());19            sagas.save(s.to(COMPENSATED));20        }21    }22}

Every call is keyed by the trip id, so a retry after a crash is harmless (see idempotency). A real orchestrator also needs timeouts, retries with backoff and a way to resume sagas left mid-flight. That plumbing is what workflow engines provide.

๐Ÿ”ง Going deeper

Frameworks that keep saga state for you

Rather than hand-roll the state machine, teams often use a workflow engine. Temporal persists the workflow's progress and replays it after a crash; its Java SDK has a Saga helper that runs registered compensations in reverse order:

1Saga saga = new Saga(new Saga.Options.Builder().build());2try {3    saga.addCompensation(activities::cancelFlight, trip.id());   // register before the step,4    activities.bookFlight(trip);                                 // so a half-done step is undone too5    saga.addCompensation(activities::cancelHotel, trip.id());6    activities.bookHotel(trip);7    activities.bookCar(trip);8} catch (ActivityFailure e) {9    saga.compensate();10    throw e;11}

Registering the compensation before its step means it may run for a step that never really happened, so it must cope with that. Other options: Eventuate Tram Sagas, Camunda (Axon Framework 4 had @Saga, but Axon 5 dropped it), and on AWS, Step Functions state machines with Catch branches that run the compensating steps.

Choreography with events5 steps
Town notice board012345๐Ÿง‘Youโœˆ๏ธAirline๐ŸจHotel๐Ÿš—Car hire
Press play and watch it happen!

Pencilled in, not confirmed

Here's the catch with booking one by one: while your plan is half done, other people can see it. Your friend checks the hotel and sees your room taken, for a trip that might be cancelled ten minutes later. Or worse, someone changes the hotel booking while your trip is half done, and when your trip is cancelled, your cancellation wipes out their change.

So careful companies write the booking in pencil first, marked pending: "held for trip 42, not confirmed yet". Anyone who asks hears the honest answer, "it's on hold, try again soon", and nobody else can grab that room. When the whole trip works out, the agent rings to turn the pencil into ink. If it fails, the hotel crosses the booking out as cancelled and frees the room.

No isolation, and the countermeasures

A saga is ACD without the I. Each local transaction commits as soon as it finishes, so other transactions see the saga's intermediate states. That allows the classic anomalies across services:

  • Dirty reads: another request reads data a saga wrote and later compensates (a room shown as booked, then released).
  • Lost updates: another saga overwrites data a saga wrote, and the compensation then overwrites theirs.
  • Fuzzy reads: a saga reads the same data twice in different steps and sees different values.

You can't remove these, only design around them. The usual countermeasures:

  • Semantic lock: a compensatable step writes a flag, such as a PENDING status on the booking. Other requests treat pending records specially (wait, refuse, or show "on hold"), and the saga clears the flag when it confirms or compensates. Add a timeout so a crashed saga can't hold the lock forever.
  • Commutative updates: design updates so order doesn't matter (debit and credit amounts, not set balance).
  • Pessimistic view: reorder steps so the risky update happens in a retriable step after the pivot.
  • Reread value: before updating, check the record hasn't changed since you read it, like optimistic locking.

Pending states also make the user experience honest: "booking in progress" is a real, visible state of the system.

Pending states as a semantic lock5 steps
๐Ÿง‘โ€๐Ÿ’ผTravel agent๐ŸจHotel๐Ÿš—Car hire๐ŸงณAnother traveller
Press play and watch it happen!

When the trip hits a snag

In the notice board version, every company has to pin up its note after it books. Picture the hotel clerk writing your room into the booking book, then tripping before pinning the note up. The room is booked, but nobody hears about it, and the trip stalls forever.

So the hotel does both in one go: it writes the room in the booking book and puts the note it needs to send into a tray called the outbox, in the same office, as one single entry. Either both are done or neither is. A messenger then carries every note in the outbox to the notice board and ticks it off. If the messenger trips before ticking, they carry it again next time. The same note may be pinned up twice, so everyone checks the trip number and ignores a note they've already dealt with.

Other things can go wrong too. The travel agent might fall asleep halfway through the plan: the notebook says exactly which bookings are done, so a colleague can pick it up and carry on. A company might not answer when asked to book the hotel: the agent doesn't guess, but asks "is trip 42 booked with you?" before cancelling anything. And some things can't be taken back, like an email already sent: the agent sends a second one saying sorry, it was cancelled.

What can go wrong

Every saga step communicates over a network, so messages get lost, retried and delivered twice. Two building blocks make that safe; they are also the answer to the duplicate-delivery failure below:

Idempotent steps. Every command and event carries a stable id (the trip id, an event id), and every handler records what it has processed. A redelivered BookHotel for trip 42 finds the booking already there and replies with the same result. Compensations must be idempotent too. See idempotency.

The transactional outbox. A service must update its database and publish an event, and doing both directly is a dual write: a crash between them leaves a booking with no event, or an event with no booking. Instead, write the event into an outbox table in the same local transaction as the business change:

1@Transactional2public void bookRoom(BookRoom cmd) {3    if (bookings.existsByTripId(cmd.tripId())) return;          // duplicate command: already done (a unique constraint on trip id closes the race)4    bookings.save(new Booking(cmd.tripId(), cmd.room(), Status.PENDING));5    outbox.save(new OutboxEvent(UUID.randomUUID(), "HotelBooked", cmd.tripId(), toJson(cmd)));6}

A separate message relay publishes outbox rows to the broker, either by polling the table (a polling publisher, often with SELECT โ€ฆ FOR UPDATE SKIP LOCKED so relay instances don't collide) or by tailing the database's transaction log with change data capture, such as Debezium reading the Postgres WAL or the MySQL binlog. If the relay crashes after publishing but before marking the row sent, it publishes again: the outbox gives at-least-once delivery, so consumers must deduplicate by event id.

Failures to design for, beyond the pending-state anomalies above:

  • A compensation fails. Compensations are retried until they succeed (see the saga topic above), but the target can be down for hours or reject the call for a reason nobody planned. Symptom: sagas stuck in a COMPENSATING state, a growing retry count, a dead-letter queue filling up. Fix: retry with exponential backoff, alert when a saga stays in that state past a threshold, and give operators a manual intervention path (a dashboard or command to retry, skip or fix the data by hand). Never silently drop the saga.
  • The orchestrator crashes mid-saga. Nothing finishes the trip and, for example, a hotel stays PENDING. Symptom: sagas whose state hasn't changed for longer than any step should take. Fix: persist the saga state after every step (see the orchestrator sketch above), and on restart scan for unfinished sagas and resume them; the idempotent steps make re-running the step that was in flight harmless. A semantic-lock timeout releases anything that never resumes.
  • A step message is delivered twice. The relay republishes (scene below), or the broker redelivers after a missed acknowledgement. Symptom: a second hotel booking, a double charge. Fix: idempotent participants that keep the processed command or event ids (a unique constraint on the trip id is the simplest guard).
  • A step times out and the outcome is unknown. The orchestrator never got a reply: the booking may have happened, not happened, or still be in progress. Compensating blindly could cancel a booking that never existed, or miss one that did. Symptom: timeout exceptions such as SocketTimeoutException or a client TimeoutException. Fix: query the participant for the trip id's status before deciding, or resend the same idempotent command, which returns the real outcome; only then continue or compensate. A compensation registered for every step must also cope with a step that never ran.
  • A compensation can't truly undo. The confirmation email is already sent and the money has already left the card. Fix: semantic compensation, a new action that makes things right, such as a "your booking was cancelled" email or a refund (which may cost a fee), and put steps with outside effects after the pivot where possible.
ChoiceYou gainYou pay
Orchestration over choreographyThe flow, timeouts and saga state live in one place, so stuck sagas are easy to find and resumeA central component that must be persisted, kept highly available and kept free of business logic
Saga over 2PCNo cross-service locks and no blocking coordinator; works with APIs that can't do XANo isolation, semantic undo, compensations to write and eventual consistency
Pivot placed earlyFewer compensations: after it, the remaining steps are just retriedEvery later step must be retriable and sure to succeed, and you commit irreversibly before most checks have run
Pivot placed lateMore steps are compensatable, so failures cost less to reverseMore undo work and more time spent in visible intermediate states
The transactional outbox5 steps
๐Ÿข Hotel officeBooking book0123Outbox tray0123Town notice board0123๐ŸจHotel clerk๐ŸƒMessenger
Press play and watch it happen!

๐Ÿงฉ Quick quiz

Quick quiz! 5 questions about Sagas and distributed transactions, told the same way as the story.
  1. The agent has heard "yes, it's held" from all three companies, then their phone dies before the confirm call. What do the companies do?
  2. Your flight and hotel are booked when the car falls through. What does the plan do next?
  3. While your trip is half booked, a friend checks the hotel. What stops them being told the wrong thing?
  4. Why does the hotel write the note into the outbox tray on the same page as the booking, instead of pinning it up straight away?
  5. The agent asks the hotel to book your room but the phone line goes silent, with no answer. What should the agent do?
Answer every question to check.Passing marks Sagas and distributed transactions as done.
Got the hang of Sagas and distributed transactions? Mark it as done, and your paths show how far youโ€™ve got.

Saved in this browser.

๐Ÿ“จ Event-driven systemsStep 4 of 5

โ† Previous on the path๐Ÿ“’ Event sourcing and CQRSNext on the path โ†’๐Ÿ’Œ Vector clocks and ordering events