Case Study 35 โ Saga Pattern for Distributed Transactions
Design distributed transaction orchestration using the Saga pattern for a flight + hotel + payment booking flow (or e-commerce checkout): multiple microservices, each with local ACID, no 2PC across services, with compensating transactions when steps fail.
1. Problem
A user books a trip:
- Reserve flight (FlightService)
- Reserve hotel (HotelService)
- Charge payment (PaymentService)
- Send confirmation (NotificationService)
Each service owns its database. A single XA/2PC transaction across four services is fragile (blocking locks, coordinator SPOF, poor availability). Instead, run a saga: a sequence of local transactions linked by events or an orchestrator; on failure, run compensations (semantic undo).
You must handle: partial failure, duplicate messages, ordering, timeouts, and compensation failures.
2. Requirements
Functional (MVP)
- Start saga on
BookTripcommand - Steps: reserve flight โ reserve hotel โ charge โ notify
- On step failure: compensate completed steps in reverse order
- Compensations: cancel flight, cancel hotel, refund payment
- Saga states: pending, running, compensating, completed, failed
- Query saga status by
sagaId - Idempotent step execution (safe retries)
- Support orchestration and document choreography alternative
Out of scope (initially)
- Cross-saga isolation (inventory oversell at global level โ use reservations + TTL)
- Long-running human approval steps (extend with timeouts)
- Visual workflow designer UI
- Exactly-once side effects without idempotent design (impossible โ design for at-least-once)
Non-functional
- End-to-end booking p99 < 3 s (happy path)
- Saga state durable โ survive orchestrator crash
- At-least-once message delivery with idempotent consumers
- Compensation must eventually complete or alert ops
- Audit trail of every step and compensation attempt
3. Back-of-the-envelope
These numbers are rough order-of-magnitude math โ not a booking platform SLA. In interviews, the goal is to show you know what to count and which resource breaks first. A useful shortcut: 1 QPS sustained โ 86,400 requests/day (86,400 seconds in a day). Sagas are low-QPS orchestration with high correctness requirements โ the surprise is message volume during failure paths, not happy-path throughput.
Why we estimate
A saga coordinates multiple microservices without 2PC. Estimates tell us:
- Whether the orchestrator or downstream services is the real bottleneck
- How much durable saga state and idempotency storage actually need
- Why compensation latency matters more than happy-path booking rate
Assumptions
| Assumption | Value | Why it matters |
|---|---|---|
| Bookings/day (peak season) | 50K | Drives saga creation rate |
| Steps per saga (happy path) | 4 | Flight โ hotel โ payment โ notify |
| Max steps (with compensations) | 10 | Failure path runs reverse compensations |
| Avg step latency | 200 ms | External service call + local DB |
| Failure rate | 5% of sagas | Trigger compensation chain |
| Message size | ~2 KB | Commands, replies, state updates |
| Services involved | 4 | Flight, Hotel, Payment, Notification |
Step A โ Traffic (QPS / throughput) with labeled arithmetic
Saga creation rate:
Bookings/day = 50,000
Avg booking rate = 50K รท 86,400
โ 0.6 sagas/second
Peak (ร10 for holiday rush):
โ 6 sagas/second
Happy-path message volume:
Messages per saga = 4 commands + 4 replies = 8 messages
Peak happy path = 8 ร 6 sagas/s โ 48 messages/second
Failure-path message volume (5% of sagas):
Failed sagas/s โ 6 ร 5% โ 0.3 sagas/s
Compensation msgs โ 3 compensate commands ร 0.3 โ 1 msg/s average
Worst-case burst (many simultaneous failures):
+15 compensate messages/second additional
End-to-end latency (happy path):
4 steps ร 200 ms โ 800 ms sequential minimum
+ orchestrator overhead + network โ target p99 < 3 s
Step B โ Storage
Saga state (durable โ must survive orchestrator crash):
Sagas/day = 50,000
Retention = 30 days
Bytes per saga โ 2 KB (state, step history, timestamps)
Monthly storage = 50K/day ร 30 days ร 2 KB โ 3 GB/month
โ Tiny โ saga state is not a storage problem
Outbox + inbox dedup (idempotency keys):
Step keys ร 7-day retention โ small Redis/DB table
Each service stores processed messageId to reject duplicates
โ At 6 sagas/s peak, this is thousands of keys, not millions
Step C โ Bandwidth / other
Orchestrator โ service messaging:
Peak ~48 msg/s ร 2 KB โ 96 KB/s
Bandwidth is irrelevant โ latency and reliability dominate
Compensation SLA:
99% compensations complete within 5 minutes
Stuck compensations โ manual ops queue + alert
Compensation failure is worse than initial failure โ user may be double-charged
Transactional outbox:
Each service write + outbox insert in same local DB transaction
Separate relay process publishes to message bus
โ Guarantees at-least-once delivery without 2PC across services
Step D โ Ratios and capacity table
| Metric | Average | Peak | Notes |
|---|---|---|---|
| Saga starts/s | ~0.6/s | ~6/s | Low QPS โ correctness over throughput |
| Happy-path msgs/s | ~5/s | ~48/s | 8 messages per saga |
| Failure-path msgs/s | ~0.3/s | ~15/s | 5% failure + compensation burst |
| Saga state/month | ~3 GB | โ | Durable orchestrator DB |
| End-to-end p99 | โ | < 3 s | 4 ร 200 ms sequential steps |
| Compensation SLA | โ | 99% in 5 min | Manual queue for stuck |
What the numbers tell us
- ~0.6 sagas/s average, ~6/s peak is tiny โ orchestrator is not a throughput bottleneck; state durability and idempotency are
- 3 GB/month saga state โ store full audit trail; replay from any step on orchestrator crash
- 5% failure rate doubles message complexity โ compensations run in reverse order; each must be idempotent
- 800 ms minimum happy path โ parallelize independent steps where possible; timeout + compensate on slow services
- At-least-once delivery is inevitable โ design every forward action and compensation with business-level idempotency keys
- Transactional outbox โ never publish to bus before local DB commit
Common mistake for this problem
Proposing 2PC / XA transactions across microservices โ blocking locks, coordinator SPOF, poor availability under partition. Interviewers want the Saga pattern: local ACID per service + orchestrator state machine + compensating transactions. Another mistake: ignoring compensation failures โ "cancel flight" may fail if the flight already departed; you need retry, manual intervention, and alerting, not infinite automatic retry.
4. High-Level Design (HLD)
Orchestration (central coordinator)
Choreography (decentralized โ comparison)
No central orchestrator โ each service subscribes to events and publishes next step or compensation. Harder to visualize global state; good for simple flows.
Components
| Component | Role |
|---|---|
| Booking API | Starts saga; returns sagaId |
| Saga Orchestrator | State machine; sends commands; handles replies |
| Saga State DB | Durable saga instance, current step, history |
| Message Bus | Kafka/SQS โ at-least-once delivery |
| Transactional Outbox | Atomically persist saga update + outbound message |
| Flight/Hotel/Payment Services | Execute commands; emit success/failure events |
| Inbox / Idempotency store | Dedup processed (sagaId, step) per service |
| Compensation worker | Retry stuck compensations; escalate to ops |
| Admin API | Inspect saga timeline; manual retry |
Flows
Happy path (orchestration)
- API creates
sagaId, orchestrator writesRUNNING, stepRESERVE_FLIGHT - Outbox publishes
ReserveFlight - Flight service reserves, replies
FlightReserved - Orchestrator advances โ
RESERVE_HOTELโ โฆ โCHARGEโNOTIFYโCOMPLETED
Failure with compensation
- Payment returns
PaymentFailed - Orchestrator transitions to
COMPENSATING, stepCANCEL_HOTEL - After hotel cancelled โ
CANCEL_FLIGHT - If flight already ticketed,
CancelFlightmay fail โ retry with backoff; alert if non-compensatable
Orchestrator crash mid-saga
- New leader reads sagas in
RUNNING/COMPENSATING - Resend last command if no reply received (idempotent retry)
- Or wait for duplicate reply (idempotent orchestrator)
Trade-offs
- Orchestration vs choreography โ Orchestration: clear state, single place to debug; choreography: fewer coupling points, harder global view
- Sync HTTP vs async messaging โ Async + outbox survives crashes; sync simpler but brittle
- Semantic vs automatic compensation โ Refund is semantic undo, not DB rollback
- Saga vs 2PC โ Saga: availability + local TX; 2PC: strong atomicity, blocks on failure
- Parallel steps โ Reserve flight and hotel in parallel cuts latency; compensate both if either fails
5. Low-Level Design (LLD)
APIs
Booking API:
POST /api/v1/bookings
Body: {
"userId": "u_101",
"flightOfferId": "fo_88",
"hotelOfferId": "ho_42",
"paymentMethodId": "pm_7"
}
โ { "sagaId": "saga-99102", "status": "RUNNING" }
GET /api/v1/bookings/:sagaId
โ {
"sagaId": "saga-99102",
"status": "COMPENSATING",
"steps": [
{ "name": "RESERVE_FLIGHT", "status": "COMPLETED" },
{ "name": "RESERVE_HOTEL", "status": "COMPLETED" },
{ "name": "CHARGE_PAYMENT", "status": "FAILED", "error": "insufficient_funds" },
{ "name": "CANCEL_HOTEL", "status": "RUNNING" }
]
}
Orchestrator โ service commands (Kafka topics):
Topic: saga.commands.flight
{
"sagaId": "saga-99102",
"stepId": "RESERVE_FLIGHT",
"command": "ReserveFlight",
"payload": { "offerId": "fo_88", "userId": "u_101" },
"idempotencyKey": "saga-99102:RESERVE_FLIGHT"
}
Topic: saga.events.flight
{
"sagaId": "saga-99102",
"stepId": "RESERVE_FLIGHT",
"event": "FlightReserved",
"payload": { "reservationId": "fr_555" }
}
Compensation command:
{
"sagaId": "saga-99102",
"stepId": "COMPENSATE_HOTEL",
"command": "CancelHotel",
"payload": { "reservationId": "hr_777" },
"idempotencyKey": "saga-99102:COMPENSATE_HOTEL"
}
Schema
Saga orchestrator DB:
sagas (
saga_id UUID PRIMARY KEY,
user_id BIGINT NOT NULL,
status VARCHAR(16), -- RUNNING, COMPENSATING, COMPLETED, FAILED
current_step VARCHAR(32),
payload JSONB,
created_at TIMESTAMPTZ,
updated_at TIMESTAMPTZ
)
saga_steps (
saga_id UUID,
step_id VARCHAR(32),
status VARCHAR(16), -- PENDING, RUNNING, COMPLETED, FAILED, COMPENSATED
request_payload JSONB,
response_payload JSONB,
error_message TEXT,
attempt INT DEFAULT 0,
PRIMARY KEY (saga_id, step_id)
)
outbox (
id BIGSERIAL PRIMARY KEY,
saga_id UUID,
topic VARCHAR(128),
message JSONB,
published BOOLEAN DEFAULT FALSE,
created_at TIMESTAMPTZ
)
CREATE INDEX idx_outbox_unpublished ON outbox (published) WHERE published = FALSE;
Per-service inbox:
inbox (
idempotency_key VARCHAR(128) PRIMARY KEY,
saga_id UUID,
step_id VARCHAR(32),
processed_at TIMESTAMPTZ,
result JSONB
)
Service-local reservation tables:
flight_reservations (
reservation_id UUID PRIMARY KEY,
saga_id UUID UNIQUE,
offer_id VARCHAR,
status VARCHAR, -- HELD, CONFIRMED, CANCELLED
expires_at TIMESTAMPTZ
)
Modules
BookingController
SagaOrchestrator
SagaStateMachine
StepDefinitionRegistry
OutboxPublisher
InboxDeduper
CommandDispatcher
EventHandler
CompensationPlanner
SagaRecoveryJob
FlightCommandHandler / HotelCommandHandler / PaymentCommandHandler
Saga state machine definition
steps (forward):
1. RESERVE_FLIGHT
2. RESERVE_HOTEL
3. CHARGE_PAYMENT
4. SEND_NOTIFICATION
compensations (reverse order of completed forward steps):
CHARGE_PAYMENT โ RefundPayment
RESERVE_HOTEL โ CancelHotel
RESERVE_FLIGHT โ CancelFlight
transitions:
on step SUCCESS โ next forward step
on step FAILURE โ COMPENSATING โ first pending compensation
on compensation SUCCESS โ next compensation or FAILED (done)
on all forward done โ COMPLETED
Algorithm โ orchestrator start (with outbox)
function startSaga(userId, bookingRequest):
sagaId = uuid()
tx:
insert sagas(sagaId, status='RUNNING', current_step='RESERVE_FLIGHT', payload)
insert saga_steps(sagaId, 'RESERVE_FLIGHT', status='PENDING')
insert outbox(topic='saga.commands.flight', message=ReserveFlight(...))
commit tx
outboxRelay.pollAndPublish() // separate worker
return sagaId
Algorithm โ handle service event
function onEvent(event):
if not inbox.tryMarkProcessed(event.idempotencyKey):
return // duplicate
saga = repo.load(event.sagaId)
step = repo.step(event.sagaId, event.stepId)
if event.type.endsWith("Failed"):
step.status = 'FAILED'
saga.status = 'COMPENSATING'
next = compensationPlanner.firstPending(saga)
enqueueCompensation(next)
return
step.status = 'COMPLETED'
step.response = event.payload
nextForward = stateMachine.nextForward(saga)
if nextForward is null:
saga.status = 'COMPLETED'
else:
saga.current_step = nextForward
enqueueCommand(nextForward)
repo.save(saga, step)
Algorithm โ idempotent service handler (Flight)
function handleReserveFlight(cmd):
if inbox.exists(cmd.idempotencyKey):
return inbox.result(cmd.idempotencyKey)
tx:
existing = repo.findBySagaId(cmd.sagaId)
if existing:
result = FlightReserved(existing)
else:
resId = reserveInventory(cmd.offerId) // may fail if sold out
repo.insert(resId, cmd.sagaId, status='HELD')
result = FlightReserved(resId)
inbox.save(cmd.idempotencyKey, result)
commit tx
publishEvent(result)
return result
Algorithm โ compensation with retry
function enqueueCompensation(step):
cmd = buildCompensateCommand(step)
tx:
insert outbox(compensate topic, cmd)
update saga_steps set status='RUNNING' where step=step
commit tx
function compensationReaper():
stuck = repo.findCompensations(status='RUNNING', olderThan=5min)
for s in stuck:
if s.attempt >= MAX:
alertOps(s)
continue
s.attempt++
enqueueCompensation(s) // idempotent cancel
Algorithm โ parallel saga variant (flight + hotel)
function startParallelSaga(request):
saga.status = 'RUNNING'
enqueue RESERVE_FLIGHT and RESERVE_HOTEL concurrently
function onParallelEvent(event):
mark branch complete
if any branch FAILED:
enter COMPENSATING (cancel whichever completed)
if both COMPLETED:
enqueue CHARGE_PAYMENT
Use join pattern: orchestrator waits for both replies before payment โ reduces charge-then-cancel hotel-only failures.
Algorithm โ choreography alternative (PaymentFailed)
// PaymentService
function onChargeFailed(event):
publish HotelCancelRequested { sagaId, reservationId }
// HotelService
function onHotelCancelRequested(event):
cancel(event.reservationId)
publish HotelCancelled { sagaId }
// FlightService listens HotelCancelled or PaymentFailed
function onCompensate(event):
cancelFlight(event.sagaId)
publish FlightCancelled { sagaId }
// Booking read model subscribes to all events and builds status
Risk: ** cyclic dependencies** and missing compensations without central state โ mitigated by event catalog and correlation sagaId.
Concurrency & correctness
- No global lock โ each service transaction is local
- Idempotency key =
sagaId:stepIdon every command and event - Outbox pattern โ saga state and message publish atomic
- Compensation is not rollback โ cancel/reserve release may fail (already flown) โ manual saga
- Ordering โ partition Kafka by
sagaIdfor per-saga ordering - Exactly-once illusion = at-least-once + idempotent handlers + inbox
Failure modes
| Failure | Consequence | Mitigation |
|---|---|---|
| Payment succeeds, notify fails | User charged, no email | Retry notify; saga stays RUNNING on notify |
| Compensate hotel fails | Orphan hotel hold | Reaper retries; TTL on holds |
| Duplicate ReserveFlight | Double booking | UNIQUE(saga_id) in flight service |
| Orchestrator crash after charge | Unknown if charged | Query payment status on recovery; idempotent charge |
| Message reorder | Charge before hotel reserved | Partition by sagaId; state machine guards |
| Non-compensatable step | Partial completion | Manual intervention queue; legal workflow |
| Outbox relay stuck | Commands not sent | Monitor unpublished outbox; multi-worker relay |
6. Scale evolution
| Stage | Change |
|---|---|
| MVP | Orchestrator + Postgres outbox + Kafka; 4 services |
| Higher volume | Partition sagas; horizontal orchestrator (shard by sagaId) |
| Long workflows | Add timeouts, scheduled steps, human tasks (Temporal) |
| Observability | Saga timeline UI; distributed trace correlation on sagaId |
| Choreography hybrid | Orchestrator for booking; choreography for notifications |
| Strong inventory | Reservation TTL + pessimistic hold at Flight/Hotel separately |
7. Recap
- Saga = sequence of local transactions + compensations โ not distributed 2PC
- Orchestration centralizes the state machine; choreography decentralizes via events
- Transactional outbox + idempotent inbox make at-least-once safe
- Compensations are business undo (cancel, refund), not DB ROLLBACK
- Design forward and compensate pairs for every step; plan for stuck compensations
Practice: draw the orchestration sequence for a payment failure after flight and hotel succeed; write pseudocode for onEvent transitioning to COMPENSATING and enqueueing compensations in reverse order.