AlgoViz

Inside a pub-sub system

hard 35 min

How 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

0:00 / 3:45

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

  1. 1987

    The Isis toolkit's news service, presented at SOSP, is one of the earliest publicly described pub-sub systems.

  2. 1999

    MQTT is invented for small devices. Its brokers push messages over open connections.

  3. 2011

    LinkedIn open-sources Kafka. Subscribers pull from a partitioned log and store only a position.

  4. 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.

Step 1 of 3

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.

One flyer, many towns
FLYER OFFICEHILLLAKE

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)

TargetValueIt decides
Peak publish rate1,000,000 messages/s of 1 KBNumber of partitions and brokers
Delay, publish to deliveryUnder 100 ms in one region at p99, reader keeping upPull must not poll slowly
Availability99.99%, about 52 minutes a yearCopies in three zones
Retention7 daysDisk space
OrderPer keyPartition by key
DeliveryAt least onceLeases and idempotent readers

Architecture

Five parts

Control plane and data plane

Publishers reach an API gateway, which asks the control plane who owns the partition and routes to broker 2. Broker 2 copies to brokers 1 and 3. Push workers take batches and post to an endpoint, and after five tries write to a dead-letter topic. A pull subscriber reads from broker 3.
The gateway asks the control plane once and remembers the answer. Messages do not flow through it.
PartDoesKeeps
API gatewayAuthentication, permissions, limits per client, TLS, routingA cache of who owns what
Topic and subscription managerCreates topics and subscriptions, checks filtersTheir settings
BrokersOwn partitions, append, replicate, serve readsThe message logs
Delivery engineLeases, pull, push workers, retry with backoffIn-flight messages
Ack trackerCursor and gaps per subscription and partitionProgress, stored durably
Gateways and push workers are stateless and simple to add. Brokers are not: they own data, and moving a partition takes time.

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?

Confirming before replication is faster, and loses messages when the leader dies.
Confirm afterDelayLost if
NothingLowestAny failure
The leader wrote itLowThe leader's disk or machine is lost before copying
All in-sync copies wrote itHigherEvery in-sync copy is lost
Set a minimum number of in-sync copies. Kafka calls it min.insync.replicas: with too few, it refuses the write instead of pretending.

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

StoreGoodBad
Append-only log (as in Kafka)Highest throughput, natural order, sequential readsOffsets and gaps must be managed
In-memory key-value (Redis)Simple, expiry built in, fast by keyMemory is costly for days of data; durability needs care
Wide-column (Cassandra)Replicated, spreads across regionsHigher delay; deleting a moving window leaves tombstones
For this job the log wins: it is written at the end, read in order and deleted whole segments at a time. See log-based queues.

Data model

RecordKeyFields
Messagetopic, partition, offsetid, data, attributes, publish time, ordering key
Subscriptionsubscription idtopic, name, filter, push address, ack deadline, delivery type, max attempts
Progresssubscription, partitioncursor, acknowledged offsets above it
Leasesubscription, messageworker, deadline, attempt
The message key has no reader in it: that is what makes one stored copy enough.

Retention and cleanup

Seven days is the default in Kafka and in Google Cloud Pub/Sub subscriptions. A reader that is further behind loses data, so alert long before that.

Partitions

Split a topic, keep order per key

Three partitions, three copies, three zones

A publisher sends key k1 to partition 0, key k2 to partition 1 and key k7 to partition 2. Brokers in zones A, B and C each lead one partition and hold copies of the other two.
Each broker leads one partition and follows two, so the writing is shared and any zone can be lost.

Which partition?

p=hash(key) mod Np = \mathrm{hash}(\text{key}) \bmod N
The same key always lands in the same partition while NN stays the same. Changing NN moves keys and breaks order across the change, so choose some spare partitions early.

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

PullPush
Who startsThe subscriber asksThe system posts to an endpoint
PaceThe subscriber decidesThe system must slow down for it
NeedsA client and a connection outAn HTTPS endpoint the service can reach
DelayLow with a long poll or an open stream; high with slow pollingLow while the endpoint keeps up
BatchingEasySmaller; the endpoint answers for each request
AckA separate callA success status is the ack
FitsHigh volume, batch workWeb hooks, functions that scale to zero
Pull is not slow by nature. A request that waits at the broker until a message arrives is answered at once. More in push and pull.

Push to an endpoint

Any other status counts as a failure. Back off, and lower the sending rate when failures rise.

Progress

Leases, acks and gaps

  1. 1

    Deliver

    The message is leased to one worker of the subscription.

  2. 2

    Start the timer

    The ack deadline begins. A long job extends its lease.

  3. 3

    Process

    The worker does the job, safely repeatable.

  4. 4

    Ack

    The offset is marked done. The cursor moves past every finished message at the front.

  5. 5

    Nack or timeout

    The message becomes available again after a growing pause.

One message in one subscription

Each subscription walks its own copy of this diagram for the same stored message.

Failures

Retries and dead letters

Backoff between attempts

waitn=min⁡(cap, base×2n−1)1+2+4+8=15 s\text{wait}_n = \min(\text{cap},\ \text{base} \times 2^{n-1}) \qquad 1 + 2 + 4 + 8 = 15\ \text{s}
Base 1 second and five attempts means four waits, 15 seconds in all, plus random jitter. If the endpoint is down for an hour, five quick tries send everything to dead letters, so stretch the waits or pause the subscription.

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.

BreaksWhat happensAnswer
A brokerIts partitions lose their leaderAn in-sync follower is elected; clients refresh their map
A zoneA third of the copies goCopies in three zones; keep room to carry the load
The control planeNo new topics or movesData plane keeps running on what it knows
A push endpointRetries pile upBackoff, lower rate, pause, alert
A regionEverything in itCopy to another region, usually asynchronously: say how much may be lost

Numbers

Capacity

Storage

1,000,0003≈333,000/s333,000×1 KB×86,400≈28.8 TB/day28.8×3×7≈605 TB\tfrac{1{,}000{,}000}{3} \approx 333{,}000/\text{s} \quad 333{,}000 \times 1\,\text{KB} \times 86{,}400 \approx 28.8\,\text{TB/day} \quad 28.8 \times 3 \times 7 \approx 605\,\text{TB}
The peak is three times the average, so the average is 333,000 messages a second. Three copies for seven days. Compression often reduces this; measure with real messages.

Sizing at the peak (assumed limits)

ItemCalculationResult
Incoming1,000,000 x 1 KB1 GB/s
Written with 3 copies1 GB/s x 33 GB/s
Read by 4 subscriptions1 GB/s x 44 GB/s
Partitions at 10 MB/s each1,000 / 10100
Brokers at 100 MB/s written each3,000 / 10030
With one of three zones lost30 x 3 / 245
Disk per broker605 TB / 45about 13.4 TB
Two thirds of the brokers must carry the peak, so 45. The per-broker and per-partition limits are assumptions; test your own machines.

Operate

Watch it

MetricUnitTells you
Throughput in and outmessages/s, bytes/sLoad and fan-out
Delayms, publish to ackWhat users feel
Oldest unacknowledged messageseconds, per subscriptionHow far behind, against retention
Ack and redelivery rate%Short deadlines or failing handlers
Dead letterscountBugs waiting for a person
Under-replicated partitionscountRisk 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?

Most teams should not build one. Knowing the inside helps you set the right options.

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.

Sources