SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
  • Client-Server
  • Monolithic Architecture
  • Microservices
  • Serverless
  • Event-Driven Architecture
  • Peer-to-Peer (P2P)
  • Hexagonal Architecture
  • CQRS
  • Event Sourcing
  • Domain-Driven Design (DDD)
  • Layered (N-Tier) Architecture
  • Containers and Docker
  • Kubernetes Basics
  • Clean Architecture and Modular Monolith
  • Multi-Tenancy
  • Cloud Basics: Regions, Zones and Edge
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Architecture/Architectural Patterns

Event-Driven Architecture

Parts of the system react to events instead of calling each other directly.

⏱ 15 min readIntermediateMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

Event-driven architecture (EDA) is a way to build systems where parts talk by sending events: short messages that say "this just happened". Other parts react when they care.

  • A producer announces a fact, like OrderPlaced. It does not know who will listen.
  • A broker (a queue or a log such as Kafka) carries the event to every consumer that subscribed.
  • Parts are loosely coupled: you can add, change or restart a consumer without touching the producer.

02Concept: What is it?

In a request-driven design, one service calls another and waits: "Charge this card. Reduce the stock. Send the email." The caller must know every service, and if one is down, the whole call fails.

In an event-driven design, the order service only records that an order was placed and publishes an event. It does not ask anyone to do anything. The payment, stock, email and analytics services each subscribe to that event and do their own job in their own time.

An event is a fact about the past (named in the past tense: OrderPlaced, PaymentFailed). It is different from a command ("ChargeCard"), which asks one specific service to do something. Events are broadcast; commands are directed.

Producer, broker and consumers
🛒ProducerOrder service
→↓OrderPlaced
📬Event brokerKafka, RabbitMQ, SNS/SQS
→↓delivers copies
💳Payment
📦Inventory
✉️Email
📈Analytics
The producer talks only to the broker. New consumers can join without any change to the producer.
🧠Tell, do not ask
The producer tells the world what happened. It does not ask for a result. That is why the customer does not have to wait for email or analytics to finish.

03Real-Life Example

🍵The Bell at a Restaurant Kitchen
In a busy restaurant, the waiter does not walk to the chef, then the drink bar, then the dessert station, waiting at each one. The waiter puts the order slip on the rail and rings a bell. The chef starts the main dish, the bar makes the drinks and the dessert station prepares its part, each at its own speed. If the dessert chef is on a break, the slip waits and gets done when they return. The waiter is already serving the next table. A new station (say, a coffee bar) can be added without teaching the waiter anything new.
Restaurant
Event-driven system
The order slip on the rail
An event (OrderPlaced)
The waiter
The producer
The rail and the bell
The event broker
Each station that reads the slip
A consumer (subscriber)
A new coffee station joins
A new subscriber, no change to the producer
A slip waiting while a station is on break
A queued event kept by the broker
Two stations both make the same dish by mistake
A duplicate event handled twice
One event, many reactions
🧾OrderPlaced
→↓
💳Charge the card
📦Reserve the stock
✉️Send the email
📈Update the dashboard

04Why Do We Need It?

🔗Loose coupling
Services do not need to know each other. They only agree on the event shape.
🧯Failure isolation
If one consumer is down, the others and the producer keep working. Events wait in the broker.
⚡Fast responses
The user gets an answer after the first step. Slow work happens in the background.
➕Easy to extend
Add a new feature by adding a new subscriber. The producer stays unchanged.
📈Scales by part
Add more copies of only the consumer that is slow.
🕰️A record of what happened
A log of events can be replayed to rebuild data or feed new features.
Events turn "do this for me, now" into "this happened, react if you care". That removes waiting and removes knowledge between services.

05Where Do We Use It?

🛍️Order flows
Order, payment, stock, shipping and email all react to one another's events.
📱Notifications
A new message, like or follow triggers pushes, emails and counters.
🌡️IoT and sensors
Millions of small readings stream in and rules react to them.
🚨Fraud detection
Each payment event is checked as it happens, and alerts are sent right away.
🔄Data pipelines
Changes in one database are streamed to search, caches and analytics.
λServerless apps
Functions are started by events like a new file or queue message.

