Event-Driven Architecture
Services communicate through events for loose coupling and async processing.
Event-Driven Architecture (EDA) structures a system around the production, detection, and reaction to events. Services communicate by emitting events rather than calling each other directly.
Architecture
┌──────────┐ event ┌───────────┐ event ┌──────────┐
│ Producer │──────────▶│ Message │──────────▶│ Consumer │
│ Service │ │ Broker │ │ Service │
└──────────┘ └─────┬─────┘ └──────────┘
│
┌──────┼──────┐
│ │ │
┌────▼─┐ ┌─▼──┐ ┌─▼────┐
│ Svc A│ │Svc B│ │ Svc C│
└──────┘ └────┘ └──────┘
Core Concepts
| Term | Definition |
|---|---|
| Event | A fact that happened (immutable, past tense) |
| Producer | Service that emits events |
| Consumer | Service that reacts to events |
| Broker | Middleware that routes events (Kafka, RabbitMQ, SQS) |
When to Use
- Loose coupling is a priority — producers don’t know about consumers
- Async workflows — processing can happen at different speeds
- Fan-out — one event triggers multiple independent reactions
- Audit trail — events are a log of what happened and when
When to Avoid
- When you need strong consistency (synchronous is simpler)
- When request-response latency matters (events add delay)
- Small systems where direct calls are sufficient
Patterns
Event Sourcing
Store every state change as an event. Current state is derived by replaying events.
CQRS (Command Query Responsibility Segregation)
Separate write models (commands) from read models (queries). Writes produce events; reads use denormalized projections.
Saga
Manage distributed transactions through a sequence of local transactions, each publishing an event that triggers the next step. Compensating events handle failures.
Challenges
| Challenge | Mitigation |
|---|---|
| Eventual consistency | Communicate SLAs; use UI patterns for stale data |
| Event ordering | Use partitioned logs (Kafka topics) |
| Duplicate events | Idempotent consumers |
| Schema evolution | Schema registry, backward-compatible changes |
| Debugging | Distributed tracing, event replay in dev |