Nextgen Blog
HomeLearnAIQuantumRoboticsSecuritySpaceAbout
Nextgen Blog

By Anubhav — full stack engineer, IIT Mandi CSE. Deep dives into AI, software engineering, and the technologies shaping the next generation of tech.

Navigate

  • Home
  • Learn
  • Blog
  • Archive
  • About

Topics

  • Artificial Intelligence
  • Quantum Computing
  • Robotics
  • Cybersecurity
  • Space Tech

Connect

Built with ❤️ & By - Anubhav

© 2026 Nextgen Blog by Anubhav. All rights reserved.

Privacy PolicyTerms of Service
Phase 04 · Storage, Queues & Event StreamingChapter 23 of 33
22.
Phase 04Read time ~25 minDifficulty advanced

Event-Driven Architecture

In this chapter
  • 01Introduction
  • 02What Is an Event?
  • 03Event vs Command vs Query
  • 04Event
  • 05Command
  • 06Query
  • 07Why Events?
  • 08Core EDA Components
  • 09Event Producer
  • 10Event Consumer
  • 11Event Broker
  • 12Event-Driven Architecture Flow
  • 13Event Notification
  • 14Event-Carried State Transfer
  • 15Event Notification vs Event-Carried State
  • 16Choreography
  • 17Choreography Example
  • 18Advantages of Choreography
  • 19Choreography Problems
  • 20Orchestration
  • 21Choreography vs Orchestration
  • 22Orchestrator Example
  • 23Saga Pattern
  • 24Saga Example
  • 25Saga Choreography
  • 26Saga Orchestration
  • 27Saga Limitations
  • 28Eventual Consistency
  • 29Strong vs Eventual Consistency
  • 30Where Eventual Consistency Is Often Acceptable
  • 31Idempotency in EDA
  • 32Idempotent Consumer
  • 33Duplicate Event Scenario
  • 34Ordering in EDA
  • 35Event Versioning
  • 36Backward Compatibility
  • 37Event Contract Governance
  • 38Event Storm
  • 39Event Granularity
  • 40Event Naming
  • 41Event Ownership
  • 42Source of Truth
  • 43Derived State
  • 44Event Sourcing
  • 45Event-Sourced Aggregate
  • 46Benefits of Event Sourcing
  • 47Event Sourcing Challenges
  • 48CQRS
  • 49Why CQRS?
  • 50CQRS Is Not Automatically Event Sourcing
  • 51EDA and Microservices
  • 52Synchronous + Asynchronous Architecture
  • 53Event-Driven Workflow Example
  • 54Failure in Event-Driven Workflows
  • 55Retry Strategy
  • 56Event Dead-Letter Handling
  • 57Poison Events
  • 58Partition Blocking
  • 59Eventual Consistency and User Experience
  • 60Distributed Tracing
  • 61Observability
  • 62Events
  • 63Consumers
  • 64Workflow
  • 65Business SLAs
  • 66Event-Driven Architecture Security
  • 67Privacy Challenge
  • 68Event Replay and Side Effects
  • 69Replay-Safe Consumers
  • 70Event Versioning Strategy
  • 71Strategy A — Backward-compatible schema
  • 72Strategy B — Explicit event versions
  • 73Strategy C — New event type
  • 74Event Contract Testing
  • 75EDA Architecture Pattern
  • 76Database-per-Service
  • 77Distributed Transaction Problem
  • 78E-Commerce Saga Example
  • 79Orchestration-Based E-Commerce Saga
  • 80Choreography-Based E-Commerce Saga
  • 81Notification Architecture
  • 82Search Index Architecture
  • 83Analytics Architecture
  • 84Event Mesh Concept
  • 85Common Mistakes
  • 86Mistake 1
  • 87Mistake 2
  • 88Mistake 3
  • 89Mistake 4
  • 90Mistake 5
  • 91Mistake 6
  • 92Mistake 7
  • 93Mistake 8
  • 94Mistake 9
  • 95Mistake 10
  • 96Mistake 11
  • 97Mistake 12
  • 98Interview Framework
  • 99Interview Question: Event vs Command
  • 100Interview Question: Choreography vs Orchestration
  • 101Interview Question: What Is a Saga?
  • 102Interview Question: Why Is Eventual Consistency Common in EDA?
  • 103Interview Question: Why Is Idempotency Important?
  • 104Interview Question: Can Kafka Replace a Database?
  • 105Mini Project
  • 106Services
  • 107Events
  • 108Workflow
  • 109Mini Project Requirements
  • 110Advanced Mini Project
  • 111Production Checklist
  • 112Key Mental Model
  • 113Chapter Summary
  • 114Interview Revision Checklist
  • 115Next Chapter
  • 116Chapter 22 — Distributed Systems Fundamentals
