Saga pattern
A saga is a sequence of local transactions, each with a compensating action if a later step fails.
T1: Reserve inventory → C1: Release reservation
T2: Charge payment → C2: Refund
T3: Confirm order → (no compensate / mark cancelled)
If T2 fails, run C1. No global lock across services.
Choreography vs orchestration
| Style | How | Trade-off |
|---|---|---|
| Choreography | Each service listens and emits events | Decoupled, hard to trace |
| Orchestration | Central saga coordinator drives steps | Clear flow, coordinator is critical component |
Both appear in interviews — pick based on complexity and observability needs.
Compensating transactions
Not always true "undo" — may be business action (issue credit, send apology email). Must be idempotent — saga retries are normal.
Transactional outbox
Problem: DB commit succeeds, message publish crashes → downstream never notified.
Outbox: In same local DB transaction, insert business row + outbox event row. Separate relay (polling or CDC/Debezium) publishes to Kafka and marks sent.
Guarantees at-least-once publish aligned with DB write — foundation for reliable cross-service propagation.
BEGIN;
INSERT INTO orders ...;
INSERT INTO outbox (event_type, payload) ...;
COMMIT;
-- relay reads outbox → publishes to Kafka
Pairs with Topic 8 delivery semantics.
vs 2PC
Sagas accept temporary inconsistency between steps; 2PC seeks atomic all-or-nothing. Sagas scale better across autonomous services.
Not covered
REST API design, generic idempotency keys on HTTP — only distributed atomicity patterns here.
Further Reading
- DDIA — Ch. 9: §9.5.3 distributed transactions in practice; Ch. 11: §11.4 stream processing and exactly-once (outbox connection)Book25m
- Chris Richardson — Pattern: Saga (microservices.io)Article20m
- Debezium blog — Reliable Microservices Data Exchange With the Outbox Pattern (practical outbox + CDC)Article20m
Hands-On Tasks (Optional)
Low-setup exercises — browser visualizers, paper drills, or optional Docker. No autograding; the goal is interview fluency.
- Sketch a saga for order placement20m
Order service, payment service, inventory service. Write choreography steps and compensating actions for payment failure after inventory reserved. 6–8 bullets.