Sub topic 1
What an Event Is, and How It Differs from a Command
Prerequisites
Assume you know basic programming, HTTP request/response APIs, database transactions, and the idea of distributed systems.
Events, Commands, and Queries
An event is a record of something that already happened. It uses past tense, such as OrderPlaced or PaymentCaptured. The producer publishes the fact without requiring a particular consumer.
A command is a request for an action. It uses an imperative, such as PlaceOrder or CapturePayment. A command normally has one intended receiver, which may accept or reject it.
A query asks for information and expects a response. For example, GET /orders/o-1 is a query. Events usually do not require an immediate response.
| Message | Meaning | Typical response |
|---|---|---|
| Event | Something happened | None required |
| Command | Please perform an action | Accepted or rejected |
| Query | Please return information | Data |
Producers and Consumers
A producer creates and publishes an event. A consumer receives events and performs work. For example, an order service can publish order.placed. Inventory, billing, and notifications can each consume it.
This separates the producer from the consumers. The order service does not need to know which consumers exist or how they work. Adding a notification consumer does not require changing order placement code.
from collections import defaultdict
handlers = defaultdict(list)
def subscribe(event_type, handler):
handlers[event_type].append(handler)
def publish(event_type, event):
for handler in handlers[event_type]:
handler(event)
subscribe("order.placed", lambda e: print("Reserve", e["order_id"]))
subscribe("order.placed", lambda e: print("Email", e["order_id"]))
publish("order.placed", {"order_id": "o-1"})Brokers
An event broker is infrastructure that accepts messages, stores or routes them, and delivers them to consumers. It can provide buffering, retries, access control, and monitoring. The producer and consumer can run at different times or speeds.
Topics Versus Queues
A topic supports fan-out: each subscribed consumer receives its own copy of an event. Use a topic when several independent actions must happen.
A work queue distributes jobs among competing consumers. Each job usually goes to one available worker. Use a queue when workers share one task, such as processing image thumbnails.
Exercise
An order event must trigger inventory reservation and receipt delivery. Should these use a topic or one competing-consumer queue?
Show answer
Use a topic, because both independent consumers must receive the event.