In this chapter (116 sections)
01Introduction02What Is an Event?03Event vs Command vs Query04Event05Command06Query07Why Events?08Core EDA Components09Event Producer10Event Consumer11Event Broker12Event-Driven Architecture Flow13Event Notification14Event-Carried State Transfer15Event Notification vs Event-Carried State16Choreography17Choreography Example18Advantages of Choreography19Choreography Problems20Orchestration21Choreography vs Orchestration22Orchestrator Example23Saga Pattern24Saga Example25Saga Choreography26Saga Orchestration27Saga Limitations28Eventual Consistency29Strong vs Eventual Consistency30Where Eventual Consistency Is Often Acceptable31Idempotency in EDA32Idempotent Consumer33Duplicate Event Scenario34Ordering in EDA35Event Versioning36Backward Compatibility37Event Contract Governance38Event Storm39Event Granularity40Event Naming41Event Ownership42Source of Truth43Derived State44Event Sourcing45Event-Sourced Aggregate46Benefits of Event Sourcing47Event Sourcing Challenges48CQRS49Why CQRS?50CQRS Is Not Automatically Event Sourcing51EDA and Microservices52Synchronous + Asynchronous Architecture53Event-Driven Workflow Example54Failure in Event-Driven Workflows55Retry Strategy56Event Dead-Letter Handling57Poison Events58Partition Blocking59Eventual Consistency and User Experience60Distributed Tracing61Observability62Events63Consumers64Workflow65Business SLAs66Event-Driven Architecture Security67Privacy Challenge68Event Replay and Side Effects69Replay-Safe Consumers70Event Versioning Strategy71Strategy A — Backward-compatible schema72Strategy B — Explicit event versions73Strategy C — New event type74Event Contract Testing75EDA Architecture Pattern76Database-per-Service77Distributed Transaction Problem78E-Commerce Saga Example79Orchestration-Based E-Commerce Saga80Choreography-Based E-Commerce Saga81Notification Architecture82Search Index Architecture83Analytics Architecture84Event Mesh Concept85Common Mistakes86Mistake 187Mistake 288Mistake 389Mistake 490Mistake 591Mistake 692Mistake 793Mistake 894Mistake 995Mistake 1096Mistake 1197Mistake 1298Interview Framework99Interview Question: Event vs Command100Interview Question: Choreography vs Orchestration101Interview Question: What Is a Saga?102Interview Question: Why Is Eventual Consistency Common in EDA?103Interview Question: Why Is Idempotency Important?104Interview Question: Can Kafka Replace a Database?105Mini Project106Services107Events108Workflow109Mini Project Requirements110Advanced Mini Project111Production Checklist112Key Mental Model113Chapter Summary114Interview Revision Checklist115Next Chapter116Chapter 22 — Distributed Systems Fundamentals

1. Introduction#

In the previous chapters, we learned:

Message Queues
      ↓
Kafka
      ↓
Event Streaming

Now we move one level higher.

The technology is not the architecture.

Kafka, RabbitMQ, SQS, Pub/Sub, Redis Streams, and similar systems are infrastructure.

Event-Driven Architecture (EDA) is an architectural style in which components communicate and coordinate using events.

The central idea is:

A system publishes facts about things that happened, and other components react to those facts.

Example:

Order Service
      |
      | OrderCreated
      v
Event Broker
      |
      +------→ Inventory
      |
      +------→ Payment
      |
      +------→ Notification
      |
      +------→ Analytics

This architecture can reduce direct coupling between services.


2. What Is an Event?#

An event represents something that has already happened.

Examples:

UserRegistered
OrderCreated
PaymentCompleted
PaymentFailed
ItemShipped
VideoUploaded
InvoiceGenerated

Notice the naming:

OrderCreated

rather than:

CreateOrder

The first describes a fact.

The second describes an instruction.


3. Event vs Command vs Query#

This distinction is extremely important.

Event#

A fact:

OrderCreated

Meaning:

An order was created.

Command#

An instruction:

CreateOrder

Meaning:

Please create an order.

Query#

A request for information:

GetOrder

Meaning:

Please give me order information.

Mental model:

Command → Do something
 
Event   → Something happened
 
Query   → Give me information

4. Why Events?#

Imagine an Order Service directly calling:

Inventory
Payment
Notification
Analytics
Recommendation
Fraud

Architecture:

                 Inventory
                    ^
                    |
Payment ← Order → Notification
                    |
                    v
               Analytics

The Order Service becomes aware of many downstream systems.

This creates coupling.

With events:

Order Service
      |
      v
OrderCreated
      |
      +----→ Inventory
      +----→ Payment
      +----→ Notification
      +----→ Analytics

The producer only needs to publish the event.

New consumers can be added without necessarily changing the original producer.


5. Core EDA Components#

A typical event-driven architecture contains:

Event Producer
      |
      v
Event Broker
      |
      v
Event Consumer

Additional components may include:

Schema Registry
Dead-Letter Queue
Retry System
Event Store
Stream Processor
Monitoring
Tracing

