Event-Driven Architecture: Patterns & Pitfalls
An overview of event-driven architecture patterns including pub/sub, event sourcing, and the saga pattern — with Mermaid sequence diagrams.
Event-Driven Architecture: Patterns & Pitfalls
Event-Driven Architecture (EDA) is a software design pattern where the flow of the program is determined by events — significant changes in state that are published, detected, and consumed asynchronously.
Core Patterns
1. Pub/Sub (Publish–Subscribe)
Producers publish events to a topic; consumers subscribe independently. Producers don't know about consumers.
Key property: Adding a new subscriber (e.g., Fraud Detection) requires zero changes to the publisher.
2. Event Sourcing
Instead of storing current state, store every state-changing event. Current state is derived by replaying events.
| Traditional CRUD | Event Sourcing |
|---|---|
| UPDATE orders SET status='shipped' | Append OrderShipped{orderId, carrier, trackingNo} |
| Current state in a row | Current state = replay of all events |
| History lost | Full audit trail |
| One model | Separate write (events) and read (projections) models |
3. Saga Pattern — Coordinating Distributed Transactions
When a business process spans multiple services, there's no distributed transaction. Instead, a saga coordinates via events and compensating actions.
Common Pitfalls
- Event schema evolution — Consumers must handle old and new event versions. Use a schema registry.
- Ordering guarantees — Events may arrive out of order across partitions. Use partition keys carefully.
- Idempotency — At-least-once delivery means handlers must be idempotent (use
eventIddeduplication). - Debugging complexity — Distributed traces are harder than a single call stack. Invest in correlation IDs and observability.
- Eventual consistency — Users may see stale reads. Design UX to accommodate this.
When to Use EDA
- Microservices needing loose coupling.
- Real-time data pipelines (Kafka, Pulsar).
- CQRS — separate read and write models.
- Audit-critical systems (finance, healthcare) where event sourcing provides a full history.