Event-Driven Architecture — System Design

Event-driven architecture: a producer publishes an event (a fact in the past tense, such as order.paid) to a broker without knowing its consumers (loose…

After Budi pays, the order service calls three services one by one: update the tickets left, send the e-ticket, add points. Budi waits until all three are done. If just one is down, the checkout fails, even though his card has already been charged.

The head of the neighbourhood doesn't work like that. When the water supply is about to go off, he just writes in the neighbourhood WhatsApp group: "The water supply is off tomorrow at 8." He doesn't phone every house one by one and doesn't wait for answers. Each house reacts on its own: one fills buckets, another buys bottled water. A new resident just joins the group, and nothing changes for the announcer. Someone whose phone is off reads it later.

Building a system this way is called event-driven architecture: services keep each other informed through events, records that something has already happened. Announce the fact, let whoever cares react.

Commands and events

There are two ways for one service to tell another something:

Command Event
Form an order: "SendETicket #1001" a fact, in the past tense: order.paid (or OrderPlaced)
Addressed to one specific receiver whoever subscribes: 0, 1 or 10 of them
The sender waits for the answer, and the command can be refused doesn't wait, doesn't know who is listening
If the receiver is down the sender fails too the event waits in the broker

The terms: the producer (or publisher) is whoever publishes the event, a consumer (or subscriber) subscribes and reacts, and the broker sits in between, storing and passing events on, for example Kafka, RabbitMQ or Redis Streams. Because the producer doesn't know its consumers, the two are loosely coupled: they can be changed, deployed and fail independently.

Command style: call them one by one

Budi pays for order #1001: 2 Archipelago Concert tickets, $150. With commands, order calls concert, email, then points in turn and waits for each (example model numbers):

ms What happens
10 order saves payment #1001
50 concert done: 9,998 tickets left
550 email done: e-ticket #1001 sent
580 points done: Budi has 150 points (1 point per $1)
580 Budi gets 200: payment successful

Now email is down. order waits until its 2,000 ms timeout, then gives up: at ms 2,050 Budi gets 503 Service Unavailable. Yet his card has been charged, the tickets left have gone down, and his points haven't arrived. One dead service brings checkout down, and leaves the data half done.

Event style: publish once

With events, order saves the payment, publishes order.paid to the broker (5 ms), and answers Budi right away. Each subscriber gets its own copy of the event and works on its own. In this model the queue in front of concert lags 250 ms:

ms What happens
10 order saves payment #1001
15 order publishes order.paid (evt-1001)
15 Budi gets 200: payment successful
45 points done: Budi has 150 points
305 concert done: 9,998 tickets left
515 email done: e-ticket #1001 sent

Budi waits only 15 ms, not 580. And if email is down, Budi still gets 200 at ms 15. The event waits in email's queue in the broker, and the e-ticket goes out as soon as email is back. Want a new feature, say sales analytics? Add a subscriber. Not one line of order changes.

How this differs from the Message Queue lesson: on a queue, one message is taken by one worker. With publish/subscribe, every subscriber gets its own copy, so concert, email and points all receive evt-1001.

// TicketTune: Budi pays for order #1001, event style (an example model)
const idempotent = false; // consumers remember the event ids they have processed
const concertLag = 250; // ms of queue in front of the concert consumer
let emailUp = true;
let ticketsLeft = 10000;
let budiPoints = 0;
let eTickets = 0;
const emailQueue = [];
const schedule = []; // a virtual clock: [ms, function]
const later = (ms, fn) => schedule.push([ms, fn]);
const log = (ms, text) => console.log(`[${ms} ms] ${text}`);
const subscribers = [];

function subscribe(name, ms, handler) {
  subscribers.push({ name, ms, handler, seen: new Set() });
}

function run(s, event, t) {
  if (idempotent && s.seen.has(event.id)) return log(t, `${s.name}: ${event.id} already processed, skip`);
  s.seen.add(event.id);
  log(t, `${s.name} done: ${s.handler(event)}`);
}

function publish(event, t) {
  for (const s of subscribers) {
    if (s.name === "email" && !emailUp) {
      emailQueue.push(event);
      log(t, `email down: ${event.id} waits in the email queue`);
    } else {
      later(t + s.ms, () => run(s, event, t + s.ms));
    }
  }
}

subscribe("concert", concertLag + 40, (e) => `tickets left ${(ticketsLeft -= e.qty)}`);
subscribe("email", 500, (e) => `e-ticket #${e.orderId} sent (${++eTickets})`);
subscribe("points", 30, (e) => `Budi's points ${(budiPoints += e.total)}`);

const event = { type: "order.paid", id: "evt-1001", orderId: 1001, qty: 2, total: 150 };
log(10, "order saves payment #1001");
log(15, `order publishes ${event.type} (${event.id})`);
publish(event, 15);
log(15, "Budi: 200 payment successful");
later(1000, () => log(1000, `Budi refreshes the concert page: ${ticketsLeft} left`));

while (schedule.length) {
  schedule.sort((a, b) => a[0] - b[0]); // earliest first
  schedule.shift()[1]();
}

Eventual consistency: the concert page lags behind

Budi gets "successful" at ms 15, but concert only updates the tickets left at ms 305. In between, the concert page still shows 10,000. Data in different services differs for a while and then becomes the same: that is eventual consistency.

During a ticket war, the queue in front of concert can pile up. With a 1,000 ms lag, concert finishes at ms 1,055, and Budi refreshing at ms 1,000 still sees 10,000 left. So design the UI honestly: "Payment successful, your e-ticket is on its way", not a promise that every number has already changed.

Events can arrive twice

Brokers usually promise at-least-once delivery: an event arrives at least once. If a consumer finishes but its ack is lost, the broker sends the same event again. A naive points consumer adds 150 again: Budi ends up with 300 points, the tickets left drop to 9,996, and the e-ticket is sent twice.

The fix is an idempotent consumer: every event has a unique id (evt-1001), and the consumer stores the ids it has processed. The same event comes again, it is skipped. In the code above, set idempotent to true. It's the same pattern as the Idempotency-Key in the Idempotency lesson, and as the e-ticket consumer in the Message Queue lesson.

The price you pay

🤔 When a command, when an event

Use a command when the sender needs the answer now: checking a seat is still free before paying, charging the card. Use an event when the others can react later: e-tickets, points, analytics, notifications. A small CRUD app with one team doesn't need a broker at all.

⚠️ What makes event-driven systems messy

TL;DR: Event-driven architecture: a producer publishes an event (a fact in the past tense, such as order.paid) to a broker without knowing its consumers (loose coupling), and every subscriber reacts on its own. A command goes to one receiver, and its answer is awaited. TicketTune: with commands Budi waits 580 ms and checkout fails when email is down; with events Budi waits 15 ms, and the event for email waits in the broker. Adding a feature = adding a subscriber; order doesn't change. The price: eventual consistency (the tickets left only change at ms 305), scattered debugging (use correlation IDs and tracing), and duplicates from at-least-once delivery, so consumers must be idempotent (store the event ids already processed).

⚡ Command or event

Meaning: A command is an order to one receiver, and its answer is awaited. An event is a fact that has already happened, such as order.paid. The producer publishes it to a broker without knowing its consumers (loose coupling), and every subscriber reacts on its own.

⚡ Publish once, don't wait

Guess first: the email service is down when Budi pays. In the event style, what does Budi get?

Still 200 at ms 15. The event waits in email's queue in the broker, and the e-ticket goes out as soon as email is back. In the command style, Budi gets 503.

Meaning: Budi waits only 15 ms, not 580 ms.

⚡ A new feature = a new subscriber

Write:

subscribe("concert", concertLag + 40, (e) => `tickets left ${(ticketsLeft -= e.qty)}`);
subscribe("email", 500, (e) => `e-ticket #${e.orderId} sent (${++eTickets})`);
subscribe("points", 30, (e) => `Budi's points ${(budiPoints += e.total)}`);

Meaning: order calls nobody directly; it only does publish. Want sales analytics? Add a subscriber, and not one line of order changes.

⚡ The price you pay

Meaning: Eventual consistency: the concert page still shows 10,000 until concert finishes at ms 305. Brokers are usually at-least-once, so every consumer must be idempotent: store the ids of processed events, and skip one that comes again.

What you will learn