Distributed Transactions
TL;DR
Problem: Atomic operations across multiple services/databases. 2PC (Two-Phase Commit): Coordinator ensures all-or-nothing (slow, blocking). Saga: Choreographed compensation (eventual consistency). Outbox pattern: Reliable events without dual writes.
Patterns
1. Two-Phase Commit (2PC)
Pros: Strong consistency (ACID)
Cons: Slow (multiple round trips), blocking (coordinator failure halts system)
Rarely used in microservices (too rigid).
2. Saga Pattern
Long-running transaction with compensating actions.
Example (Order workflow):
1. Reserve inventory → compensate: Release inventory
2. Charge payment → compensate: Refund payment
3. Ship order → compensate: Cancel shipment
If payment fails: Compensate by releasing inventory.
Pros: Eventual consistency, resilient
Cons: Complex (need compensating logic), no isolation
3. Outbox Pattern
Problem: Dual writes (write to DB + send event) - can fail between steps.
Solution: Write to database and outbox table in same transaction.
Benefits: Guaranteed event delivery (transactional).
For deep dive: See your existing Event Sourcing - Outbox Pattern
Common Interview Questions
Q1: "How do you handle transactions across microservices?"
Answer:
- Avoid if possible: Design services to avoid distributed transactions
- Saga pattern: Compensating transactions (eventual consistency)
- Outbox pattern: Reliable event publishing
- Not 2PC: Too slow and fragile for microservices
Q2: "What is the saga pattern?"
Answer:
- Long-running transaction split into local transactions
- Each step has compensating action (undo)
- If step fails, run compensations in reverse
- Example: Order (reserve → pay → ship), if pay fails, release reservation
Q3: "Explain the outbox pattern."
Answer:
- Problem: Dual writes (DB + event) can fail inconsistently
- Solution: Write to DB and outbox table atomically
- Background worker publishes events from outbox
- Benefit: Guaranteed event delivery
Quick Reference
2PC: Strong consistency (slow, blocking)
Saga: Compensating transactions (eventual)
Outbox: Reliable events (transactional)
Prefer: Saga + Outbox for microservices
Next: Rate Limiting & Throttling.