HLD · Transactions
Saga Pattern & Distributed Transactions
Coordinate multi-service workflows without a single global 2PC lock.
1. Why not 2PC (two-phase commit)?
Classic 2PC: coordinator locks all participants until all agree commit/abort. Blocks on failures; poor availability; not suited for microservices across unreliable networks.
Interview: "We use sagas for long-running business processes across services."
2. What is a saga?
A sequence of local transactions. Each step commits in its own service. If a step fails, run compensating transactions to undo prior steps.
3. Example: travel booking
- Book flight — Flight service reserves seat
- Book hotel — Hotel service reserves room
- Charge card — Payment service captures payment
If step 3 fails → compensate: cancel hotel, cancel flight (async refund events).
4. Choreography vs orchestration
| Choreography | Orchestration |
|---|---|
| Services react to events (no central brain) | Central saga orchestrator drives steps |
| Loose coupling; harder to visualize flow | Clear state machine; single place for logic |
| Good for simple flows | Good for complex sagas (Temporal, Camunda) |
Choreography example: OrderCreated event → Payment listens → PaymentFailed event → Inventory listens and releases stock.
5. Compensating transactions
Not always literal undo — semantic reverse:
- Reserve seat → release seat
- Charge $50 → refund $50 (idempotent refund_id)
- Send email → send cancellation email (can't unsend)
Compensations must be idempotent — safe to retry.
6. Isolation challenges
Between saga steps, other users see intermediate state (hotel booked but not paid). Mitigations:
- Pending state: Mark booking "PENDING_PAYMENT"
- Semantic lock: Hold inventory with TTL until payment completes
7. Outbox pattern (reliable events)
DB write + event publish atomically: write business row and outbox row in same transaction; separate poller publishes to Kafka.
Prevents "order saved but event lost" race.
8. Tools
Temporal, AWS Step Functions, Cadence — durable workflow engines with retries, timers, compensation handlers.
Quick revision
- Saga: Local TX steps + compensations on failure.
- Not 2PC: Better availability; eventual consistency across services.
- Choreography = events; Orchestration = central coordinator.
- Compensations must be idempotent.
- Outbox for reliable event publishing with DB write.