FullStack AI Hub
Studio
System Design · 06. Architecture
12 min
10 steps
Intermediate

Event-Driven Systems

Coordinate cross-service workflows reliably without distributed 2PC locks using Transactional Outbox, Choreography vs Orchestration, Compensating Sagas, and Idempotent Consumers.

System Design06. ArchitectureLesson 3 of 4
12 minIntermediate10 steps

Event-Driven Systems

Coordinate cross-service workflows reliably without distributed 2PC locks using Transactional Outbox, Choreography vs Orchestration, Compensating Sagas, and Idempotent Consumers.

LOCK DURATION
420 ms
ON COORD CRASH
All Blocked
THROUGHPUT
Low
AVAILABILITY
Fragile
2PC PARTICIPANTS (LOCKED) · Blocked on CoordinatorLOCK 1LOCK 2LOCK 3Checkout2PCCoordinator76%Blocking SPOFOrders DB72%Row LockedPayments DB74%Row LockedInventory DB70%Row Locked
command / workflow step
local ACID TX + outbox
confirmed / compensated
domain event stream
step failure / rollback
In This LessonStep 1 of 10
What You Will Master
  • ✓Eliminate dual-write event loss by combining state changes and Outbox events inside one local ACID transaction
  • ✓Compare Event Choreography vs Saga Orchestration for multi-service checkout workflows without 2PC locks
  • ✓Undo partial distributed commits cleanly using compensating transactions (refund, release stock) on failure
  • ✓Defend consumers against duplicate deliveries, out-of-order events, and poison pills using Inbox deduplication and DLQs

Architectural Trade-Off Comparison Matrix

PatternBest ForKey Trade-Off
Transactional Outbox + CDCGuaranteeing that every committed SQL row publishes its domain event to Kafka with zero dual-write lossRequires a CDC relay (Debezium) and idempotent consumers for at-least-once delivery
Event ChoreographySimple 2–3 service flows where services react autonomously to domain events without a central bossHard to trace or debug once 6+ services form implicit event cycles ("pinball architecture")
Saga Orchestrator (Temporal / Step Functions)Complex multi-step workflows (Order → Pay → Reserve → Ship) needing explicit state & compensating rollbacksAdds a durable workflow engine to run, though it keeps domain services simple
Idempotent Inbox + DLQSafely absorbing Kafka/SQS redeliveries and isolating malformed poison messages without stalling partitionsStores `processed_event_id` keys for the deduplication window and needs DLQ replay ops

Step-by-Step Architectural Breakdown (10 Steps)

Full architectural walkthrough transcript and state transitions for Event-Driven Systems.

STEP 01 · PROBLEMJump to step →

Why distributed Two-Phase Commit (2PC) stalls microservices

In a monolith, updating `Orders`, `Payments`, and `Inventory` runs inside one local SQL transaction. Across 3 microservices with private databases, trying to coordinate a distributed **Two-Phase Commit (2PC)** holds row locks open across the network.

If the coordinator crashes between `PREPARE` and `COMMIT`, all 3 databases stay **frozen in limbo** holding locks until manual recovery!

watch:2PC is a blocking protocol: one slow participant or crashed coordinator locks rows across every participating microservice.

Two-Phase Commit (2PC)Blocking Distributed LocksWhy Sagas Exist
STEP 02 · PROBLEMJump to step →

The Dual-Write Hazard: DB commits, then Kafka publish crashes

Switching to events looks simple: `db.save(order)` followed by `kafka.publish(OrderCreated)`. What could go wrong?

If the container crashes, OOMs, or hits a network blip **in the 2 ms between DB commit and Kafka publish**, the customer is charged—**but Warehouse never receives the event** and the order vanishes forever!

watch:Writing to two separate systems (SQL + Kafka) without coordination ALWAYS drifts under real crashes—never trust naive dual writes.

Dual-Write ProblemLost Domain EventsGhost Orders
STEP 03 · SOLUTIONJump to step →

Solve dual writes with Transactional Outbox + CDC

Write the `Order` row **and** an `outbox_events` row inside **one single local SQL transaction**. Both commit atomically or both roll back together—zero dual-write gap!

A lightweight **CDC Relay (`Debezium`)** tails the database Write-Ahead Log and publishes every committed outbox row reliably into **Kafka**.

good:Log-tailing CDC (Debezium) reads Postgres WAL directly in milliseconds without hammering your primary tables with `SELECT * FROM outbox` polling.

Transactional OutboxChange Data Capture (Debezium)At-Least-Once Publishing
STEP 04 · TECHNIQUEJump to step →

Saga style #1: Event Choreography (autonomous services)

