Multi-Step Distributed Workflows (Saga & Outbox Pattern)
Multi-Step Distributed Workflows (Saga & Outbox Pattern)
In a microservices architecture, business workflows span multiple independent services (e.g. Order Service, Payment Service, Inventory Service). Because distributed Two-Phase Commit (2PC) does not scale well over networks, modern systems use the Saga Pattern.
1. The Saga Pattern
A Saga is a sequence of local transactions where each step updates a local database and emits a message. If a step fails, the Saga executes Compensating Transactions to undo prior steps:
Step 1: Reserve Inventory (Success)
Step 2: Debit Customer Card (Failed - Insufficient Funds!)
Compensation Step 1: Release Reserved InventoryOrchestration vs. Choreography
- Choreography (Event-Driven): Services listen to Kafka events and publish completion events. Simple for short workflows, but difficult to monitor and debug as topologies grow.
- Orchestration (Centralized Coordinator): A dedicated workflow engine (Temporal, AWS Step Functions) centrally commands each participant what step to execute next and handles timeouts.
2. The Transactional Outbox Pattern
How do you guarantee that a database update and a Kafka message emission both succeed without dual-write failures?
- Write the business data AND the outbound event into an
outboxtable within the same local ACID database transaction. - A background Debezium (Change Data Capture) or Polling process reads the outbox table and streams the events to Kafka with at-least-once delivery.
Key Architecture Trade-Offs & Decision Matrix
| Decision Factor | Choice A | Choice B | Selected Architectural Rationale |
|---|---|---|---|
| Communication Protocol | REST over HTTP/2 | WebSockets / gRPC | Use REST for stateless CRUD APIs; use WebSockets for low-latency bidirectional streaming. |
| State Management | Centralized Distributed Store | Local Memory with Sticky Sessions | Centralized Redis / Database state allows seamless container auto-scaling and zero-downtime rolling deploys. |
| Concurrency Control | Optimistic Locking (version column) | Pessimistic Locking (SELECT FOR UPDATE) | Optimistic locking delivers superior throughput for low-conflict consumer operations. |
Related Topics
Expand your knowledge by learning about adjacent concepts in system design.
Consistent Hashing Architecture & Implementation
Deep dive into consistent hashing algorithms, virtual nodes, token rings, and minimal key remapping during cluster resizing in distributed databases.
Event-Driven Architecture & Scaling with Apache Kafka
Design resilient, event-driven distributed architectures using Apache Kafka: topic partitioning, consumer group rebalancing, idempotence, and exactly-once semantics.
Networking Essentials
Learn the important parts of networking that you'll need to know for your system design interviews
Cheat Sheet Utility
View and print a concise system design reference card.