Distributed Systems Reference/Distributed Transactions

Sagas & Transactional Outbox

Choreography vs orchestration sagas, compensating transactions, and outbox pattern for reliable publish-after-write across DB and message broker.

4/5Overview: 30m

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

StyleHowTrade-off
ChoreographyEach service listens and emits eventsDecoupled, hard to trace
OrchestrationCentral saga coordinator drives stepsClear 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

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 placement

    Order service, payment service, inventory service. Write choreography steps and compensating actions for payment failure after inventory reserved. 6–8 bullets.

    20m