06Types / Parts / How It Works

Four common styles

StyleWhat the event carriesExample
Event notificationOnly a small signal: what happened and an ID. The consumer fetches details if needed.“Order 42 was placed”
Event-carried state transferAll the data the consumer needs, so it never has to call back.OrderPlaced with items, address, price
Event sourcingThe events are the source of truth. State is rebuilt by replaying them.A bank account as a list of deposits and withdrawals
CQRS with eventsWrites produce events that update separate read models.Write to the database, update a search index from events

Two ways to wire it

Pub/sub topic vs event log
Pub/Sub topic (fan-out)
📣Publisher
↓
📬Topiccopy for each subscriber
🅰️Sub A
🅱️Sub B
Event log (Kafka)
📣Producer
↓
📜Log1 2 3 4 5 6 ...
👁️Group Aat event 6
👁️Group Bat event 3
Fan-out Replayable log
A queue gives each message to one worker. A log keeps events, and each consumer group reads at its own position, and can replay.

Choreography and orchestration

WayHow it worksGood and bad
ChoreographyEach service reacts to events and emits new ones. Nobody is in charge.Very loose and simple at first. Hard to see the whole flow as it grows.
OrchestrationA central coordinator tells each step what to do, often with commands.Easy to follow and to add retries. The coordinator is a central piece to run.
VisualizerDirect calls vs events: break a service and see who is hurtPlace orders in 'Direct calls', break Payment or Email, and watch orders fail. Switch to 'Events', break a service again, place orders, then press Fix. Finally add a Loyalty service in both modes.
How do the services talk?
Which service is down?
🛒Order service0 ok · 0 failed
→↓OrderPlaced
📬Brokerempty
→↓each service reads
💳Paymentdone 0
📦Inventorydone 0
✉️Emaildone 0
📈Analyticsdone 0
Customer waits
50 ms
order + publish
Orders failed
0
seen by customers
Half-done
0
charged, then failed
Events waiting
0
kept by the broker
Order code edits
0
new services added: 0
Press Place an order. Then break a service and place more orders, in both modes.

A simplified model. Direct mode calls services in order and stops at the first failure. Events mode assumes a broker that stores events until the consumer is back (as Kafka, RabbitMQ or SQS do).

07How to Use It / Steps / Implementation

Designing an event-driven flow

  1. 1
    Find the business events
    List the important facts: OrderPlaced, PaymentCaptured, ItemShipped. Name them in the past tense.
  2. 2
    Design the event
    Give it a unique ID, a type, a time, a version and the data consumers need. Keep it small and stable.
  3. 3
    Choose a broker
    Queue or pub/sub for simple fan-out (SQS, SNS, RabbitMQ). A log for replay and very high volume (Kafka, Kinesis).
  4. 4
    Make consumers idempotent
    Delivery is often at least once. Store processed event IDs, or make the update safe to repeat.
  5. 5
    Handle failures
    Retry with delay, then move bad events to a dead letter queue so one poison message does not block everyone.
  6. 6
    Plan ordering
    Order is usually guaranteed only inside one partition. Use a key (like order ID) so related events stay in order.
  7. 7
    Version events
    Add fields, do not remove them. Old consumers must keep working while new ones roll out.
  8. 8
    Trace it
    Pass a correlation ID through every event so you can follow one customer action across services.
💡The outbox pattern
Saving to the database and publishing an event are two steps, and one can fail. Write the event to an outbox table in the same database transaction, and let a small process publish it. Then you never lose or invent an event.
⚠️Not everything should be an event
When the user needs an answer right now ("is this seat free?"), a plain request and response is simpler and clearer. Use events for things that can happen after.

08Key Terms to Know

TermMeaning in easy words
EventA record that something happened, named in the past tense
Producer / publisherThe part that creates and sends events
Consumer / subscriberThe part that receives events and reacts
Event brokerThe middle system that stores and delivers events (Kafka, RabbitMQ, SNS/SQS)
TopicA named channel for one kind of event
CommandA request that asks one service to do something. Not a fact
ChoreographyServices react to each other's events with no central boss
OrchestrationA central coordinator directs the steps
Eventual consistencyParts may be out of date for a short time, then catch up
Idempotent consumerHandling the same event twice has the same result as once
Dead letter queueA place for events that keep failing, so they can be checked later

