
Event-driven architecture is a way of building software where a part of the system announces what just happened, such as "order placed", and moves on. A go-between holds the announcement, and other parts react to it later, in their own time. The part that announced never waits for them and never calls them by name.
In this post we start at a busy dosa restaurant's ticket rail. Then we take the shop app from the observer pattern post, watch a slow mail server make every order wait, and fix it with a tiny event bus in plain Python: a queue and a worker thread. We compare two of the event patterns Martin Fowler names, notification and state transfer. Then we look at what events cost: data that's briefly out of date, bugs that are harder to trace, and events that arrive twice. We finish with when not to use it, and the beginner mistake that emails a customer about an order that was never saved.
A few words first. An event is a record of something that happened, such as "order 101 was placed". The part that announces it is the producer (or publisher), and the parts that react are consumers (or listeners, or subscribers). The go-between that holds events and hands them on is the broker. A queue is a line: the first thing put in is the first thing taken out. A thread is a second line of work inside the same program. In standard Python, threads take turns running Python code, but while one thread waits, say for a slow network, another gets on with its work, so the two overlap. A worker is a thread (or program) whose only job is to take things off a queue and deal with them.
Key takeaways
- In event-driven architecture, a service says what happened and carries on. Other services react when the event reaches them.
- A broker in the middle holds each event until a worker takes it, so the order service no longer waits for slow jobs such as email.
- Two of Fowler's event patterns differ in what the event carries. Event notification keeps it small, often just an id, so listeners call back for the details. Event-carried state transfer carries the data itself, so they don't have to.
- The costs: for a moment the parts disagree (eventual consistency), the flow is harder to follow and debug, and the same event can arrive twice, so listeners must be safe to run again (idempotent).
- Save first, then publish. Publishing first can confirm an order that was never saved.
- Skip it for a small app with one database, and for any step that must finish before you reply.
- Our example uses Python's
queue.Queueinside one program. Real systems use a broker, a separate service that keeps events safe when your program stops.
What is event-driven architecture in simple words?
Think of a busy dosa restaurant at lunchtime. A waiter takes your order, writes it on a ticket, clips the ticket to the rail by the kitchen window, and goes straight back to the next table. He doesn't stand at the stove until your dosa is ready. Whichever cook is free takes the next ticket off the rail and makes everything on it. Each ticket goes to one cook. The waiter and the cooks never wait for each other. The rail sits between them.
Software can work the same way. In our shop app, the order service is the waiter, "order placed" is the ticket, and the jobs that follow, such as sending a confirmation email and taking the items out of stock, are the dishes on the ticket. The rail is the broker, and the cook is the worker that takes each event and does every job on it. The order service saves the order, clips an event to the rail, and tells the customer "done". The email and the stock happen a moment later.
The picture also shows the catches, which we'll meet properly later. For a minute your table has ordered but the kitchen hasn't started. And if the same ticket gets clipped twice, two dosas come out.
What problem does event-driven architecture solve?
In the last post, the order service told one Event, and the event called each listener in turn: send_email, then stock.reserve. That kept the order service from knowing who listens. But place still ran every listener itself, one after another, and only returned when they had all finished.
Now the mail server is slow today. Here are the same two listeners, with send_email taking 2 seconds:
# listeners.py
import time
def send_email(order):
time.sleep(2) # pretend the mail server is slow today
print(f"Email to {order['email']}: order {order['id']} confirmed")
class Stock:
def __init__(self, counts):
self.counts = counts
def reserve(self, order):
self.counts[order["item"]] -= order["qty"]
print(f"Stock: {self.counts[order['item']]} {order['item']} left")
time.sleep(2) just pauses for 2 seconds, standing in for a slow network. Put a timer around the order in last post's main.py. time.perf_counter() reads a stopwatch, so the difference between two readings is how long the code in between took:
import time
start = time.perf_counter()
shop.place({"id": 101, "email": "asha@example.com", "item": "dosa-mix", "qty": 2})
print(f"Order 101 placed in {time.perf_counter() - start:.1f} s")
Run it with last post's events.py and orders.py:
Email to asha@example.com: order 101 confirmed
Stock: 8 dosa-mix left
Order 101 placed in 2.0 s
The customer stares at a spinning wheel for 2 seconds, waiting for an email they'll read later anyway. Add reward points, a message to the warehouse and a sales dashboard, and every slow listener adds its time to every checkout. If the mail server hangs completely, checkout hangs with it. None of these jobs needs to finish before the customer hears "order placed". They only need to happen soon.
How does event-driven architecture work?
AWS (Amazon Web Services, the cloud company) defines it in one sentence: "An event-driven architecture uses events to trigger and communicate between decoupled services and is common in modern applications built with microservices." Decoupled means the parts don't depend on each other, and microservices are small separate programs that each own one job, as in our monolith vs microservices post. AWS names three parts: "A producer publishes an event to the router, which filters and pushes the events to consumers." Their router is what we're calling the broker.

