ayushsalampuriya.xyzRevise

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

  1. Book flight — Flight service reserves seat
  2. Book hotel — Hotel service reserves room
  3. Charge card — Payment service captures payment

If step 3 fails → compensate: cancel hotel, cancel flight (async refund events).

4. Choreography vs orchestration

ChoreographyOrchestration
Services react to events (no central brain)Central saga orchestrator drives steps
Loose coupling; harder to visualize flowClear state machine; single place for logic
Good for simple flowsGood 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:

Compensations must be idempotent — safe to retry.

6. Isolation challenges

Between saga steps, other users see intermediate state (hotel booked but not paid). Mitigations:

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.