6. Event Producer#

The producer creates an event.

Example:

Order Service

After successfully creating an order:

OrderCreated

The producer should publish meaningful business facts rather than exposing internal implementation details.


7. Event Consumer#

A consumer reacts to an event.

Example:

OrderCreated
      |
      v
Inventory Service

The Inventory Service might reserve inventory.

Another consumer:

OrderCreated
      |
      v
Notification Service

may send an email.

Consumers should generally not assume they are the only consumer.


8. Event Broker#

The broker transports and often stores events.

Examples of technologies include:

Kafka
RabbitMQ
Amazon SQS/SNS
Google Pub/Sub
Azure Service Bus
Redis Streams

The correct technology depends on:

  • throughput
  • durability
  • ordering
  • replay
  • delivery semantics
  • operational requirements
  • cloud environment

9. Event-Driven Architecture Flow#

A typical flow:

User
 |
 v
Order API
 |
 v
Order Service
 |
 +----→ Database
 |
 +----→ OrderCreated
             |
             v
          Broker
             |
      +------+------+
      |      |      |
      v      v      v
 Inventory Payment Notification

Each consumer can evolve independently.


10. Event Notification#

The simplest event style is event notification.

Example:

OrderCreated

The event tells consumers:

Something happened.

The consumer may then query another service for additional information.

For example:

OrderCreated
    |
    v
Inventory Service
    |
    v
GET order details

This is simple, but it can introduce additional network calls.


11. Event-Carried State Transfer#

Instead of sending only:

OrderCreated

the event can carry relevant data:

{
  "eventType": "OrderCreated",
  "orderId": "ORD-123",
  "userId": "U-42",
  "items": [
    {
      "productId": "P-100",
      "quantity": 2
    }
  ],
  "total": 4999
}

Consumers may not need to call the Order Service.

Benefits:

  • fewer synchronous dependencies
  • lower latency
  • greater consumer autonomy

Trade-off:

  • larger events
  • duplicated data
  • more schema-evolution responsibility

12. Event Notification vs Event-Carried State#

Approach Event Contains Consumer Dependency
Notification Minimal fact May call producer
State transfer Relevant state More independent

Use the smallest event that satisfies the consumer requirements without creating unnecessary coupling.


13. Choreography#

Choreography means services react to events independently.

Example:

OrderCreated
     |
     +----→ Inventory
     |
     +----→ Payment
     |
     +----→ Notification

There is no central coordinator telling every service what to do.

Each service decides how to react.


14. Choreography Example#

Order workflow:

OrderCreated
     |
     v
Inventory
     |
     | InventoryReserved
     v
Payment
     |
     | PaymentCompleted
     v
Shipping
     |
     | ShipmentCreated
     v
Notification

The workflow emerges from event reactions.


15. Advantages of Choreography#

Benefits:

  • loose coupling
  • independent services
  • easy addition of independent consumers
  • no central workflow coordinator
  • natural event-driven communication

However, choreography becomes difficult when workflows become highly complex.


16. Choreography Problems#

Imagine:

Order
 ↓
Inventory
 ↓
Payment
 ↓
Fraud
 ↓
Shipping
 ↓
Notification
 ↓
Loyalty
 ↓
Analytics

With many events and services, understanding the complete workflow becomes difficult.

Potential problems:

  • hidden dependencies
  • difficult debugging
  • difficult workflow visualization
  • complex failure handling
  • accidental event chains
  • unclear ownership

This is sometimes called a distributed business workflow becoming hard to reason about.


17. Orchestration#

Orchestration introduces a central workflow coordinator.

Example:

            Order Orchestrator
             /      |       \
            v       v        v
       Inventory Payment Shipping

The orchestrator decides what happens next.

For example:

1. Reserve inventory
2. Charge payment
3. Create shipment
4. Send confirmation

18. Choreography vs Orchestration#

Choreography Orchestration
Services react to events Coordinator controls workflow
Decentralized Central workflow logic
Less central coupling Coordinator knows participants
Can become hard to trace Easier workflow visibility
Good for independent reactions Good for complex workflows

Neither is universally superior.

The right choice depends on workflow complexity and ownership.


19. Orchestrator Example#

                 Order Orchestrator
                         |
            +------------+------------+
            |            |            |
            v            v            v
       Inventory      Payment      Shipping
            |            |            |
            +------------+------------+
                         |
                         v
                     Completed

The orchestrator can handle:

  • timeouts
  • retries
  • compensation
  • branching
  • workflow state
  • failure handling

20. Saga Pattern#

A Saga coordinates a distributed business transaction across multiple services.

Why?

Because a normal database transaction cannot easily span:

Order DB
Inventory DB
Payment DB
Shipping DB

A Saga breaks the business transaction into local transactions.

Example:

Create Order
     ↓
Reserve Inventory
     ↓
Charge Payment
     ↓
Create Shipment

