System Design · 04. Communication · 10 min · Intermediate
Pub/Sub & Events
Announce that something happened, and let anyone who cares listen.
In short
The publisher sends one event and makes 1 call, not 3 or 4. The broker fans it out: 500 orders a second to 4 subscribers is 2,000/s.
A log keeps events so readers track their own offsets and can replay. Partitions and consumer groups share the work and keep order per key.
Key ideas
- An event says what happened ("order placed"). A command says what to do ("send an email"). Pub/sub carries events. (step 2)
- The log is the source of the story. Subscribers are just different positions in it. (step 5)
Good to know
- Loose coupling: teams add listeners without asking the publisher's team. (step 3)
- More partitions means more parallel readers and writers. Pick the key so related events stay together. (step 6)
- Replay turns "we lost a day of statistics" into "we ran the job again". (step 8)
Watch out
- Every new listener means a change in the one service that should not care who listens. (step 1)
- Fan-out multiplies traffic. A topic with 1,000 subscribers turns 500 events a second into 500,000 deliveries a second. (step 4)
- The number of partitions is the ceiling for parallelism inside one group. (step 7)
- Write down event names and shapes like a public API, and version them. (step 9)
Key numbers
- Calls per order
- 1
- Subscribers
- 4
- Deliveries
- 2,000/s
Terms
- Publish/subscribe
- A style where senders publish events to a topic and any number of subscribers receive them.
- Topic
- A named channel that events are published to.
- Event
- A message saying that something happened, such as order.placed.
- Subscription
- A subscriber's own place in a topic, so each reader gets its own copy.
- Fan-out
- One published event becoming many deliveries, one per subscriber.
- Event log
- An append-only list of events that stays for a set time and is not deleted when read.
- Offset
- The position of the next event a reader will read in a log.
- Partition
- One slice of a topic; order is kept inside a partition, chosen by a key.
- Consumer group
- A set of workers that share a topic's partitions, each partition read by one of them.
- Replay
- Resetting the offset to read old events again.
- Event-driven design
- Services react to events instead of being called directly.