Event-Driven Architecture: Events, Commands, and Patterns
Learn event-driven architecture fundamentals: event sourcing, CQRS, event correlation, choreography vs orchestration, and implementation patterns.
Event-driven architecture lets services publish facts that independent consumers can process, but reliable delivery takes more than adding a broker. This guide compares event sourcing, CQRS, choreography, orchestration, and batch replay, then explains scoped delivery guarantees, ordering, schema evolution, idempotency, and the outbox pattern. Use its failure scenarios and deployment checklist to decide where asynchronous messaging fits and what your team must operate.
Event-driven architecture: events, commands, and patterns
Introduction
An order service can save an order successfully, then crash before publishing OrderPlaced. Inventory and shipping never hear about the order, even though the customer sees a success message. An event-driven design records the business change and publishes a durable event so independent consumers can react; an outbox can close the gap between the database write and publication.
This guide covers event sourcing, CQRS, messaging guarantees, workflow coordination, schema evolution, and the operational work behind those choices. The examples are illustrative pseudocode where broker APIs or language syntax are simplified.
Architecture decisions
Commands and events
A command asks a specific receiver to do something, such as ReserveInventory. An event records a fact that has already happened, such as InventoryReserved. Use request-response when the caller needs an immediate result or must know whether a request was accepted. Publish an event when independent consumers need to react to a completed change without making the producer call each one directly.
This is a boundary choice, not a rule that every service should use a broker. An event producer still owns a stable contract, and consumers still need retry and duplicate handling.
Choreography and orchestration
In choreography, services react to events and publish the next facts in a workflow. It keeps each step local, but the overall process can be hard to trace as conditions and compensations accumulate.
In orchestration, a workflow coordinator tracks progress and decides which step runs next. That makes branching, timeouts, and compensation easier to see, at the cost of a component that owns workflow state. Choose based on how much coordination the business process needs; see Saga Pattern for implementation choices.
Event sourcing and CQRS
Event-driven architecture does not require event sourcing. A broker can distribute integration events while each service keeps its own current state. Event sourcing instead stores domain changes as an ordered stream and rebuilds state from that history. CQRS separates write and read models; a system can use CQRS without storing an event history. See Event Sourcing and CQRS Pattern for those distinct patterns.
Operational costs
An event broker moves work out of the request path, but the result arrives later. Teams need to operate broker capacity, topic or queue permissions, schema compatibility, retries, dead-letter handling, replay, retention, and consumer lag. Partition keys and consumer capacity set the useful parallelism; a hot key or slow consumer can still build a backlog.
Estimate the cost of retained data and replay before treating an event stream as an audit record or recovery mechanism. If a user action must return a definitive answer, keep a synchronous path for that decision and publish an event for downstream work.
| Factor | Event-driven | Request-response | Decision point |
|---|---|---|---|
| Coupling | Producers publish to a broker; consumers depend on event contracts | Caller depends on a service endpoint and response contract | Choose async when consumers should evolve independently and can tolerate delay. |
| Response time | Producer can return after accepting work; downstream completion is later | Caller can receive an immediate result | Keep a synchronous check for actions that need an immediate decision. |
| Consistency | Consumers and projections can lag behind the source | A response can report the result of the current request | Define how clients handle stale reads, retries, and reconciliation. |
| Scale | Parallelism depends on partitions, keys, and consumer capacity | Capacity depends on caller and service instances | Benchmark actual workload; a hot key or slow consumer can limit throughput. |
| Failure handling | Requires retries, dead-letter handling, replay controls, and lag alerts | Failures surface in the request path and need timeout/retry policy | Choose based on the recovery path the team can operate. |
| Operations | Broker, schemas, access, retention, backups, and replay need owners | Fewer messaging components, but services must meet availability targets | Include staff time and data lifecycle in the cost. |
When to use / when not to use
Use EDA when
- Several independent consumers need to react to the same completed business fact.
- The producer can accept work before every consumer finishes, and the workflow can tolerate eventual consistency.
- The team can own the broker, event contracts, retries, replay permissions, retention, and consumer health.
- Consumers benefit from a durable handoff or from processing events at different rates.
If compliance requires a historical record, define which facts must be published, who can access them, and how long they are retained. A broker stream is not automatically a complete audit log; Event Sourcing is a separate choice for domains that need their event history as the source of truth.
Choose another approach when
- The caller needs an immediate success or rejection before it can continue.
- The workflow is simple and a direct call is easier to understand and operate.
- The team cannot support broker outages, lag, schema changes, replay, and dead-letter handling.
- A batch process is a better fit for the workload than continuous event delivery.
Delivery, ordering, and processing scope
Delivery guarantees depend on broker configuration and failure assumptions. At-least-once delivery can repeat a message; consumers should be idempotent. Kafka transactions can coordinate output records and consumed offsets within Kafka, while an external database or API needs its own coordination. See Exactly-Once Delivery and Exactly-Once Semantics in Stream Processing for the guarantees and boundaries.
Ordering is scoped too. Kafka preserves order within a partition. Key related records consistently when per-entity order matters; cross-partition order requires coordination or a single partition, which limits parallelism. A timestamp describes when an event occurred, not a global sequence.
Coordinate multi-service workflows
Use choreography for a small flow of independent reactions. Use orchestration when the workflow has branching, deadlines, or compensating actions that need a visible owner. A saga records progress and handles failures across local transactions; it does not turn those transactions into one global database transaction. See Saga Pattern.
Keep event contracts explicit
An event reports a fact and should have a stable type, source, identifier, and documented payload. Use a schema registry when multiple producers and consumers need compatibility checks. Decide whether metadata belongs in a standard envelope or application extension; see Event Envelopes and Metadata.
Publish reliably and make retries safe
When a database change and its event must agree, write the event to an outbox in the same database transaction and relay it later. A relay may publish again after a crash, so consumers still need idempotency. The Outbox Pattern covers the implementation.
Choose payload size deliberately. A notification carries an identifier and asks consumers to fetch details; event-carried state avoids that callback but stores more data in every copy. Include only fields consumers need and apply the same privacy and retention rules to retries, dead-letter streams, and replay archives.
Operate consumers under load
Monitor consumer lag and bound retries and buffers. Scale consumers only where partitioning and downstream capacity allow it; throttling or pausing producers may be safer than building an unbounded backlog. See Backpressure Handling and Dead-Letter Queues for operational patterns.
Production failure scenarios
| Failure | Impact | Mitigation |
|---|---|---|
| Event broker failure | Events not published or consumed | Use broker clustering with replication; implement outbox pattern |
| Consumer crash mid-processing | Events may be lost or reprocessed | Use acknowledgment after successful processing; idempotent consumers |
| Out-of-order event delivery | State becomes inconsistent | Key related records to the same partition, validate per-entity sequence, and define conflict handling |
| Event schema version mismatch | Consumers cannot deserialize events | Implement schema versioning; use upcasters or schema registry |
| Poison event blocking consumer | Consumer stops processing | Configure dead letter queues; implement retry limits |
| Cascading failures | One service failure triggers failures in others | Implement circuit breakers; design for partial availability |
| Event replay overload | New consumer overwhelms system with replays | Throttle replay rate; process in batches with backpressure |
| Correlation ID loss | Cannot trace transactions across services | Propagate correlation IDs through all events; log correlation |
Two recovery details are easy to miss in a design review. An outbox relay can publish a record successfully and crash before recording that it sent it; after restart, it publishes the same event again. Treat that as expected at-least-once delivery: preserve the event ID across attempts and make the consumer’s deduplication record atomic with its state change. Also, a dead-letter replay can put an old event behind newer events for the same entity. Before redriving, check whether the consumer depends on per-entity order; pause or isolate that key if necessary, then compare the repaired state with the event history.
Security and compliance notes
Treat each event copy as data with its own access and retention rules. Limit producer and consumer permissions, keep sensitive fields out of payloads and logs, and include retry queues, dead-letter topics, archives, backups, and downstream stores in deletion plans. See Event Security and Sensitive Data for a Kafka ACL example and lifecycle guidance, Event Envelopes and Metadata for event fields, and Dead-Letter Queues for controlled redrive.
Observability checklist
Track producer acknowledgments, consumer lag, processing latency, retry counts, and dead-letter depth by topic, partition, and consumer group. Carry event IDs and correlation or trace context across the asynchronous boundary. Log processing outcomes and identifiers, not full payloads or credentials. See Distributed Tracing, Backpressure Handling, and Dead-Letter Queues for focused operational guidance.
Common pitfalls / anti-patterns
- Using events as queries: If the caller needs an immediate answer, use request-response. For asynchronous work, put only the required data in the event instead of waiting for a reply event.
- Confusing EDA with event sourcing or CQRS: A broker can distribute integration events while services store current state. Add an event store or separate read models only when the domain needs them.
- Treating broker delivery as exactly-once everywhere: Name the input, output, and systems inside the transaction boundary. Make repeated effects safe; see Exactly-Once Delivery.
- Assuming global ordering: Order is scoped to a broker partition or queue group. Key related events consistently and coordinate dependencies across partitions.
- Leaving workflow logic implicit: A short chain may suit choreography. Branches, deadlines, and compensation can need a saga coordinator.
- Keeping retries unbounded: Define retry limits, a dead-letter path, and a controlled replay procedure before launch.
Quick recap checklist
- Name commands as requests and events as facts that already happened.
- Choose event-driven communication when independent consumers need to react; keep synchronous calls for workflows that need an immediate answer.
- Give events stable IDs, schema versions, and correlation IDs so consumers can deduplicate messages and traces can cross service boundaries.
- Make consumers idempotent, and define retry, dead-letter, and replay procedures before production.
- Use an outbox when a database update and event publication must stay in sync.
- Add event sourcing or CQRS only when audit history, replay, or distinct read models justify the extra operational work.
Pre-deployment checklist
- Event schemas and compatibility rules are documented.
- Producer and consumer identities have scoped permissions.
- Retry limits, dead-letter handling, and replay ownership are defined.
- Consumers tolerate redelivery; outbox publication is monitored where used.
- Retention, backups, and deletion paths include downstream copies.
- Consumer lag, broker health, and publish acknowledgments have alerts.
- Workflow compensation and read-model recovery have been exercised.
Interview questions
Publish a fact when independent consumers can act later and the producer does not need their immediate results. Use request-response when the caller must make a decision from the response.
A command asks one owner to perform an action. An event records a fact that already happened and may have several consumers.
No. Services can publish integration events while storing current state. Event sourcing uses a retained domain stream as its source of truth; CQRS separates read and write models. See Event Sourcing and CQRS Pattern.
As branches, timeouts, and compensating actions grow, it can become hard to see who owns the workflow. A saga coordinator can make progress and recovery steps explicit. See Saga Pattern.
It means one visible result within a named boundary, not one physical read. State the inputs, outputs, transaction, and failure assumptions. A Kafka transaction does not include an unrelated database or API.
Scope order to the broker and key: Kafka orders records within a partition, while SQS FIFO orders within a message group. Cross-partition dependencies need coordination. Event time is not a sequence number.
It commits the business change and an outbox row in one database transaction. A relay publishes later and may retry, so consumers still need idempotency. See Outbox Pattern.
Use a stable identity, source, type, and documented context. Keep domain facts in the payload; define application extension fields explicitly. See Event Envelopes and Metadata.
Bound retries, isolate poison messages, alert on lag and dead-letter depth, then define who can inspect or replay the message. See Dead-Letter Queues.
Plan for broker and schema operations, access control, retention, backups, retries, dead-letter handling, replay, and consumer lag. Check that the team can run the recovery path before moving work out of a request.
Further reading
- Apache Kafka: its durable log, replay capability, and consumer groups suit many EDA workloads
- Pub/Sub Patterns: pub/sub patterns that complement event-driven architecture
- Message Queue Types: messaging infrastructure for event-driven systems
- CloudEvents specification and project: a common event format and its context attributes
- Apache Kafka documentation: topics, partitions, producers, and consumers
Conclusion
Event-driven architecture lets services publish facts without knowing which consumers will act on them. Events, idempotent handlers, schema evolution, and correlation IDs make that model workable; an outbox protects publication from database failures. Use event sourcing and CQRS when their replay or read-model benefits solve a real domain problem, since both add operational complexity.
Category
Related Posts
Event Sourcing: Projections, Replay, and Recovery
An operations guide to event streams, idempotent projections, schema changes, snapshots, lag, and safe read-model rebuilds.
GraphQL Federation: Subgraphs, Routing, and Trade-offs
Learn how GraphQL federation composes subgraphs, routes operations, and affects service ownership, query planning, latency, failure handling, and authorization.
CQRS Pattern
Decide whether separate command and query models solve a real problem, how to begin in one store, and when a read model can tolerate lag.