Course contentsShow
← Cloud and Infrastructure
Lesson 2738 of 2,98959. Queueing and Async PatternsFree lesson

Event-Driven State Machines

Model complex business processes as state machines that react to events and emit new events on transitions.

Event-Driven State Machines

What you'll learn: How to model complex business processes as state machines that react to events and emit new events on transitions.

The Core Idea

An event-driven state machine combines two powerful patterns: it uses a state machine (a model with defined states and transitions) and makes it event-driven (transitions happen in response to events, and transitions themselves emit new events). This approach excels at modeling long-running business processes where each step depends on external events and triggers downstream actions.

Think of an order fulfillment process: the order moves through states like PENDING → PAYMENT_PROCESSING → PREPARING → SHIPPED → DELIVERED. Each transition happens when an event arrives (PaymentConfirmed, ItemsPicked, etc.), and each transition emits new events that other systems consume (OrderShipped might trigger email notifications and inventory updates).

Why This Matters

Traditional workflow systems often use orchestration—a central coordinator that calls services directly. Event-driven state machines use choreography: the state machine reacts to events and publishes new ones, allowing loose coupling. Services don't need to know about each other; they just respond to events.

This pattern builds on concepts you know: event sourcing stores all state changes as events, CQRS separates reads from writes, saga patterns handle distributed transactions, and event replay lets you rebuild state or fix errors.

The Flow

  1. State machine receives an event
  2. Validates the transition is allowed from current state
  3. Executes transition logic (possibly using compensating transactions if needed)
  4. Updates state
  5. Emits one or more new events (using outbox pattern for reliability)
  6. Other systems react to those events, potentially triggering further transitions

Key Takeaway: Event-driven state machines model complex processes as states and transitions triggered by events, enabling loosely-coupled, auditable, and recoverable business workflows in distributed systems.