Skip to content

Event_driven


Event-Driven Architecture (EDA) is a software architecture paradigm where services communicate by producing and consuming events rather than making direct synchronous calls.

Request-Driven vs Event-Driven
=============================
REQUEST-DRIVEN: EVENT-DRIVEN:
Client Client
| |
v v
Service A Service A (Producer)
| |
| Call | Publish Event
v v
Service B Message Broker
| |
| Call | Consume Event
v v
Service C Service B (Consumer)
|
v
Service C
Tight coupling Loose coupling
Synchronous Asynchronous

Event TypeDescriptionExample
NotificationSomething happened”User signed up”
CommandRequest an action”Process order”
DocumentData snapshot”Order created”
Event Message Format
===================
{
"eventId": "uuid-12345",
"eventType": "OrderCreated",
"timestamp": "2024-01-15T10:30:00Z",
"producer": "order-service",
"data": {
"orderId": "order-789",
"userId": "user-456",
"amount": 99.99,
"items": [...]
}
}

Pub/Sub Pattern
===============
Producer Topic Consumers
+--------+ +--------+ +--------+
| Order | ----------->| orders | --------->|Email |
|Service | +--------+ |Service |
+--------+ +--------+ +--------+
+--------+ +--------+
| | --------->|Analytics|
+--------+ +--------+
+--------+ +--------+
| | --------->|Inventory|
+--------+ +--------+
Characteristics:
- One event, multiple consumers
- Decoupled producers/consumers
- Event broadcast to all subscribers
Event Streaming
==============
Kafka/Event Hub: Topics as Logs
+------------------------------------------------+
Partition 0: [E1] -> [E2] -> [E5] -> [E7] -> ...
Partition 1: [E3] -> [E4] -> [E6] -> ...
Partition 2: [E8] -> [E9] -> [E10] -> ...
Consumers read from offset:
+--------------------------------------------+
| Consumer A: offset=5 (processing E7) |
| Consumer B: offset=2 (processing E5) |
+--------------------------------------------+
Benefits:
- Replay events
- Exactly-once processing
- Event retention
- Partition ordering
Event Sourcing
==============
Instead of storing current state, store all events:
Traditional: Event Sourcing:
+--------------------+ +--------------------+
| Order Table: | | Events: |
| order_id: 123 | | OrderCreated |
| status: shipped | | OrderPaid |
| total: 99.99 | | OrderShipped |
+--------------------+ +--------------------+
Rebuild state by replaying events:
+----------------------------------+
| Created(99.99) |
| + Paid() |
| + Shipped() |
| = Current: Shipped, 99.99 |
+----------------------------------+
Benefits:
- Complete audit trail
- Temporal queries
- Event replay/debugging

BrokerCharacteristics
Apache KafkaHigh throughput, distributed, persistent
RabbitMQFlexible routing, older, mature
AWS SQSFully managed, simple
AWS SNSPub/sub, push notifications
Google Pub/SubManaged, global
Kafka Architecture
=================
+--------------------------------------------------+
| Kafka Cluster |
+--------------------------------------------------+
+----------+ +----------+ +----------+
| Broker 1 | | Broker 2 | | Broker 3|
| (Leader) | | (Follower| |(Follower)|
+----------+ +----------+ +----------+
Topics are partitioned and replicated:
+------------------------------------------+
| Topic: Orders |
| Partition 0: Leader on Broker 1 |
| Partition 1: Leader on Broker 2 |
| Partition 2: Leader on Broker 3 |
+------------------------------------------+
Producers write to topics:
+------------------------------------------+
| Producer: Order Service |
| - Keys partition by order_id |
| - Balances across partitions |
+------------------------------------------+
Consumers read from topics:
+------------------------------------------+
| Consumer Group: email-service |
| - Each partition assigned to one worker|
| - Offsets managed by Kafka |
+------------------------------------------+

13.5 Benefits of Event-Driven Architecture

Section titled “13.5 Benefits of Event-Driven Architecture”
BenefitDescription
Loose CouplingProducers don’t know consumers
ScalabilityEasy to add consumers
ResilienceFailed events can be replayed
AuditabilityComplete event history
Real-timeLow latency event processing
FlexibilityAdd services without changing producers

ChallengeDescription
Eventual ConsistencyData may be temporarily inconsistent
DebuggingHard to trace distributed flows
OrderingEvents may arrive out of order
DuplicatesIdempotency needed
Schema EvolutionEvent schema changes over time
Challenge: Eventual Consistency
=================================
Synchronous: Eventual:
+---------+ +---------+ +--------+ +--------+
| Service | -> | Service | |Service | -> | Queue |
+---------+ +---------+ +--------+ +--------+
| | |
v v v
Immediate Slow Consumer
consistency consistency processes
Solution: Compensating Transactions
===================================
Order Service: Create order
Inventory Service: Reserve items (or compensate)
If inventory fails:
1. Send "ReserveFailed" event
2. Order Service rolls back order
3. Send "OrderCancelled" event

CQRS
====
Traditional: CQRS:
+----------+ +----------+ +----------+
| Service | | Command | | Query |
| Read/ | => | Service | | Service |
| Write | | (Write) | | (Read) |
+----------+ +----------+ +----------+
| |
v v
+-------+ +-------+
| Write | | Read |
| DB | | DB |
+-------+ +-------+
Separates read and write models!
CQRS with Event Sourcing
=======================
Command Side:
+--------+ +--------+ +--------+
|Client | -> | Command| -> | Event | -> Write DB
|Request | | Handler| | Store | (append-only)
+--------+ +--------+ +--------+
Query Side:
+--------+ +--------+ +--------+
|Client | -> |Query | -> | Read | <- Materialized
|Request | |Handler | | Model | Views
+--------+ +--------+ +--------+
Event Flow:
1. Command processed -> Event stored
2. Event published -> Projectors update views
3. Query reads from materialized views

Saga Pattern
============
Instead of ACID across services, use Choreography or Orchestration:
CHOREOGRAPHY (Event-based):
==========================
Order Service -> [OrderCreated] -> Inventory Service
|
v
[InventoryReserved]
|
v
Payment Service <----------------- [ReserveFailed]
|
v
[PaymentProcessed]
ORCHESTRATION (Central coordinator):
====================================
Order Service -> Orchestrator
|
+---------+---------+
| | |
v v v
Inventory Payment Shipping
| | |
+---------+---------+
|
v
Complete

PracticeDescription
Immutable EventsDon’t modify after creation
VersioningInclude version in event
Schema RegistryTrack event schemas
IdempotencyHandle duplicate events
Correlation IDsTrack related events
{
"eventId": "uuid",
"eventType": "OrderCreated",
"eventVersion": "1.0",
"timestamp": "2024-01-15T10:30:00Z",
"correlationId": "order-123",
"causationId": "command-456",
"producer": "order-service",
"data": { ... }
}

Key event-driven concepts:

  1. Events over requests - Loose coupling, async communication
  2. Pub/Sub - One event, multiple consumers
  3. Event sourcing - Store events, rebuild state
  4. CQRS - Separate read and write models
  5. Saga pattern - Handle distributed transactions
  6. Challenges - Eventual consistency, ordering, debugging
  7. Schema evolution - Plan for change

Next: Chapter 14: CQRS Pattern