Sub topic 1
What an Event Is, and How It Differs from a Command
Prerequisites
This chapter assumes you have:
- Basic programming skills in any language. The examples use Python and JSON.
- Familiarity with request/response APIs such as HTTP.
- A basic understanding of databases and transactions.
- Awareness of what a distributed system is: several processes on different machines cooperating over a network.
You do not need to know any message broker product. Brokers appear in a later chapter.
Three kinds of messages
Software components talk to each other by sending messages. Three kinds of message appear constantly, and mixing them up is the most common early mistake in event-driven design:
- A query asks for information and changes nothing. Example: "What is the status of order o-1?"
- A command asks a specific component to do something. Example: "Reserve stock for order o-1."
- An event states that something has already happened. Example: "Order o-1 was placed."
The rest of this chapter explains why these differ and what that difference does to your design.
What an event is
An event is an immutable record of a fact: something that happened in the past, in your business or your system. Three properties follow from that definition.
- It is in the past tense.
order.placed,payment.captured,address.changed. The thing is done. Nobody can reject it. - It is immutable. If the fact changes, you do not edit the old event. You publish a new one, such as
order.cancelled. - It does not address a receiver. The event says what happened. It does not say who should react or how.
Here is a typical event as JSON. This shape is called an envelope: metadata around a payload.
{
"id": "6f1c2d9e-3b7a-4c55-9d0e-1a2b3c4d5e6f",
"type": "order.placed",
"version": 1,
"occurredAt": "2026-11-26T11:00:00Z",
"data": {
"orderId": "o-1",
"customerId": "c-9",
"totalCents": 4599
}
}Each field has a job:
| Field | Purpose |
|---|---|
| `id` | A unique identifier. Consumers use it to detect duplicates. |
| `type` | A name for the kind of fact. Consumers use it to decide whether they care. |
| `version` | The schema version of `data`. It lets the format change over time. |
| `occurredAt` | When the fact happened, not when it was delivered. |
| `data` | The details of the fact. |
Later chapters return to id (idempotency) and version (schema evolution). For now, notice that nothing in the envelope names a receiver.
What a command is
A command is a request addressed to one logical receiver. It is phrased as an instruction in the imperative: ReserveStock, SendReceipt, CapturePayment.
A command differs from an event in four ways:
- It can fail or be refused. The receiver may reject
ReserveStockbecause the item is out of stock. An event cannot be refused, because the thing already happened. - The sender expects an effect. The sender cares whether the work gets done, and often waits for the outcome.
- The sender knows the receiver. It must know where to send the command.
- It has one handler. Two components that both process the same command would do the work twice.
An event can have zero, one or many consumers. The producer neither knows nor cares.
Queries
A query reads state. It is usually a synchronous request/response call, such as GET /orders/o-1. A query has no side effects, so you can repeat it safely. Queries matter in this chapter because event-driven systems often replace many cross-service queries with local copies of data built from events. Later chapters on event-carried state transfer and CQRS explain that.
Comparing the three
| Aspect | Query | Command | Event |
|---|---|---|---|
| Meaning | "Tell me X" | "Do X" | "X happened" |
| Tense | Question | Imperative | Past |
| Changes state | No | Yes, if accepted | Records a change that already occurred |
| Can be rejected | Not applicable | Yes | No |
| Receivers | One | One | Zero or more |
| Sender knows receiver | Yes | Yes | No |
| Typical name | `GetOrder` | `PlaceOrder` | `OrderPlaced` |
Why the distinction matters
Consider an order service that must reserve stock and send a receipt after an order is placed. There are two ways to design it.
Command style. The order service calls the inventory service (ReserveStock) and then the notification service (SendReceipt). It knows both services. Adding a loyalty-points service means editing the order service. If the notification service is down, the order service must decide what to do.
Event style. The order service records the order and publishes order.placed. Inventory and notifications each react on their own. Adding loyalty points means adding a new consumer. The order service is not touched.
The second design reverses the direction of knowledge. In the command style, the sender knows its receivers. In the event style, receivers know the events they care about, and the producer does not know them. This is what "decoupling" means in practice.
A minimal event bus
The following code shows the event idea in a single process. The publisher calls publish with an event type and a payload. It has no reference to any handler.
from collections import defaultdict
class EventBus:
def __init__(self):
self._handlers = defaultdict(list)
def subscribe(self, event_type, handler):
self._handlers[event_type].append(handler)
def publish(self, event_type, payload):
for handler in self._handlers[event_type]:
handler(payload)
bus = EventBus()
bus.subscribe("order_placed", lambda e: print("reserve stock for", e["order_id"]))
bus.subscribe("order_placed", lambda e: print("send receipt for", e["order_id"]))
bus.publish("order_placed", {"order_id": "o-1"})Running it prints both lines, in subscription order. One event reached two independent handlers. Adding a third handler needs one more subscribe call and no change to the publisher.
This toy bus is synchronous and in-process. If a handler raises an exception, publish stops and later handlers never run. A real broker runs handlers independently, in other processes, and adds storage and delivery rules. Those are the subject of the next chapters.
Naming events well
Good names carry most of the design discipline. Follow these rules:
- Use the past tense.
InvoicePaid, notPayInvoice. A present-tense or imperative name usually means you have written a command and labelled it an event. - Name the business fact, not the technical change.
CustomerMovedsays more thanCustomerTableRowUpdated. - Prefer specific events over generic ones.
OrderShippedandOrderCancelledare better than oneOrderUpdatedthat forces every consumer to inspect fields and guess what changed. - Name the source. An event belongs to the component that owns the fact. Only the order service publishes
order.placed.
Common errors
Disguised commands. An event named order.placed whose only consumer is the inventory service, and which the order service waits on, is a command with extra steps. Test it: if the producer needs a particular consumer to act, or needs the outcome, you have a command. Use one directly, or redesign the flow.
Events that can be refused. If a consumer's job is to approve or veto, the message is a request. Model the request as a command and the answer as an event, such as PaymentCaptured or PaymentDeclined.
Mutating events. Editing an event after publication breaks every consumer that already processed it. Publish a correcting event instead.
Leaking internals. Publishing your database row structure ties every consumer to your table design. Publish what a business person would recognize as a fact.
Assuming immediate effect. Publishing an event does not mean the consumers have acted. Between the publish and the reaction there is a gap, and your design must tolerate it. The chapter on eventual consistency covers this.
Edge cases
- Events that trigger commands. A consumer may react to
order.placedby issuing its own command, such asReserveStock, to a component it owns. Events cross boundaries between teams, and commands usually stay inside them. - Facts about failure. Failures are facts too.
PaymentDeclinedis a valid event. It records that an attempt happened and failed. - Time.
occurredAtrecords when the fact happened. Consumers receive events later, so never use the receiving time as the business time. - Zero consumers. An event nobody consumes is still valid. A producer must not depend on listeners existing, though you should periodically remove events no one uses.
Exercise
Classify each message as a query, command or event, and rewrite any badly named message: (a) GetInvoice, (b) ChargeCard, (c) ShipOrder published after the warehouse has already shipped the parcel, (d) CustomerEmailChanged.
Show answer
(a) Query: it reads state and changes nothing. (b) Command: an imperative addressed to a payment component, which may refuse it. (c) It is an event with a command name. The parcel has already shipped, so rename it OrderShipped. (d) Event: past tense, a fact, no named receiver.
Exercise
The order service publishes order.placed and then waits until the inventory service replies that stock is reserved before confirming to the customer. Is order.placed working as an event here? What would you change?
Show answer
No. The producer depends on a specific consumer acting and on its outcome, and the inventory service can refuse. That is a command. Either send ReserveStock directly and handle the reply, or publish order.placed as a plain fact, let inventory publish StockReserved or StockRejected, and have the order service react to those events later.