09Pros, Cons and Trade-offs

✅ Pros
  • Loose coupling between services
  • One failing consumer does not stop the others
  • Fast responses for the user
  • Easy to add new reactions
  • Scales and buffers sudden bursts
  • Natural audit trail of what happened
⚠️ Cons
  • Harder to follow the whole flow
  • Eventual consistency, not instant
  • Duplicates and ordering need care
  • Debugging across services is harder
  • The broker is one more system to run
  • Event shapes are a contract that is hard to change

Trade-offs

ChoiceWe gainWe lose
Events instead of direct callsIndependence and failure isolationA clear step-by-step flow and instant answers
ChoreographyNo central bottleneck, very flexibleHard to see and change the whole flow
OrchestrationOne place that shows the flowA central part that knows many services
Fat events (carry all data)Consumers never call backBigger messages and a stronger contract
Thin events (just an ID)Small and simpleConsumers must call back for details
At-least-once deliveryNo lost eventsConsumers must handle duplicates

10Common Problems and Mistakes

Common mistakes

  1. Hidden request-response. A service publishes an event and then waits for the answer event. This is a slow call with extra steps.
  2. Ignoring duplicates. Retries deliver the same event twice and a customer is charged twice.
  3. Assuming global order. Events on different partitions can arrive in any order.
  4. Losing events. Saving data and publishing without an outbox can leave them out of step.
  5. Changing an event shape suddenly. Removing a field breaks every old consumer.
  6. Poison messages. One bad event retried forever blocks the queue.
  7. Event spaghetti. Services react to each other in long chains no one can draw anymore.

Things to watch

🐌Consumer lag
How far a consumer is behind the newest event. A growing lag means it is too slow.
☠️Dead letter queue size
A growing dead letter queue means events keep failing.
🔁Retry storms
Many retries at once can overload a recovering service. Use backoff.
🧭Tracing
Pass a correlation ID so a single action can be followed from start to end.

11Real-World Examples

🚗Uber
Trip, driver location and payment updates flow as events between many services.
📺Netflix
Uses Kafka-based event streams for data pipelines and real-time monitoring.
💼LinkedIn
Created Kafka to move activity events (views, clicks, messages) between systems.
🛍️E-commerce
Order placed leads to payment, stock, shipping and email, each reacting on its own.
🏦Banks
Transaction events feed fraud checks, alerts and statements in near real time.
☁️Cloud platforms
Services like Amazon EventBridge and Azure Event Grid route events between apps and functions.
📝Note
Companies change their tools over time. Treat these as examples of the style, not a permanent list.
Mini case: order with a failing email service
🛒Order servicesaves, publishes, replies
→↓OrderPlaced
📬Brokerkeeps the event
⇢⇣later
✉️Email servicewas down, now back
The customer is not affected. The email event waits, and is sent when the email service recovers.

12Related Topics to Read Next

Message Queues→

The simplest way to carry events to workers.

Pub/Sub→

Lets one event reach many subscribers.

Message Brokers→

The systems that store and deliver events.

Delivery Semantics→

At-most-once, at-least-once and exactly-once explained.

Dead Letter Queues→

Where events that keep failing are parked.

CQRS→

Often uses events to keep read models up to date.

Event Sourcing→

Stores events as the source of truth.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: services communicate by publishing and reacting to events through a broker.
  • ✔Event: a past-tense fact (OrderPlaced). Command: a request to one receiver.
  • ✔Gain: loose coupling, failure isolation, fast replies, easy to add features.
  • ✔Cost: eventual consistency, harder tracing, duplicates and ordering.
  • ✔Rules: idempotent consumers, retries with backoff, a dead letter queue, versioned events.
  • ✔Order: only inside one partition. Use a key like the order ID.
  • ✔Safe publishing: outbox pattern, so data and event never go out of step.
  • ✔One line: “Say what happened, and let everyone who cares react on their own.”
← Previous
Serverless
Next →
Peer-to-Peer (P2P)