Part 2 of 7 · 2 min read
Events and commands
A command asks for something and may fail. An event records something that already happened.
Think of a restaurant. A guest says "I would like the soup". That is a request, and the kitchen may answer "sorry, we are out". Once the kitchen says "soup for table 4 is ordered", the order is a fact. Later the guest may cancel, but then "table 4 cancelled the soup" is a second fact. The first one stays true: the soup was ordered.
The DDIA book separates the two. A request from a user first arrives as a command. At this point it can still fail, for example because a rule is broken. The application first checks whether it can carry out the command. If the check passes and the command is accepted, it becomes an event, which is durable and unchangeable.
Command
A command is a request to do something. It may be refused.
Example: "reserve seat 14C on flight 220 for customer 31". If the seat is taken, the command fails.
Event
An event is a record that something happened. It is named in the past tense and it is never changed afterwards.
Example: "seat 14C on flight 220 was reserved for customer 31, at 10:42".
DDIA draws a rule from this. A consumer of an event stream cannot reject an event. By the time a consumer sees it, the event is part of the log and other consumers may have seen it too. So any check that could fail must happen before the event is created. For example, a serializable transaction (Level 5) can check the seat and publish the event in one step. Or the work can be split into two events: "seat tentatively held", and later "reservation confirmed" once an asynchronous check is done.
The Building Microservices book describes the style that follows from events: event-based collaboration. In request/response, a client asks another service to do something. In event-based collaboration, the client says "this thing happened" and expects others to know what to do. It never tells anyone what to do. The sender cannot know who will react, so new subscribers can be added without the sender changing.
| Command | Event | |
|---|---|---|
| Tense | Imperative: "reserve seat" | Past: "seat reserved" |
| Can it fail? | Yes | No, it already happened |
| Who is it addressed to? | One known receiver | Anyone who is interested |
| What does the sender expect? | An action | Nothing in particular |
Check yourself:
- Why can a consumer not reject an event?
- Rewrite the command "cancel order 12" as an event.