If something fails, compensating actions may undo previous business effects.


21. Saga Example#

Suppose:

Order Created ✓
Inventory Reserved ✓
Payment Charged ✓
Shipping Failed ✗

A compensation could be:

Release Inventory
Refund Payment
Cancel Order

The important idea is:

A Saga uses a sequence of local transactions and compensating actions rather than one global database transaction.


22. Saga Choreography#

In choreography-based Saga:

OrderCreated
     |
     v
Inventory
     |
InventoryReserved
     |
     v
Payment
     |
PaymentCompleted
     |
     v
Shipping

Each service reacts to events.

Failure events trigger compensating reactions.


23. Saga Orchestration#

In orchestration-based Saga:

             Saga Orchestrator
                    |
          +---------+---------+
          |         |         |
          v         v         v
     Inventory   Payment   Shipping

The orchestrator controls the sequence and compensation.

This can be easier to understand for complex workflows.


24. Saga Limitations#

Sagas do not provide the same atomicity as a single database transaction.

There can be periods of intermediate state.

Example:

Payment = SUCCESS
Shipping = PENDING

During that time, the system is temporarily inconsistent from a global perspective.

Therefore business workflows must be designed to tolerate intermediate states.


25. Eventual Consistency#

Event-driven systems often use eventual consistency.

Example:

Order DB
   |
   v
OrderCreated
   |
   v
Search Index

There may be a short delay:

Order exists
but
search index does not show it yet

Eventually:

event processed
→ search updated

This is eventual consistency.


26. Strong vs Eventual Consistency#

Strong consistency aims for:

write
 ↓
read
 ↓
immediately sees latest state

Eventual consistency allows:

write
 ↓
temporary stale state
 ↓
event processing
 ↓
latest state appears

The choice depends on business requirements.


27. Where Eventual Consistency Is Often Acceptable#

Examples:

  • search indexes
  • analytics dashboards
  • recommendation systems
  • notification counters
  • activity feeds
  • derived read models

Where it may be harder to accept:

  • certain payment authorization decisions
  • inventory overselling controls
  • security authorization
  • some financial ledger operations

The exact consistency requirement must be derived from the business operation.


28. Idempotency in EDA#

Events can be duplicated.

Example:

OrderCreated
OrderCreated

A consumer must not accidentally:

charge customer twice

Use:

eventId
+
idempotency record
+
transactional business operation

29. Idempotent Consumer#

Example:

Event ID = evt_123

Consumer checks:

Has evt_123 already been processed?

If yes:

skip

If no:

process
record evt_123

The check and business state update should be designed carefully to avoid races.


30. Duplicate Event Scenario#

Suppose:

Consumer processes event
       |
       v
Database commit succeeds
       |
       X
ACK/offset commit fails
       |
       v
Event delivered again

This is normal in at-least-once systems.

The correct response is not:

Assume duplicates never happen.

Instead:

Make the business operation safe when duplicates happen.


31. Ordering in EDA#

Some workflows require order.

Example:

OrderCreated
OrderPaid
OrderShipped
OrderDelivered

An event arriving out of order can cause incorrect state.

Possible approaches:

  • partition by entity ID
  • sequence numbers
  • version numbers
  • buffering
  • reject stale events
  • state-machine validation

32. Event Versioning#

Events evolve.

Version 1:

{
  "orderId": "123",
  "amount": 500
}

Version 2:

{
  "orderId": "123",
  "currency": "INR",
  "amount": 500
}

A robust event architecture supports compatible evolution.

Possible strategies:

add optional fields

or:

OrderCreated.v2

depending on the ecosystem.


33. Backward Compatibility#

A new consumer may need to read older events.

A new producer may need to coexist with old consumers.

Therefore event contracts should be treated as APIs.

Consider:

Producer
    |
    v
Event Contract
    |
    v
Many Consumers

Changing the event schema can affect many systems.


34. Event Contract Governance#

Large organizations may need:

  • schema registry
  • ownership
  • documentation
  • compatibility rules
  • versioning policy
  • deprecation process
  • validation

Events become shared contracts between teams.


35. Event Storm#

A common architectural failure is creating too many events.

Example:

UserNameCharacterChanged
UserNameValidated
UserNameNormalized
UserNameStored
UserProfileUpdated

Not every internal state transition needs to become a public event.

Prefer meaningful business events.


36. Event Granularity#

Too coarse:

OrderUpdated

Consumers may not know what changed.

Too fine:

OrderItemQuantityFieldChanged

can create excessive event volume.

A good event represents a meaningful business fact.


37. Event Naming#

Good:

OrderCreated
PaymentCompleted
ShipmentDispatched
UserRegistered

Potentially confusing:

ProcessOrder
DoPayment
UpdateSomething

Use past-tense factual naming for events.


38. Event Ownership#

Every important event should have a clear owner.

For example:

Order Service
  owns OrderCreated

Other services consume it.

