Inside a pub-sub system
hard 35 minHow to build a publish-subscribe service: a control plane that knows topics and subscriptions, brokers that own replicated partitions, delivery by pull and push, leases and acknowledgements per subscription, retries, dead letters and retention, with the arithmetic that sizes it.
Video lesson · Chapter 1 of 5
Design a newswire with two delivery doors
Theory
Read or listen first. About 2 min.
What it is
A pub-sub service takes messages from publishers, keeps them safe and gives a copy to every subscription. This page looks inside it. It assumes you know what a topic and a subscription are.
There are two jobs. The control plane keeps slow-changing facts: which topics and subscriptions exist, and which broker owns which part. The data plane moves messages: it writes them, copies them and delivers them, many thousands of times a second.
Why it exists
The pattern is simple to describe and hard to run. A message must survive a broken disk. A reader that stops for an hour must find its messages. One slow reader must not delay the others. One busy topic must not fill one machine.
Each of these has a known answer: replicated logs, progress stored per subscription, leases with deadlines, partitions. Knowing them lets you design such a service, and also choose and configure a ready-made one, which is what most teams should do.
A short history
1987
The Isis toolkit's news service, presented at SOSP, is one of the earliest publicly described pub-sub systems.
1999
MQTT is invented for small devices. Its brokers push messages over open connections.
2011
LinkedIn open-sources Kafka. Subscribers pull from a partitioned log and store only a position.
2025
Kafka 4.0 is the first major release that runs entirely without ZooKeeper. The brokers' own KRaft mode keeps the metadata.
Words to know
- Broker
- A server that stores partitions and serves publishers and subscribers.
- Control plane
- The part that knows what exists and who owns it.
- Data plane
- The part that moves the messages.
- Partition
- One ordered piece of a topic, with one leader.
- Leader and follower
- The copy that accepts writes, and the copies that follow it.
- In-sync replica
- A copy that has kept up with the leader.
- Lease
- A message given to one worker until a deadline.
- Cursor
- A subscription's position in a partition.
- Backlog
- Messages a subscription has not acknowledged.
- Flow control
- A limit on unfinished messages, so a reader is not flooded.
How it works
Step through the idea, or press Play.
Accept. The gateway checks the publisher and routes the message to the leader of its partition
Understand it
Start here
The puppet theatre's flyers
A puppet theatre wants towns to know about its dragon show. It does not visit each town. It hands a flyer to an office that does the rest.
The theatre handed in one flyer. Copying, sorting, carrying and chasing signatures is the office's job.
Requirements
What it must do
Functions
Publish
Send a message to a topic and get an id once it is safe.
Subscribe
Create a subscription with an optional filter.
Pull or push
Fetch messages, or have them sent to an endpoint.
Acknowledge
Confirm that a message has been processed.
Retry
Deliver unacknowledged messages again.
Dead letter
Set aside what keeps failing.
Targets for this design (assumptions)
| Target | Value | It decides |
|---|---|---|
| Peak publish rate | 1,000,000 messages/s of 1 KB | Number of partitions and brokers |
| Delay, publish to delivery | Under 100 ms in one region at p99, reader keeping up | Pull must not poll slowly |
| Availability | 99.99%, about 52 minutes a year | Copies in three zones |
| Retention | 7 days | Disk space |
| Order | Per key | Partition by key |
| Delivery | At least once | Leases and idempotent readers |
Architecture
Five parts
Control plane and data plane
| Part | Does | Keeps |
|---|---|---|
| API gateway | Authentication, permissions, limits per client, TLS, routing | A cache of who owns what |
| Topic and subscription manager | Creates topics and subscriptions, checks filters | Their settings |
| Brokers | Own partitions, append, replicate, serve reads | The message logs |
| Delivery engine | Leases, pull, push workers, retry with backoff | In-flight messages |
| Ack tracker | Cursor and gaps per subscription and partition | Progress, stored durably |
Configuration is small and changes rarely, so it needs strong consistency: a relational database with a standby, or a consensus store such as etcd. Kafka used ZooKeeper for this and, since version 4.0, runs only with its own consensus, KRaft.
Write path
Publishing safely
When does the publisher hear yes?
| Confirm after | Delay | Lost if |
|---|---|---|
| Nothing | Lowest | Any failure |
| The leader wrote it | Low | The leader's disk or machine is lost before copying |
| All in-sync copies wrote it | Higher | Every in-sync copy is lost |
A publisher that times out cannot know whether the message was stored, so it sends again. Give each publisher an id and each message a sequence number, and the leader can drop the repeat. Kafka's idempotent producer works this way.
Storage
Store one copy per message, not per reader
With four subscriptions, do not write each message four times. Write it once to the partition's log. Each subscription keeps a cursor and a small set of messages acknowledged ahead of it. A million messages and four subscriptions then cost a million records and four small progress entries.
Where to keep messages
| Store | Good | Bad |
|---|---|---|
| Append-only log (as in Kafka) | Highest throughput, natural order, sequential reads | Offsets and gaps must be managed |
| In-memory key-value (Redis) | Simple, expiry built in, fast by key | Memory is costly for days of data; durability needs care |
| Wide-column (Cassandra) | Replicated, spreads across regions | Higher delay; deleting a moving window leaves tombstones |
Data model
| Record | Key | Fields |
|---|---|---|
| Message | topic, partition, offset | id, data, attributes, publish time, ordering key |
| Subscription | subscription id | topic, name, filter, push address, ack deadline, delivery type, max attempts |
| Progress | subscription, partition | cursor, acknowledged offsets above it |
| Lease | subscription, message | worker, deadline, attempt |
Retention and cleanup
Partitions
Split a topic, keep order per key
Three partitions, three copies, three zones
Which partition?
Messages without a key can be spread evenly. A key that is far busier than the rest makes one hot partition; more partitions do not help it. Use a finer key, such as the order instead of the shop. More in data partitioning.
Delivery
Pull or push
| Pull | Push | |
|---|---|---|
| Who starts | The subscriber asks | The system posts to an endpoint |
| Pace | The subscriber decides | The system must slow down for it |
| Needs | A client and a connection out | An HTTPS endpoint the service can reach |
| Delay | Low with a long poll or an open stream; high with slow polling | Low while the endpoint keeps up |
| Batching | Easy | Smaller; the endpoint answers for each request |
| Ack | A separate call | A success status is the ack |
| Fits | High volume, batch work | Web hooks, functions that scale to zero |
Push to an endpoint
Progress
Leases, acks and gaps
- 1
Deliver
The message is leased to one worker of the subscription.
- 2
Start the timer
The ack deadline begins. A long job extends its lease.
- 3
Process
The worker does the job, safely repeatable.
- 4
Ack
The offset is marked done. The cursor moves past every finished message at the front.
- 5
Nack or timeout
The message becomes available again after a growing pause.
One message in one subscription
Failures
Retries and dead letters
Backoff between attempts
A message that fails five times goes to a dead-letter topic with its error and attempt count. An alert fires, a person looks, the bug is fixed and the message is published again. Five is the smallest and default maximum in Google Cloud Pub/Sub, where the count is approximate. A dead-letter topic with no reader and no alert is a quiet way to lose data.
| Breaks | What happens | Answer |
|---|---|---|
| A broker | Its partitions lose their leader | An in-sync follower is elected; clients refresh their map |
| A zone | A third of the copies go | Copies in three zones; keep room to carry the load |
| The control plane | No new topics or moves | Data plane keeps running on what it knows |
| A push endpoint | Retries pile up | Backoff, lower rate, pause, alert |
| A region | Everything in it | Copy to another region, usually asynchronously: say how much may be lost |
Numbers
Capacity
Storage
Sizing at the peak (assumed limits)
| Item | Calculation | Result |
|---|---|---|
| Incoming | 1,000,000 x 1 KB | 1 GB/s |
| Written with 3 copies | 1 GB/s x 3 | 3 GB/s |
| Read by 4 subscriptions | 1 GB/s x 4 | 4 GB/s |
| Partitions at 10 MB/s each | 1,000 / 10 | 100 |
| Brokers at 100 MB/s written each | 3,000 / 100 | 30 |
| With one of three zones lost | 30 x 3 / 2 | 45 |
| Disk per broker | 605 TB / 45 | about 13.4 TB |
Operate
Watch it
| Metric | Unit | Tells you |
|---|---|---|
| Throughput in and out | messages/s, bytes/s | Load and fan-out |
| Delay | ms, publish to ack | What users feel |
| Oldest unacknowledged message | seconds, per subscription | How far behind, against retention |
| Ack and redelivery rate | % | Short deadlines or failing handlers |
| Dead letters | count | Bugs waiting for a person |
| Under-replicated partitions | count | Risk of loss |
Do
- Use partitions for parallel work
- Make processing idempotent
- Set ack deadlines from measured times
- Configure dead-letter topics with alerts
- Monitor lag and throughput
Do not
- Store large payloads: send a link
- Rely on order across partitions
- Skip acknowledgements
- Use one partition for high volume
- Ignore retention settings
Build or use one?
Summary
The whole topic in one minute.
Store once, deliver many times. A message is written to one partition and copied to followers before the publisher hears yes. Subscriptions do not get physical copies: each keeps its own position and its own set of leased and acknowledged messages.
Pull lets the reader set the pace; push reaches endpoints that only speak HTTP. Deadlines bring back lost work, a dead-letter topic removes hopeless work, and retention deletes the rest. Partitions give scale, replicas give safety, and the backlog's age tells you if it all works.
- Control plane knows, data plane moves.
- Confirm after enough in-sync copies have it.
- One stored message, one cursor per subscription.
- Partition by key; order holds inside a partition.
- Lease, deadline, ack, retry with backoff, dead letter.
- Count copies and fan-out in every estimate.