In **Choreography**, there is no central boss: `Orders` emits `OrderCreated` → `Payments` hears it and emits `PaymentCaptured` → `Inventory` hears it and emits `StockReserved` → `Shipping` dispatches.

Choreography shines for **2–3 loosely coupled services**—you can plug in a new `Loyalty Points` subscriber without modifying `Orders` at all.

idea:Choreography is wonderfully decoupled for simple flows—but watch out once 6+ services chain events together, where workflow state becomes hard to track.

Event ChoreographyLoose CouplingLocal Saga Transactions
STEP 05 · SOLUTIONJump to step →

Saga style #2: Saga Orchestrator for complex workflows

When checkout spans 5+ steps (`Reserve Stock → Charge Card → Create Label → Notify`) with timeouts and retries, Choreography turns into unreadable "pinball architecture."

A durable **Saga Orchestrator** (`Temporal`, `AWS Step Functions`) tracks the exact state machine in one place—issuing explicit commands to aligned workers and recording every completed step in a durable workflow log.

good:Orchestration makes complex workflows visible, auditable, and easy to evolve without chasing events across 8 repositories.

Saga OrchestrationDurable Workflow LogCentralized State Visibility
STEP 06 · SOLUTIONJump to step →

Handle failure: semantic Compensating Transactions

In a Saga, Step 1 (`Inventory.reserve`) and Step 2 (`Payments.charge`) already committed locally—you cannot issue `SQL ROLLBACK` later if Step 3 (`Shipping`) fails!

Instead, the Orchestrator runs backward **Compensating Transactions** (`Payments.refund()` → `Inventory.release()`) until every prior side effect is semantically undone.

idea:Every forward step before the "pivot transaction" must have an idempotent compensating action that retries until it succeeds.

Compensating TransactionsPivot TransactionSemantic Rollback
STEP 07 · TECHNIQUEJump to step →

Idempotent Consumers: survive duplicate event deliveries

Outbox + Kafka guarantees **at-least-once** delivery—meaning network retries WILL deliver `PaymentCapture(event_id=771)` twice. Without deduplication, a consumer double-credits loyalty points or ships two boxes!

Use the **Transactional Inbox** pattern: insert `event_id` into a `processed_events` table inside the same local transaction as your business write. Duplicates hit `UNIQUE(event_id)` and become harmless no-ops.

good:At-least-once broker delivery + Idempotent Inbox consumer = effectively-once business outcomes.

Transactional InboxIdempotent ConsumerEffectively-Once Processing
STEP 08 · TECHNIQUEJump to step →

Handle out-of-order events & poison pills with keys + DLQs

Two subtle event bugs: first, if `OrderCancelled` overtakes `OrderCreated` on separate partitions, state corrupts—fix by **partitioning by `order_id`** and comparing monotonic `event_version`.

Second, a malformed "poison pill" event will crash a consumer in an infinite retry loop—route failures after 3 retries into a **Dead-Letter Queue (DLQ)** so healthy orders keep flowing!

watch:Never let 1 malformed JSON payload freeze a Kafka partition serving 10,000 healthy orders/min—cap retries and divert to a monitored DLQ.

Partition Key OrderingVersion GuardsDead-Letter Queue (DLQ)
STEP 09 · TRADE-OFFJump to step →

Evolve event schemas safely with a Schema Registry

Renaming `price` to `amount_cents` in `OrderCreated` without coordination silently breaks 5 downstream consumers overnight.

Enforce backward-compatible Avro or Protobuf contracts via a **Schema Registry**: producers may only **add optional fields**, never rename or change existing field types—checked automatically in CI.

idea:Backward compatibility lets new producers and old consumers coexist smoothly during rolling deployments.

Schema RegistryBackward CompatibilityContract Testing
STEP 10 · RECAPJump to step →

Production Event-Driven & Saga Blueprint end-to-end

Reliable event-driven architectures combine five interlocking pieces: **Transactional Outbox + Debezium CDC** (zero lost events), **Schema Registry** (safe evolution), **Saga Orchestrator** with **Compensating Rollbacks** (no 2PC locks), and **Idempotent Inbox + DLQ** on every consumer.

good:Event-Driven Mastery: Outbox + CDC → Schema Registry → Orchestrated Sagas + Compensations → Partition Ordering + Idempotent Inbox + DLQ.

Full Event-Driven StackSaga + Outbox + InboxZero Dual-Write Loss

Related Production Deep-Dives & Simulators

Included In Free Course
Free · Verifiable Credential

FS-102LLM Systems Foundations

Build a connected mental model from tokens through retrieval evaluation security and operations.

24 concepts~18h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.