Avoid multiple services independently claiming ownership of the same source-of-truth event.


39. Source of Truth#

Suppose:

Order DB
Search Index
Cache
Analytics DB

Which one is authoritative?

Usually one system should be the source of truth.

Example:

Order DB = source of truth
Search = derived
Cache = derived
Analytics = derived

Events propagate changes to derived systems.


40. Derived State#

Example:

Order DB
   |
   | OrderCreated
   v
Kafka
   |
   +----→ Search Index
   +----→ Analytics DB
   +----→ Cache Updater

These consumers build derived state.

If derived state becomes corrupted, event replay may allow rebuilding it.


41. Event Sourcing#

Traditional CRUD:

Orders table
----------------
order_id
status
amount

The current state is stored directly.

Event sourcing instead stores events:

OrderCreated
PaymentCompleted
OrderShipped
OrderDelivered

The current state is derived from the event history.


42. Event-Sourced Aggregate#

Example:

Events:
 
OrderCreated
OrderPaid
OrderShipped

Projection:

status = SHIPPED

The event stream becomes the historical record.


43. Benefits of Event Sourcing#

Potential benefits:

  • complete history
  • auditability
  • replay
  • temporal debugging
  • derived projections
  • reconstructable state

But it introduces complexity.


44. Event Sourcing Challenges#

Challenges include:

  • event schema evolution
  • storage growth
  • rebuilding state
  • debugging long histories
  • privacy/deletion requirements
  • replay performance
  • event versioning
  • operational complexity

Do not choose event sourcing merely because Kafka is available.


45. CQRS#

CQRS separates:

Command side

from:

Query side

Example:

                 Commands
                    |
                    v
               Write Model
                    |
                    v
                  Events
                    |
                    v
                 Broker
                    |
          +---------+---------+
          |         |         |
          v         v         v
       Search     Read DB   Analytics

Queries can use optimized read models.


46. Why CQRS?#

Suppose writes require:

normalized relational model

but reads require:

fast denormalized view

CQRS allows separate models.

Example:

Write DB:
normalized
 
Read DB:
precomputed

Events connect them.


47. CQRS Is Not Automatically Event Sourcing#

These concepts are related but different.

You can have:

CQRS without Event Sourcing

and:

Event Sourcing without full CQRS

They are often combined, but they are not synonyms.


48. EDA and Microservices#

Event-driven architecture can reduce synchronous dependencies between microservices.

Instead of:

A → B → C → D

you may have:

A → Event
      |
      +→ B
      +→ C
      +→ D

But event-driven architecture does not automatically mean:

microservices

EDA can exist in modular monoliths and other architectures too.


49. Synchronous + Asynchronous Architecture#

Real systems often use both.

Example:

Client
  |
  | synchronous
  v
Order API
  |
  +---- synchronous → Order DB
  |
  +---- asynchronous → Event Broker
                         |
                         +→ Notifications
                         +→ Analytics
                         +→ Search

Do not force everything through events.

Use synchronous calls when an immediate response is required.

Use asynchronous events when decoupling and eventual processing are appropriate.


50. Event-Driven Workflow Example#

Consider food delivery.

OrderCreated
      |
      v
Restaurant Service
      |
RestaurantAccepted
      |
      v
Payment Service
      |
PaymentCompleted
      |
      v
Delivery Service
      |
DriverAssigned
      |
      v
OrderPickedUp
      |
      v
OrderDelivered

Each event represents a business state transition.


51. Failure in Event-Driven Workflows#

Suppose:

PaymentCompleted
        |
        v
Delivery Service
        |
        X
       fail

The payment should not necessarily be repeated.

The system can retry the delivery operation independently.

This demonstrates a key benefit of decoupled processing.


52. Retry Strategy#

Consumers should classify failures.

Transient:

timeout
temporary dependency outage
rate limit

Retry:

exponential backoff
+
jitter

Permanent:

invalid event
unsupported schema
invalid business state

Move to:

DLQ

or a controlled error workflow.


53. Event Dead-Letter Handling#

A DLQ can contain:

event
error
consumer
attempt count
timestamp
trace ID

Example:

{
  "eventId": "evt_123",
  "consumer": "shipping-service",
  "attempts": 5,
  "error": "Invalid address",
  "failedAt": "2026-10-01T10:00:00Z"
}

This makes operational debugging easier.


54. Poison Events#

A poison event can repeatedly crash a consumer.

Example:

invalid schema

If the consumer retries indefinitely:

consumer
 ↓
failure
 ↓
retry
 ↓
failure
 ↓
retry

The entire partition may be blocked depending on the processing design.

Use controlled retries and dead-letter strategies.


55. Partition Blocking#

Suppose ordered processing requires:

Event 1
Event 2
Event 3

If Event 2 fails permanently:

Event 1 ✓
Event 2 ✗
Event 3 ?

You cannot simply process Event 3 if ordering is required.

