Event-driven architecture: reacting to facts
A fact, not an instruction
Section titled “A fact, not an instruction”An event says that something happened: OrderPlaced, PaymentTaken. It is a fact, so it is named in the past tense, and the part that publishes it does not decide what happens next. Other parts subscribe and react on their own. A command is an instruction to one receiver: ReserveStock, SendWelcomeEmail. It is in the imperative, it is addressed to someone, and it may be refused.
| Event | Command | |
|---|---|---|
| Says | Something happened | Do this |
| Named | In the past: OrderPlaced |
In the imperative: ReserveStock |
| Receivers | Any number, including none | One |
| Sender relies on a reaction | No | Yes |
The line is easy to blur. Martin Fowler calls the trap a passive-aggressive command: the sender expects a particular recipient to carry out an action and ought to use a command to show that, but styles the message as an event instead. A message called SendWelcomeEmail that goes through a broker, with the sender counting on the email being sent, is a command. It may be sent asynchronously, but it is still a command, and treating it as an event hides a dependency.
Mental model. A newspaper does not know who reads it, and it does not ask them to do anything. A purchase order is addressed to one supplier, who must act. Events are the newspaper. Use one when the sender does not care who reacts.
Several things are called event-driven
Section titled “Several things are called event-driven”Fowler reports that when people say “event”, they mean quite different things, and he separates four patterns. This lesson is about the first two.
- Event notification. A system sends an event to say that something changed in its domain, and does not much care about the response. The coupling is low and it is simple to set up. The danger is that a logical flow can run over several notifications and be visible nowhere in the code.
- Event-carried state transfer. The event carries the data that changed, so receivers can keep their own copy and never need to call the sender. This gives resilience and lower latency, at the price of more data moved and more state for the receiver to maintain.
- Event sourcing. The events are the record, and the state is derived from them. This is the event sourcing lesson.
- CQRS. Separate models for reading and writing, which often use events to stay in step. The CQRS lesson.
The explorer in the first lesson treats event-driven architecture as event notification and event-carried state transfer, a way of communicating that can sit inside a monolith or link services. Event sourcing and CQRS are separate patterns, and they are taught separately.
Thin events and fat events
Section titled “Thin events and fat events”A thin event carries an id and perhaps a link back to the sender: OrderPlaced with an order id of 20 bytes. Receivers that need more call the sender and ask. A fat event carries the order itself: lines, prices, address, 5 KB.
Say the order service publishes 500 events a second to four subscribers: invoicing, email, analytics and loyalty. With thin events of about 200 bytes, the broker moves 500 × 200, or 100 KB a second, which is 8.6 GB a day. But each of the four subscribers calls back for the details, which is 4 × 500, or 2,000 reads a second on the order service. With fat events of 5 KB, the broker moves 500 × 5,000, or 2.5 MB a second, which is 216 GB a day, and nobody calls back. The subscribers keep their own copy of what they need, and keep working if the order service is down.
Neither is right in general. A thin event keeps the owner of the data in charge of it and costs reads. A fat event spreads copies of the data around and makes the format of the event a contract with everybody who keeps a copy.
What it buys: the sender stops waiting
Section titled “What it buys: the sender stops waiting”Take the order service doing 40 ms of work of its own. In a design where it calls its four receivers one after another at 30 ms each, the request takes 40 + 4 × 30, which is 160 ms. Publishing an event costs it, say, 5 ms, and the request takes 45 ms. The numbers are made up, but the shape is real: the work of the receivers no longer sits on the sender’s path.
Availability follows the same route. If the request waits for the four receivers, it depends on five services at 99.9% each, and the availabilities multiply to 99.5%. If the request only has to publish, it depends on the sender and the broker. With a broker at 99.95%, a made-up figure for the arithmetic, that is 0.999 × 0.9995, or 99.85%. The receivers can be down for an hour and the order is still taken, because their events wait in the broker.
That is the case for the style in the explorer. The requirement that parts react to something that happened elsewhere, without the sender waiting for them or knowing who listens, is the one that only this style meets in full. Subscribers can be added later without touching the sender, and a broker lets consumers scale by adding instances that share the work, the pattern the Azure Architecture Center calls competing consumers.
Check your understanding: event-driven architecture
This quiz needs JavaScript to check your answers.
Choreography and orchestration
Section titled “Choreography and orchestration”When a business process spans several parts, someone has to say what happens in what order. In choreography, nobody does: each part reacts to the events of the others and publishes its own, and the process emerges. In orchestration, one component holds the process and tells each part what to do, usually by commands. The next module treats the saga, which comes in both forms.
Choreography is the more loosely coupled. It is also where Fowler’s warning about event notification bites, because the flow exists nowhere in the code: it is spread over the subscribers, and the only way to see it may be to watch a live system. The more steps a process has, the more that matters.
What gets harder
Section titled “What gets harder”The flow becomes invisible. To find out why an order was not shipped, you follow an event through its subscribers, each of which may have published another. This needs tracing that carries an identifier through the messages, and monitoring of the lag of each consumer.
Everything is eventually consistent. A reaction happens after the event. If the invoicing service takes 2 s to read OrderPlaced, then for those 2 s the order exists and the invoice does not. Any screen must cope with that, and a rule that needs both to hold at once needs another mechanism. This is why the explorer judges the style as failing the requirement that a business rule must hold across several parts at the moment a change is made.
Ordering is only partial. A log-based broker orders events within a partition, not across a topic. Key the events by order id, so that all the events of an order go to one partition, and one consumer reads them in order. With 12 partitions, a consumer group can use at most 12 consumers in parallel, so parallelism and ordering pull against each other. See partitions and consumer groups.
Duplicates are normal. Delivery is at least once, so a consumer that adds the amount of each OrderPlaced to the day’s revenue will count one twice after a rebalance. The consumer must be idempotent. And the publisher has its own half of the problem: saving to the database and publishing are two actions, so one can happen without the other, which the transactional outbox solves.
The format is a contract. Adding an optional field is safe. Renaming one breaks every subscriber, including those the publisher’s team has never heard of. Event-carried state makes this sharper, and the schema of the events of the next lessons has the same problem for the whole life of the log.
The trade-off in one place
Section titled “The trade-off in one place”- Decision. Components communicate by publishing events, facts that something happened, to a broker or a log. Others subscribe and react on their own, so the sender does not call them and does not need to know them.
- Why? It decouples the sender from its reactions: a new reaction is added without changing the sender, and a durable broker lets reactions happen later and at their own pace.
- Benefits. Loose coupling. A broker absorbs bursts and consumers scale by adding instances. If a subscriber is down, events wait for it.
- Costs. The overall flow of a process becomes implicit. Reactions happen after the event, so the system is eventually consistent. A broker is one more system to run, and consumers must handle duplicates and limited ordering.
- Failure modes. An event processed twice by a consumer that is not idempotent. The database and the broker disagreeing, if there is no outbox. A message that always fails blocks a consumer, and lag grows silently.
- Scaling limitations. The broker is a shared dependency. Ordering holds only within a partition. The format of an event must stay compatible with every subscriber.
- Alternative. A modular monolith, when the sender needs the combined result in the same request, or a rule must hold atomically across parts, which direct calls and one transaction give.
What happens if a consumer is down, or stuck?
Section titled “What happens if a consumer is down, or stuck?”Events arrive at 500 a second. A consumer is down for 30 minutes, which is 1,800 seconds. The broker keeps what it receives: 500 × 1,800 is 900,000 events waiting. This is the strength of the style, because the sender noticed nothing. But the consumer must now catch up. If it can process 800 events a second and 500 still arrive, it gains 800 − 500, which is 300 a second on the backlog, and clears it in 900,000 / 300, which is 3,000 seconds, or 50 minutes. For 80 minutes in all, whatever depends on that consumer is stale.
Now a slower consumer. If it handles 400 a second against 500 arriving, the backlog grows by 100 a second. After 10 minutes (600 s) it holds 60,000 events, and the newest event waits 60,000 / 400, which is 150 s, before anyone looks at it. Nothing has failed and no error has been raised. This is why the lag of each consumer is a number to watch, in the same way as the backpressure lesson treats queue depth.
And a stuck consumer. One event that always fails, and a consumer that retries it forever, blocks its partition. With 500 events a second spread over 12 partitions, about 42 a second land behind it, so after 10 minutes 25,000 events wait, while the other 11 partitions carry on. The usual answers are a limited number of retries and a dead-letter queue, as in retries and dead letters, and an alert on the lag of every consumer.
- An event is a past-tense fact published to anyone; a command is an instruction to one receiver. A command styled as an event hides a dependency.
- Event notification and event-carried state transfer are the two meanings used here. Thin events (200 B, 100 KB a second, but 2,000 callbacks a second from four subscribers) trade against fat ones (5 KB, 2.5 MB a second, 216 GB a day, no callbacks).
- Publishing instead of calling takes four 30 ms receivers off the request path (160 ms against 45 ms) and takes four services out of the availability chain (99.5% against 99.85% with a 99.95% broker).
- It costs a flow nobody sees, eventual consistency, partial order (key by order id; 12 partitions allow 12 consumers), duplicates and a format that is a contract.
- A consumer down for 30 minutes at 500 events a second leaves 900,000 events, cleared in 50 minutes at 800 a second; one at 400 a second falls 60,000 behind in 10 minutes, 150 s late.
Your progress
Built by GhaziAlibi.
© ShardCraft. All rights reserved.