Event-Driven Architecture

Event sourcing, CQRS, saga pattern, and domain events with Kafka.

Advanced 40 min read 📨 Kafka

Event-Driven vs Request-Driven

In a traditional request-driven architecture, services call each other synchronously (HTTP/gRPC). Service A waits for Service B to respond. This creates tight coupling — if B is slow or down, A fails too.

In an event-driven architecture, services communicate through events published to Kafka. Service A publishes "order placed" and moves on. Service B, C, and D each process the event independently, at their own pace. No waiting, no direct coupling.

AspectRequest-DrivenEvent-Driven
CouplingTight — caller knows calleeLoose — producer doesn't know consumers
FailureCascading — downstream failure breaks upstreamIsolated — consumers fail independently
ScalingScale entire chainScale each service independently
ReplayCan't replay requestsReplay events from Kafka

Event Sourcing

Instead of storing current state (like a traditional database), event sourcing stores every state change as an immutable event. Current state is derived by replaying events. Kafka's commit log is a natural fit.

Example: A bank account with event sourcing stores events like AccountOpened($0), Deposited($100), Withdrawn($30), Deposited($50). Current balance = $120 (sum of all events).

CQRS (Command Query Responsibility Segregation)

CQRS separates the write model (commands) from the read model (queries). Commands publish events to Kafka. A separate consumer builds optimized read models (views) from those events. Each read model can be optimized for its specific query pattern.

Key Takeaway: Event-driven architecture with Kafka provides loose coupling, independent scaling, and event replay. Start with simple pub/sub before adopting event sourcing or CQRS — they add complexity that isn't always justified.

⚠️ Common Mistake: Event sourcing everything

Event sourcing adds significant complexity (event versioning, snapshot management, eventual consistency). Use it for domains where audit trail and replay are critical (finance, compliance). For simple CRUD apps, traditional databases are fine.

Event Sourcing Pattern
Command
intent
Event
fact
Event Store
Kafka topic
Projection
read model
Query
serve UI

Practice Exercises

Hard Production Scenario

Design a solution using these concepts for a real-world production system.

Hard Performance Analysis

Benchmark two different approaches and explain which is better and why.