This creates a trade-off between:

strict ordering

and:

availability / throughput

The business requirement determines the correct strategy.


56. Eventual Consistency and User Experience#

Users may see temporary differences.

Example:

Order API says:
Order created
 
Search page:
Order not found

This can be acceptable if the UI communicates processing state appropriately.

Possible patterns:

processing
pending
syncing

Good system design considers the user experience of eventual consistency rather than hiding it.


57. Distributed Tracing#

An event-driven system can be difficult to debug.

Example:

HTTP request
   |
   v
Order Service
   |
   v
Kafka
   |
   v
Payment Consumer
   |
   v
Payment API

Use:

traceId
correlationId
eventId

to connect the workflow.


58. Observability#

Monitor:

Events#

publish rate
consume rate
event failures
event age

Consumers#

lag
processing latency
retry count
DLQ count

Workflow#

OrderCreated → PaymentCompleted latency
PaymentCompleted → ShipmentCreated latency

Business-level metrics are often more useful than infrastructure metrics alone.


59. Business SLAs#

Suppose:

PaymentCompleted → ShipmentCreated

must happen within:

30 seconds

Monitor the actual workflow latency.

A system can have:

Kafka healthy
CPU healthy
memory healthy

while still violating the business SLA because a consumer is slow.


60. Event-Driven Architecture Security#

Security considerations include:

  • authentication
  • authorization
  • topic permissions
  • encryption
  • schema validation
  • payload minimization
  • sensitive-data protection
  • audit logs

Do not publish secrets or unnecessary personal data into long-retention event streams.


61. Privacy Challenge#

Event streams can retain historical data.

Suppose an event contains:

user email
phone
address

and retention is:

7 years

A deletion request may be difficult if personal data is embedded throughout immutable historical events.

Therefore privacy requirements must influence event design.

Possible strategies:

  • minimize sensitive data
  • use references instead of raw data
  • tokenize sensitive values
  • define retention policies
  • separate sensitive data from event payloads

62. Event Replay and Side Effects#

Replay is powerful but dangerous.

Suppose replaying:

PaymentCompleted

causes:

charge card

again.

That would be incorrect.

Therefore consumers should distinguish between:

rebuildable projections

and:

irreversible external side effects

Replay should be designed carefully.


63. Replay-Safe Consumers#

A projection consumer might safely replay:

OrderCreated
OrderPaid
OrderShipped

to rebuild:

search index

But a payment consumer should not blindly replay historical events and charge customers again.

This distinction is essential in event-driven architectures.


64. Event Versioning Strategy#

Possible strategies:

Strategy A — Backward-compatible schema#

Add optional fields.

Strategy B — Explicit event versions#

OrderCreated.v1
OrderCreated.v2

Strategy C — New event type#

OrderCreated
OrderCreatedWithPricing

The organization should have a consistent approach.


65. Event Contract Testing#

Because many consumers depend on events, producer changes can break downstream services.

Contract tests can validate:

producer schema
vs
consumer expectations

This is especially important in large microservice environments.


66. EDA Architecture Pattern#

A common architecture:

                   API Gateway
                       |
                       v
                  Order Service
                       |
                +------+------+
                |             |
                v             v
            Order DB       Event Bus
                              |
              +---------------+---------------+
              |               |               |
              v               v               v
          Inventory        Payment        Notification
              |               |               |
              v               v               v
           Database        Provider         Provider

Each service owns its own state.

Events communicate changes.


67. Database-per-Service#

In a microservice architecture:

Order Service → Order DB
Payment Service → Payment DB
Inventory Service → Inventory DB

Do not casually allow every service to directly modify another service's database.

Instead:

Service A
   |
   v
Event
   |
   v
Service B

or use an explicit API where synchronous interaction is required.


68. Distributed Transaction Problem#

Suppose:

Order DB
Payment DB
Inventory DB

You cannot assume a single local transaction covers all three.

Instead:

Order transaction
      ↓
Event
      ↓
Inventory transaction
      ↓
Event
      ↓
Payment transaction

This introduces eventual consistency and potentially Saga-style compensation.


69. E-Commerce Saga Example#

Start:

Create Order

Then:

Reserve Inventory
      ↓
Charge Payment
      ↓
Create Shipment

Failure:

Shipment fails

Compensate:

Refund Payment
      ↓
Release Inventory
      ↓
Cancel Order

This is a classic distributed workflow.


70. Orchestration-Based E-Commerce Saga#

                 Saga Orchestrator
                         |
                 Create Order
                         |
                         v
                 Reserve Inventory
                         |
                         v
                  Charge Payment
                         |
                         v
                  Create Shipment
                         |
                         v
                       Done

If payment fails:

Release Inventory
        |
        v
Cancel Order

The orchestrator maintains workflow state.


71. Choreography-Based E-Commerce Saga#

OrderCreated
     |
     v
Inventory
     |
InventoryReserved
     |
     v