So place changes in one small way. Instead of calling the listeners, it puts the event in a queue, and putting something in a queue takes almost no time. A separate worker takes events off the queue and calls the listeners. The order service replies the moment the event is in the queue. That's why it no longer waits: the slow work still happens, just not while the customer is waiting.
How do you build a tiny event bus in Python?
Python's standard library (the tools that come with Python) has the queue we need. The queue docs describe it: "It is especially useful in threaded programming when information must be exchanged safely between multiple threads." Here the order service puts events in from the main thread (the one your program starts in), and one worker thread takes them out. We'll call the whole thing an event bus, a common name for the piece that carries events from producers to consumers:
# bus.py
import logging
import queue
import threading
log = logging.getLogger(__name__)
class EventBus:
"""Takes events now and hands them to the listeners later, on a worker thread."""
def __init__(self):
self.listeners = {} # event name -> list of functions
self.inbox = queue.Queue()
threading.Thread(target=self._work, daemon=True).start()
def subscribe(self, name, listener):
self.listeners.setdefault(name, []).append(listener)
def publish(self, name, event):
self.inbox.put((name, event)) # returns at once: nobody has been called yet
def wait(self):
self.inbox.join() # block until every event so far is handled
def _work(self):
while True:
name, event = self.inbox.get()
for listener in list(self.listeners.get(name, [])):
try:
listener(event)
except Exception as error:
who = getattr(listener, "__name__", repr(listener))
log.error("%s failed: %r", who, error)
self.inbox.task_done()
subscribeadds a listener for one event name, such as"order_placed".setdefaultstarts an empty list the first time a name is seen.publishonly puts the event name and the event in the queue. No listener runs here, which is the whole point.- The constructor (
__init__, which runs when you writeEventBus()) starts one worker thread that runs_workforever.inbox.get()waits until an event is in the queue, takes it out, and the loop calls every listener for that name. Thetryaround each call is the lesson from the observer post: one broken listener mustn't stop the others. task_done()tells the queue that this event is finished, andwait()callsjoin(), which the docs describe as: "Blocks until all items in the queue have been gotten and processed." Blocks means it doesn't return until then.daemon=Truemarks the worker as a background thread that won't keep the program running on its own. Try it 2 below shows what that means for an event the worker hasn't finished.
The order service now gets the bus handed in (dependency injection again), saves the order, and publishes:
# orders.py
class OrderService:
def __init__(self, bus):
self.orders = {}
self.bus = bus
def place(self, order):
self.orders[order["id"]] = order # 1. save it (a real app writes to its database)
self.bus.publish("order_placed", order) # 2. then say it happened
And main.py wires it up, as before, and times the order:
# main.py
import time
from bus import EventBus
from listeners import Stock, send_email
from orders import OrderService
bus = EventBus()
stock = Stock({"dosa-mix": 10})
bus.subscribe("order_placed", send_email)
bus.subscribe("order_placed", stock.reserve)
shop = OrderService(bus)
start = time.perf_counter()
shop.place({"id": 101, "email": "asha@example.com", "item": "dosa-mix", "qty": 2})
print(f"Order 101 placed in {time.perf_counter() - start:.1f} s")
bus.wait() # only so this demo doesn't quit before the worker is done
Put the four files in one folder (listeners.py, bus.py, orders.py and main.py) and run python main.py:
Order 101 placed in 0.0 s
Email to asha@example.com: order 101 confirmed
Stock: 8 dosa-mix left
Look at which line comes first. The order is placed in well under a tenth of a second, and the email and the stock follow 2 seconds later. The customer gets their answer straight away. The mail server is as slow as before; it's no longer in the customer's way.
Notice that the stock line also came 2 seconds late. Our one worker runs the listeners one after another, so a slow email still holds up the stock, and a mail server that hangs completely would stop the worker for every later order too. Checkout keeps working, but nothing behind it moves.
Fixing that needs one more fact about queues: each item goes to one taker, like a ticket that only one cook can pick up. If two workers share one queue, each event reaches only one of them. So when separate services, such as email and stock, must each see every event, each one needs its own copy. Google Cloud Pub/Sub does this with one subscription (a named stream of copies) for each service, all fed from one topic (the named channel the producer publishes to): "When a topic has multiple subscriptions, then every message has to be sent to a subscriber receiving messages on behalf of each subscription." And to share out one service's work: "You can also attach multiple subscribers to each subscription and get a load-balanced subset of messages for each subscriber." In plain words, each worker gets a share. With plain queues, the same idea is one queue for each consumer, with as many workers on each queue as it needs (our own note). Either way, a slow email no longer holds up the stock.
Be clear about what this is. Our bus is a teaching model: one worker, and the queue lives in the memory of one program. If that program stops, every event still waiting in the queue is gone.
Real systems put a message broker in the middle instead: a separate service, such as Amazon SQS (Simple Queue Service) or Google Cloud Pub/Sub, that the producer and the consumers talk to over the network. The SQS docs, for example, say: "Amazon SQS stores copies of your messages on multiple servers for redundancy and high availability." (Redundancy means keeping spare copies, and high availability means it keeps working when one server fails.) Some promises change on the way. The SQS docs on standard queues: "Standard queues ensure at-least-once message delivery, but due to the highly distributed architecture, more than one copy of a message might be delivered, and messages may occasionally arrive out of order." So the first-in, first-out line of our queue.Queue isn't a given out there. The idea is the same as ours; the broker keeps the events safe and lets the consumers run as separate programs on other machines. Message queues and workers get a post of their own next.
Event notification vs event-carried state transfer: what's the difference?
Martin Fowler, a software author whose site collects many of these patterns, wrote a short article after a meeting where his colleagues found that people mean different things by "events". He names several patterns, and two of them differ in what an event carries. (In the last post we met his event notification as telling others what changed without caring about the answer: "A key element of event notification is that the source system doesn't really care much about the response." Here the question is how much the event carries.)
Event notification keeps the event small, often just an id. Fowler: "An event need not carry much data on it, often just some id information and a link back to the sender that can be queried for more information." In our shop, that's an event with only the order's id, so each listener has to ask the order service for the rest:
# notification: the event carries only the order's id
# in orders.py, inside place():
self.bus.publish("order_placed", {"id": order["id"]})
# ...so a listener has to ask the order service for the rest
def send_email(event):
order = shop.orders[event["id"]] # in a real system, a call over the network
print(f"Email to {order['email']}: order {order['id']} confirmed")
Event-carried state transfer puts the data in the event. Fowler: "This pattern shows up when you want to update clients of a system in such a way that they don't need to contact the source system in order to do further work." (State is the data as it is right now, such as the order's items and email address.) Our orders.py already does this: it publishes the whole order, so send_email and stock.reserve never call back.

Each has a price. With notification, every listener calls the order service back, so the order service has to be up and answering. With state transfer, Fowler writes, "An obvious down-side of this pattern is that there's lots of data schlepped around and lots of copies." (Schlepped is a slang word for carried.) What you gain: "We reduce latency, as there's no remote call required to access customer information." (His example is a service that holds customer details.) Latency is waiting time, and a remote call is a request to another program over the network. Google Cloud's guide puts the same choice simply: "Events can either carry a state (such as the price of an item or a delivery address) or events can be identifiers (a notification that an order was received or shipped, for example)."
A rule of thumb (our own): if most listeners would call back for the same few fields (the named pieces of data in an event, such as email or qty), put those fields in the event. If the data is big, or changes so often that a copy would be out of date before anyone reads it, send the id.
What are the downsides of event-driven architecture?
Not waiting is the gain. Here's what it costs.
1. For a moment, the parts disagree. Change the end of main.py to look at the stock straight after placing the order:
shop.place({"id": 101, "email": "asha@example.com", "item": "dosa-mix", "qty": 2})
print("Right after place:", stock.counts["dosa-mix"])
bus.wait()
print("After the worker:", stock.counts["dosa-mix"])
Right after place: 10
Email to asha@example.com: order 101 confirmed
Stock: 8 dosa-mix left
After the worker: 8
For 2 seconds, the order exists but the stock still says 10. This is called eventual consistency: the parts of the system will agree, but not at every instant. In their article on microservices, James Lewis and Martin Fowler describe services that coordinate without one shared transaction (one all-or-nothing database change), "with explicit recognition that consistency may only be eventual consistency and problems are dealt with by compensating operations." A compensating operation is a later step that undoes a mistake, such as a refund. They also point out that this is how many businesses already work: "Often businesses handle a degree of inconsistency in order to respond quickly to demand, while having some kind of reversal process to deal with mistakes." Our restaurant does it too: your table has ordered, and the kitchen hasn't started yet.
2. The flow is harder to follow, and harder to debug. The observer post warned that you can't see who reacts by reading place. With events between services it gets worse. Fowler: "The problem is that it can be hard to see such a flow as it's not explicit in any program text. Often the only way to figure out this flow is from monitoring a live system." Google Cloud says the same: "An event-driven architecture supports dynamic tracking using monitoring services, but not static tracking using code analysis." In plain words, you find out what happens by watching the running system, not by reading the code. Errors move too. If send_email fails now, it fails on the worker, 2 seconds after place has already told the customer "done". Nobody is there to show the error to, which is why our bus writes it to the log (a record of what the program did, for someone to read later).
3. The same event can arrive twice. Many brokers, including Amazon SQS standard queues (quoted above) and Google Cloud Pub/Sub by default, promise at-least-once delivery: every event arrives, but some arrive more than once. Google Cloud's Pub/Sub docs: "By default, Pub/Sub provides at-least-once delivery of messages to subscribers. That means messages can be delivered multiple times, even if they were acknowledged." (A consumer acknowledges a message by telling the broker it has finished with it.) How can a finished message come back? The SQS docs give one way: a server holding a copy may be unavailable when the consumer deletes the message (deleting is how SQS consumers say they've finished). "If this occurs, the copy of the message isn't deleted on the server that is unavailable, and you might get that message copy again when you receive messages." Our in-memory bus never does this by itself, so we fake it by publishing twice:
order = {"id": 101, "email": "asha@example.com", "item": "dosa-mix", "qty": 2}
bus.publish("order_placed", order)
bus.publish("order_placed", order) # the same event, delivered a second time
bus.wait()
Email to asha@example.com: order 101 confirmed
Stock: 8 dosa-mix left
Email to asha@example.com: order 101 confirmed
Stock: 6 dosa-mix left
Asha gets two emails, and the stock drops by 4 for an order of 2. The AWS SQS docs give the fix in one line: "Design your applications to be idempotent (they should not be affected adversely when processing the same message more than once)." An idempotent listener gives the same result whether it runs once or five times. How to build one is post #12 in this series, Idempotency. Try it 3 below has a first taste.
When should you not use event-driven architecture?
- A small app with one database. If the whole shop is one program with one database, a broker is one more service to set up, watch, pay for and debug, plus all three costs above. A direct call, or the in-program observer from the last post, does the job. If one job is slow, try making that one job faster first.
- A step that must finish before you reply. Charging the card has to succeed before the customer hears "order placed". So does checking that there's stock, if you want to refuse orders when it runs out: with stock as an event, two customers can both be told "done" for the last packet, as the 2-second gap above shows. Call those steps directly, wait for the answer, and use events only for the "by the way" jobs.
Fowler warns about a related habit, an event used as what he calls a "passive-aggressive command": "This happens when the source system expects the recipient to carry out an action, and ought to use a command message to show that intention, but styles the message as an event instead." (A command asks another service to do something, such as "reserve 2 packets"; an event only says what already happened.) If you need it done, say so and wait. Don't announce it and hope.
What mistake do beginners make with events?
Publishing the event before the work is saved. It looks harmless to announce first and save second. Here's that version, on a day the database is down:
# orders_wrong.py
class OrderService:
def __init__(self, bus):
self.orders = {}
self.bus = bus
def save(self, order):
raise ConnectionError("database is down") # today, saving fails
def place(self, order):
self.bus.publish("order_placed", order) # say it happened...
self.save(order) # ...then try to save it
In main.py, import OrderService from orders_wrong, and tell the customer if the order fails:
try:
shop.place({"id": 101, "email": "asha@example.com", "item": "dosa-mix", "qty": 2})
except ConnectionError as error:
print("Order failed:", error)
bus.wait()
Order failed: database is down
Email to asha@example.com: order 101 confirmed
Stock: 8 dosa-mix left
The customer is told the order failed, and then gets an email saying it's confirmed. The stock went down for an order that doesn't exist. The event was already in the queue when saving failed, and an event can't be taken back: the listeners believe it.
The fix is the order in our orders.py: save first, then publish. An event should be a record of something that really happened. Saving first still leaves a smaller gap: if the program crashes between the save and the publish, the order is saved but the event is lost. Real systems have ways to close that gap too, but they're beyond this post.
1) The shop adds reward points, as in the last post: a new add_points listener. Which files change? Does place get any slower?
2) Delete the last line of main.py, bus.wait(), and run it. What does it print, and why?
3) Change Stock.reserve so that getting the same order twice takes the stock out only once. Then run the duplicate example again. What does it print?
Show the answers
1) Only listeners.py (the new function) and main.py (import it, and one more bus.subscribe("order_placed", add_points) line). bus.py and orders.py don't change. And no, place doesn't get slower: it still only puts one event in the queue, however many listeners there are. The worker takes a little longer.
2) Only Order 101 placed in 0.0 s. The main program reaches its end while the worker is still in its 2-second wait, and the worker is a daemon thread. The threading docs: "The significance of this flag is that the entire Python program exits when only daemon threads are left." So the program quits, and the event that was still being handled is lost: no email, no stock change. That's exactly why real systems keep events in a broker, outside the program, until a consumer has finished with them.
3) Keep the ids of orders already reserved, and skip any you've seen:
class Stock:
def __init__(self, counts):
self.counts = counts
self.done = set() # ids of orders already taken out of stock
def reserve(self, order):
if order["id"] in self.done:
return
self.done.add(order["id"])
self.counts[order["item"]] -= order["qty"]
print(f"Stock: {self.counts[order['item']]} {order['item']} left")
Email to asha@example.com: order 101 confirmed
Stock: 8 dosa-mix left
Email to asha@example.com: order 101 confirmed
The stock is right now, 8 not 6. Asha still gets two emails, because send_email needs the same care. And our done set lives in memory, so it's forgotten when the program restarts. Doing this properly is post #12, Idempotency.
Questions people ask
What is event-driven architecture in simple words?
Parts of a system tell each other what happened ("order placed") instead of asking each other to do things. A go-between, the broker, holds each event, and the parts that care react to it later. The part that sent the event doesn't wait for them. It's like a waiter clipping a ticket to the kitchen rail and going back to the tables.
What is the difference between the observer pattern and event-driven architecture?
The observer pattern works inside one program: the subject keeps a list of listeners and calls them itself, usually straight away. Event-driven architecture puts a broker between the parts, so the event can be handled later, often by separate programs on other machines, and the sender doesn't wait.
What is the difference between event notification and event-carried state transfer?
An event notification keeps the event small, often just an id, such as "order 101 was placed", and listeners call back to get the details. Event-carried state transfer puts the data in the event (the email, the item, the quantity), so listeners don't need to call back. The first sends less data; the second means fewer calls back and less waiting.
Is event-driven architecture the same as event sourcing?
No. Fowler lists event sourcing as a separate pattern: "The core idea of event sourcing is that whenever we make a change to the state of a system, we record that state change as an event, and we can confidently rebuild the system state by reprocessing the events at any time in the future." You can send events between services without storing every change that way. Event sourcing gets its own post later in this series.
Keep going
- Previous in this System Design series: Observer pattern, the same idea inside one program, where the subject calls each listener itself.
- Next: Message queues and workers, where the broker and the worker from this post get a closer look.
- Why services get split up in the first place: Monolith vs microservices.
Checked on 2 November 2026 against the 10 sources below.
Sources
- Martin Fowler: What do you mean by "Event-Driven"? (2017), event notification, event-carried state transfer, event sourcing
- James Lewis and Martin Fowler: Microservices (2014), eventual consistency
- AWS: What is an Event-Driven Architecture?
- AWS documentation: Amazon SQS at-least-once delivery
- AWS documentation: Amazon SQS standard queues (duplicates and order)
- Google Cloud documentation: Event-driven architectures (Eventarc)
- Google Cloud documentation: Best practices to subscribe to a Pub/Sub topic (duplicate deliveries)
- Google Cloud documentation: Overview of the Pub/Sub service (topics and subscriptions)
- Python documentation: queue: a synchronized queue class (
Queue.join,task_done) - Python documentation: threading (the GIL and daemon threads)
Every Python sample in this post was run in Python 3.13 before publishing.