Event-driven architecture in system design
In an event-driven architecture, services announce facts that have happened, such as OrderPlaced or PaymentFailed, and other services react to those events on their own schedule instead of being called directly. The producer does not know or wait for its consumers, so new features can subscribe without changing it. The price is eventual consistency, harder debugging and the need for reliable publishing, idempotent consumers and careful event design.
By Evin JohnPublished 7 min read
1. What event-driven architecture is
In a request-driven design, the order service calls inventory, then email, then analytics, and has to know about all three. In an event-driven design, the order service records the order and publishes OrderPlaced. Inventory, email and analytics subscribe and do their part. If tomorrow a loyalty service needs to award points, it subscribes too; the order service does not change. The events travel through a broker, typically a pub/sub system or a log like Kafka; message queues vs pub/sub covers the plumbing.
2. Why interviewers ask about it
Event-driven designs appear whenever one action triggers several follow-ups, whenever data must be copied into search indexes or analytics, and in most microservices discussions. Interviewers want to see that you know where events help (decoupling, fan-out, absorbing load) and where they hurt (a user waiting on a result, consistency across services), and that you can make publishing and consuming reliable.
3. Events, commands and four common styles
A command asks a specific service to do something and can be refused (ReserveStock). An event states something that already happened and cannot be refused (StockReserved). Name events in the past tense, and send commands to one owner, events to anyone interested.
| Style | What the event carries | Strength | Cost |
|---|---|---|---|
| Event notification | Just the fact and an ID: OrderPlaced {order_id} | Small events, loose coupling | Consumers call back for details, which recouples them at runtime |
| Event-carried state transfer | The data consumers need: items, totals, address | Consumers keep their own copy and work even if the producer is down | Bigger events; copies lag; schema changes ripple |
| Event sourcing | Every change, stored as the source of truth; current state is rebuilt from the events | Full history and audit; replay to rebuild or fix views | Hard to query directly; schema evolution of old events; needs snapshots |
| CQRS | Writes go to one model; events update separate read models shaped for queries | Each read model can have its own store and indexes | Read models lag; more moving parts |
4. Publishing reliably: the outbox
The classic bug: the service saves the order to its database, then publishes OrderPlaced to the broker. If it crashes between the two, the order exists but nobody hears about it. Publishing first is no better. This is the dual-write problem. Two standard fixes: the transactional outbox, where the event is written to an outbox table in the same database transaction as the state change and a relay publishes it afterwards; or change data capture, where a connector reads the database's replication log and turns committed changes into events (see replication).
import json, sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE orders (id TEXT PRIMARY KEY, total INT);
CREATE TABLE outbox (seq INTEGER PRIMARY KEY AUTOINCREMENT, topic TEXT,
key TEXT, payload TEXT, published INT DEFAULT 0);
""")
def place_order(order_id: str, total: int) -> None:
with db: # one local transaction: both rows commit, or neither does
db.execute("INSERT INTO orders VALUES (?, ?)", (order_id, total))
db.execute("INSERT INTO outbox (topic, key, payload) VALUES (?, ?, ?)",
("orders", order_id,
json.dumps({"type": "OrderPlaced", "id": order_id, "total": total})))
def relay(publish) -> int:
rows = db.execute("SELECT seq, topic, key, payload FROM outbox"
" WHERE published = 0 ORDER BY seq").fetchall()
for seq, topic, key, payload in rows:
publish(topic, key, payload) # may repeat after a crash: consumers dedupe
with db:
db.execute("UPDATE outbox SET published = 1 WHERE seq = ?", (seq,))
return len(rows)
sent = []
place_order("o-1", 120)
place_order("o-2", 75)
relay(lambda t, k, p: sent.append((t, k))) # 2
relay(lambda t, k, p: sent.append((t, k))) # 0: nothing left to sendThe relay can publish an event and crash before marking it, so the event goes out twice. That is acceptable because consumers must handle duplicates anyway. Ordering is kept per key if the relay publishes in sequence order and the broker partitions by the same key.
5. Consuming reliably
- Idempotency. Record processed event IDs, or make the effect an upsert keyed by the event's entity and version, so a redelivered event changes nothing.
- Order per entity. Partition by entity ID so all events for one order arrive in order. Include a version number so a consumer can ignore an older event that arrives late.
- Retries and dead letters. Retry transient failures with backoff; park events that keep failing in a dead-letter queue and alert.
- Replays. A log-based broker lets a new consumer start from the beginning to build its state, or an existing one rebuild after a bug fix, within the retention period.
6. Choreography vs orchestration
| Choreography | Orchestration | |
|---|---|---|
| How it works | Each service reacts to events and emits its own: OrderPlaced, then StockReserved, then PaymentCaptured | A coordinator sends commands to each service and tracks the state of the process |
| Strength | No central component; services stay independent | The whole flow is visible in one place; easier to change and debug |
| Weakness | Hard to see the full flow; cycles and implicit dependencies creep in | The orchestrator becomes a critical service and can grow into a god object |
| Failure handling | Each service emits failure events; others compensate | The orchestrator issues compensating commands (release stock, refund) |
| Fits | Short flows with few steps | Long or business-critical flows with many steps and timeouts |
Either way, cross-service work has no global transaction. Each step commits locally, and a failure later triggers compensating actions that undo earlier steps in business terms. Design those compensations up front: a captured payment is undone by a refund, not by a rollback.
7. Event design and schema evolution
- Include an event ID, type, entity ID, version and timestamp in every event.
- Make changes backward compatible. Add optional fields; do not rename or remove fields consumers rely on. Introduce a new event type for breaking changes.
- Use a schema format and registry (for example Avro, Protobuf or JSON Schema with a registry) so producers cannot publish events consumers will fail to read.
- Keep internal details out. Events are a public contract; publish business facts, not table rows.
8. How it shows up in common prompts
| Prompt | Events | Note |
|---|---|---|
| Notification system | Domain events trigger notifications | Preferences and channel services subscribe; retries per channel |
| Payment system | PaymentCaptured, RefundIssued | The ledger write stays synchronous; downstream steps react |
| Ticket booking | SeatHeld, HoldExpired, TicketIssued | Holds expire through timed events; issuing a ticket is a saga with payment |
| Search autocomplete | Query events feed aggregation | A log lets several pipelines read the same stream |
| PostCreated fans out to timelines | Fan-out workers consume and write to followers' feeds |
9. Mistakes to avoid
- Events for everything. If the user is waiting for the result, a synchronous call is usually simpler.
- Dual writes. Saving state and publishing separately loses events on crashes; use an outbox or CDC.
- Assuming exactly-once. Consumers must be idempotent.
- Commands disguised as events. "SendEmailRequested" sent to one service is a command; treat it as one.
- Breaking schemas. Renaming a field breaks every consumer you forgot existed.
- Event sourcing by default. It is a big commitment; use it where history and audit are core requirements.
10. How to talk about it in the interview
- Mark which steps are synchronous (the user waits) and which react to events.
- Say how events are published reliably: outbox or CDC.
- Give the partition key, the ordering guarantee and how consumers dedupe.
- Pick choreography or orchestration for multi-step flows, and describe one compensation.
Fictional example
- Interviewer
- A customer places a food order. Walk me through the services.
- Candidate
- The order API authorizes the card synchronously because the customer waits for confirmation. It then saves the order and an OrderPlaced row in its outbox in one transaction.
- Candidate
- The relay publishes to a topic partitioned by order ID. The restaurant service, the courier dispatch service and notifications each consume it. Because the flow has timeouts, like the restaurant not accepting within five minutes, I'd run it with an orchestrator that tracks each order's state.
- Interviewer
- The restaurant rejects the order. Then what?
- Candidate
- The orchestrator issues compensations: cancel the courier request and void the card authorization, then emits OrderCancelled so notifications tell the customer. Every handler dedupes by order ID and step.
Practicing with Natively
Event-driven answers are long chains of "and then", and the weak link is usually the failure path. Practicing with Natively, the mock interview is transcribed and talking points can surface on each follow-up, so when you review you can see whether you covered the outbox, duplicates and compensations. It can read a screenshot of a flow diagram or prompt and explain it, and the transcript and notes are kept afterwards.
Questions people ask
What is event-driven architecture?
A design where services publish facts that have happened, such as OrderPlaced, and other services subscribe and react on their own schedule. The producer does not call or wait for consumers, so new consumers can be added without changing it.
What is the transactional outbox pattern?
Writing an event to an outbox table in the same database transaction as the state change, then having a relay publish outbox rows to the broker. It prevents losing events when a service crashes between saving data and publishing.
What is the difference between choreography and orchestration?
In choreography each service reacts to events and emits its own, with no central controller. In orchestration a coordinator sends commands to each service and tracks the process, which makes long flows easier to follow and change.
Is event sourcing the same as event-driven architecture?
No. Event sourcing stores every change as an event and rebuilds state from them. Event-driven architecture only means services communicate through events; most event-driven systems store current state normally.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