Payment
     |
PaymentCompleted
     |
     v
Shipping

Failure events propagate compensation.

This can be elegant for simple workflows but harder to reason about as the workflow grows.


72. Notification Architecture#

Example:

Business Event
      |
      v
Notification Event
      |
      v
Notification Service
      |
      +---- Email
      +---- SMS
      +---- Push

Each delivery channel can have:

  • its own queue
  • retry policy
  • provider
  • rate limit
  • monitoring

73. Search Index Architecture#

Product Service
      |
ProductUpdated
      |
      v
Event Broker
      |
      v
Search Indexer
      |
      v
Search Engine

If the search index is lost:

replay product events
      |
      v
rebuild index

This is a powerful use of event retention.


74. Analytics Architecture#

Services
   |
   v
Event Bus
   |
   +---- Stream Processor
   |
   +---- Data Warehouse
   |
   +---- Data Lake

The same event stream can serve multiple analytical systems.


75. Event Mesh Concept#

At very large organizational scale, many event domains may exist:

Orders
Payments
Customers
Inventory
Shipping

Each domain can publish events.

Consumers subscribe to events relevant to their needs.

Governance becomes increasingly important:

ownership
schemas
security
discoverability
retention
versioning

76. Common Mistakes#

Mistake 1#

Turning every internal method call into an event.

Mistake 2#

Using events where synchronous response is required.

Mistake 3#

No clear event ownership.

Mistake 4#

No schema/versioning strategy.

Mistake 5#

Assuming event delivery is exactly once.

Mistake 6#

No idempotency.

Mistake 7#

Using event replay for irreversible side effects without safeguards.

Mistake 8#

Building overly complex choreography.

Mistake 9#

Using Saga without defining compensation.

Mistake 10#

Assuming eventual consistency is acceptable everywhere.

Mistake 11#

Publishing sensitive information unnecessarily.

Mistake 12#

Ignoring observability across asynchronous boundaries.


77. Interview Framework#

When asked:

Design an event-driven system.

Start with requirements:

What events?
Who produces them?
Who consumes them?
Does the caller need an immediate response?
What throughput?
What ordering?
What durability?
What retention?
Can events be duplicated?
Need replay?
Need workflow orchestration?
Need compensation?
What consistency is required?

Then define:

Producer
   ↓
Event Broker
   ↓
Consumers

Then discuss:

event contracts
partitioning
ordering
retries
DLQ
idempotency
Saga
observability
security

78. Interview Question: Event vs Command#

Answer:

An event represents a fact that has already happened, while a command is an instruction asking a component to perform an action.

Example:

OrderCreated → event
 
CreateOrder → command

79. Interview Question: Choreography vs Orchestration#

Answer:

In choreography, services independently react to events and the workflow emerges from those reactions. In orchestration, a central coordinator explicitly controls the workflow, including sequencing, retries, and compensation.


80. Interview Question: What Is a Saga?#

Answer:

A Saga is a distributed transaction pattern in which a business operation is split into local transactions, with compensating actions used when later steps fail.


81. Interview Question: Why Is Eventual Consistency Common in EDA?#

Answer:

Because asynchronous events introduce processing delays between the source system and derived consumers. The source can commit immediately while other systems update asynchronously, resulting in temporary inconsistency that converges over time.


82. Interview Question: Why Is Idempotency Important?#

Answer:

Because asynchronous delivery commonly permits retries and duplicate events. Idempotent consumers prevent repeated delivery from creating repeated business effects.


83. Interview Question: Can Kafka Replace a Database?#

Answer:

Kafka and databases solve different primary problems. Kafka is optimized for durable event streams, partitioned logs, replay, and fan-out, while databases provide querying, transactions, constraints, and current application state. Production systems often use both.


84. Mini Project#

Build an event-driven e-commerce workflow.

Services#

Order Service
Inventory Service
Payment Service
Shipping Service
Notification Service

Use:

Kafka

or another event broker.


85. Events#

Implement:

OrderCreated
InventoryReserved
InventoryReservationFailed
PaymentCompleted
PaymentFailed
ShipmentCreated
ShipmentFailed
OrderCompleted
OrderCancelled

86. Workflow#

Normal:

OrderCreated
     ↓
InventoryReserved
     ↓
PaymentCompleted
     ↓
ShipmentCreated
     ↓
OrderCompleted

Failure:

OrderCreated
     ↓
InventoryReserved
     ↓
PaymentFailed
     ↓
ReleaseInventory
     ↓
OrderCancelled

87. Mini Project Requirements#

Implement:

event schemas
event IDs
idempotency
consumer groups
retries
DLQ
workflow state
trace IDs
metrics

Also simulate:

duplicate event
consumer crash
payment timeout
inventory failure
out-of-order event
slow consumer
schema version change

88. Advanced Mini Project#

Add an orchestration service:

Saga Orchestrator

Track:

sagaId
orderId
currentStep
status
attempts
failureReason
createdAt
updatedAt

Implement compensation.

This transforms the project from a simple event demo into a realistic distributed workflow.


89. Production Checklist#

[ ] Event definitions
[ ] Event ownership
[ ] Event schema
[ ] Versioning
[ ] Compatibility rules
[ ] Producer reliability
[ ] Consumer idempotency
[ ] Retry strategy
[ ] DLQ
[ ] Ordering strategy
[ ] Partition strategy
[ ] Event retention
[ ] Replay strategy
[ ] Saga where required
[ ] Compensation logic
[ ] Source-of-truth definition
[ ] Eventual consistency requirements
[ ] Observability
[ ] Distributed tracing
[ ] Security
[ ] Privacy
[ ] Capacity planning
[ ] Failure testing

90. Key Mental Model#

Remember these layers:

                 ARCHITECTURE
                      |
                      v
             Event-Driven Design
                      |
          +-----------+-----------+
          |                       |
          v                       v
    Choreography             Orchestration
          |                       |
          +-----------+-----------+
                      |
                      v
                Event Broker
                      |
          +-----------+-----------+
          |           |           |
          v           v           v
       Consumer    Consumer    Consumer

And for distributed workflows:

Local Transaction
       ↓
Event
       ↓
Local Transaction
       ↓
Event
       ↓
Local Transaction

If a later step fails:

Compensating Action

91. Chapter Summary#

The most important concepts are:

  1. Event-Driven Architecture uses events as communication boundaries.
  2. An event represents a fact that happened.
  3. A command requests an action.
  4. A query requests information.
  5. Event notification communicates that something happened.
  6. Event-carried state transfers useful data with the event.
  7. Choreography lets services react independently.
  8. Orchestration uses a central workflow coordinator.
  9. Sagas coordinate distributed business transactions.
  10. Sagas use compensation instead of global database transactions.
  11. Eventual consistency is common in asynchronous systems.
  12. Idempotency protects against duplicate delivery.
  13. Event ordering must be designed around business requirements.
  14. Events are shared contracts and require schema governance.
  15. Event sourcing stores business history as events.
  16. CQRS separates write and read responsibilities.
  17. CQRS and Event Sourcing are related but not identical.
  18. Event replay is powerful for rebuilding derived state.
  19. Replay must be protected from irreversible side effects.
  20. Events should have clear ownership.
  21. A source of truth should be clearly identified.
  22. Events can connect microservices without requiring direct synchronous dependencies.
  23. Real systems often combine synchronous APIs and asynchronous events.
  24. Retry and DLQ strategies are essential.
  25. Distributed tracing is essential for asynchronous workflows.
  26. Privacy must be considered because event streams can retain historical data.
  27. Business SLAs should measure end-to-end workflow latency.
  28. Event-driven architecture is a design style, not a specific product.

The central principle is:

Publish meaningful business facts.
Keep consumers independently useful.
Assume duplicates and failures.
Define consistency explicitly.
Use orchestration when workflows become complex.
Use compensation for distributed transactions.

92. Interview Revision Checklist#

You should now be able to explain:

  • Event-Driven Architecture
  • Event
  • Command
  • Query
  • Producer
  • Consumer
  • Event broker
  • Event notification
  • Event-carried state transfer
  • Choreography
  • Orchestration
  • Saga
  • Saga choreography
  • Saga orchestration
  • Compensation
  • Eventual consistency
  • Strong consistency
  • Idempotency
  • Duplicate events
  • Event ordering
  • Event versioning
  • Schema governance
  • Event ownership
  • Source of truth
  • Derived state
  • Event Sourcing
  • CQRS
  • CQRS vs Event Sourcing
  • Replay
  • Replay-safe consumers
  • Retry
  • Dead-letter queues
  • Poison events
  • Distributed tracing
  • Business-level SLAs
  • Privacy in event streams
  • Microservices with events
  • Database-per-service
  • Transactional outbox
  • Event-driven workflows
  • E-commerce Saga architecture

93. Next Chapter#

Chapter 22 — Distributed Systems Fundamentals#

In the next chapter we will step back from queues and events and study the deeper principles behind distributed systems.

We will learn:

  • What a distributed system is
  • Why distributed systems are difficult
  • Nodes and networks
  • Partial failure
  • Network partitions
  • Latency
  • Clock problems
  • Timeouts
  • Retries
  • Failure detection
  • Leader election
  • Replication
  • Distributed state
  • Coordination
  • Consensus intuition
  • Availability
  • Reliability
  • Scalability
  • Fault tolerance
  • Idempotency
  • Distributed-system trade-offs
  • Real-world failure scenarios
  • System-design interview questions

Finished this chapter?

Mark it as complete to track your mastery.

Previous ChapterChapter 20 — Kafka & Event StreamingNext ChapterChapter 22 — Distributed Systems Fundamentals
PrevNext