Courses / System Design Interview / Chapter 17
Module 3 · Building Blocks II: Monitoring, Caching and Messaging · Chapter 17 of 49
Publish-Subscribe Systems
Builds on Back-of-the-Envelope Estimates, Building Blocks: The Parts Every Design Reuses, Distributed Caches and Distributed Message Queues. Next up: Rate Limiters.
Part 1 · Topics, publishers, subscribers and fan-out
Announcing instead of asking
When an order is placed, billing, email and analytics all need to know. If the order service called each of them, it would have to know all three and wait for the slowest.
In publish-subscribe, usually shortened to pub-sub, the order service does something simpler. It announces that the order was placed and moves on. The announcement is an event: a small record that says something happened, such as order 101 placed. The service that sends it is the publisher. The events go to a named channel called a topic. Any service that has subscribed to the topic gets a copy of every event published to it. The act of delivering one event to many subscribers is fan-out.
The publisher does not know who the subscribers are, how many there are, or whether they are running. That is the point of the pattern. Adding a fourth service that needs to know about orders means subscribing it to the topic. The order service does not change and is not redeployed.
An event and a command are different. A command tells a particular service to do something, such as send receipt to customer 7. An event states a fact, order 101 placed, and leaves it to each listener to decide what to do. Pub-sub is the right tool for events. A command to one worker belongs in a queue.
The Google Cloud Pub/Sub overview describes the publisher's side in these terms: a publisher sends events to the service without regard to how or when they will be processed, and the service delivers them to the services that react to them. That is the decoupling in one sentence.
A topic in code
The smallest working topic keeps one inbox per subscriber. Publishing copies the event into every inbox, and each subscriber reads its own inbox at its own pace. The code below builds that with Python queues and threads, and then three subscribers each receive the same three events.
import queue import threading class Topic: def __init__(self): self.inboxes = {} # subscriber name -> its own queue def subscribe(self, name): self.inboxes[name] = queue.Queue() return self.inboxes[name] def publish(self, event): # every inbox gets its own copy for inbox in self.inboxes.values(): inbox.put(event)
l1_topic.py, part 1: a topic with one inbox per subscriber
topic, received, threads = Topic(), {}, []
def listen(name, inbox):
received[name] = []
while (event := inbox.get()) is not None: # None means: stop
received[name].append(event)
for name in ("billing", "email", "analytics"):
inbox = topic.subscribe(name)
t = threading.Thread(target=listen, args=(name, inbox))
t.start()
threads.append(t)
for n in (101, 102, 103):
topic.publish(f"order {n} placed")
for inbox in topic.inboxes.values():
inbox.put(None)
for t in threads:
t.join()
for name, events in received.items():
print(f"{name:<10}", events)l1_topic.py, part 2: three subscribers, three events
It was run with Python 3.12.10. Each subscriber appends to its own list, so the output does not depend on which thread ran first.
billing ['order 101 placed', 'order 102 placed', 'order 103 placed'] email ['order 101 placed', 'order 102 placed', 'order 103 placed'] analytics ['order 101 placed', 'order 102 placed', 'order 103 placed']
Each of the three subscribers received all three events, in the order they were published. The publisher called publish three times and never mentioned billing, email or analytics. The topic is the only thing that knows about them.
The inbox for each subscriber is what makes fan-out safe. If email is slow, its inbox grows and billing is not affected, because billing reads from a different inbox. The scene below shows exactly that.
What pub-sub costs
Pub-sub removes the coupling to subscribers and adds others. The publisher and subscribers still share the shape of the event: if the publisher renames a field, subscribers that read it break. Treat the event format as a contract, add fields without removing old ones, and version it when you must change it.
It also hides the flow. In a direct call, you read the code and see who is called. With a topic, you have to look at the subscriptions to learn who reacts, so a design with many topics needs a list of who publishes and who subscribes to each. And the delivery rules still apply: a subscriber can see an event twice or late, which the later lessons cover.
Typical uses are sending notifications when something happens, keeping a search index in step with a database, telling caches to drop a changed entry, and feeding analytics. A published change event is also how several regions can each drop the same stale cache entry, as the cache chapter noted.
What does the publisher know about its subscribers?
- Nothing. It sends the event to the topic, and the topic delivers a copy to each subscriber.
- That is why a new subscriber can be added without changing the publisher.
What is the difference between an event and a command?
- An event states that something happened, and each listener decides what to do. A command asks one service to do something.
- Events suit topics. A single task for one worker suits a queue.
In the scene, email goes down while order 102 is published. What happens to billing and analytics?
- They receive the event normally, because each subscriber has its own inbox.
- Email's copy waits in its inbox, and it catches up when it returns.
Part 2 · Queues versus pub-sub
Two questions
A queue and a topic look alike: a producer writes, a consumer reads, and a broker sits in between. The difference is in who receives what, and you can state it as two questions.
A queue answers the question: who will do this job? Each message goes to exactly one of the consumers that share the queue, so the work is divided. A topic answers the question: who needs to know about this? Each message goes to every subscriber, so the knowledge is shared.
| Question | Queue | Topic |
|---|---|---|
| Who gets a message | One consumer out of the group | Every subscriber |
| What adding consumers does | Spreads the work, so it finishes sooner | Adds one more reader of every message |
| Does the sender know the readers | Not by name, only that someone will do it | No, and does not care |
| Typical content | A job: resize this photo | An event: a photo was uploaded |
| If a reader is slow | The queue gets longer, and workers share the load | Only that subscriber's inbox grows |
| Message lifetime | Gone once handled | Kept for each subscriber until it has handled it |
The wrong tool shows up quickly. If you publish a photo-resize job to a topic with three workers subscribed, all three resize the same photo. If you put an order-placed event on a queue that billing and email both read, each of them sees only some of the orders.
Counting deliveries
The program below sends the same six events two ways. Three worker threads share one inbox, which is a queue. Then each of three workers has its own inbox, which is a topic. It counts the deliveries.
import queue import threading from collections import Counter EVENTS = [f"order {n} placed" for n in range(1, 7)] def consume(inbox, name, log): while (event := inbox.get()) is not None: log.append((name, event)) def run(inboxes, publish): # one worker thread per inbox log = [] threads = [threading.Thread(target=consume, args=(q, f"w{i}", log)) for i, q in enumerate(inboxes)] for t in threads: t.start() publish() for q in inboxes: q.put(None) # one stop signal per worker for t in threads: t.join() return log
l2_compare.py, part 1: workers and a runner
def report(label, log): times = set(Counter(e for _, e in log).values()) print(f"{label}: {len(log)} deliveries, each event handled " f"{times.pop()} time(s)") shared = queue.Queue() to_queue = lambda: [shared.put(e) for e in EVENTS] report("queue", run([shared] * 3, to_queue)) # 3 workers, 1 inbox own = [queue.Queue() for _ in range(3)] def fan_out(): for e in EVENTS: for q in own: q.put(e) report("topic", run(own, fan_out)) # 1 inbox per worker
l2_compare.py, part 2: the same events as a queue and as a topic
It was run with Python 3.12.10. Which worker took which message from the queue changes from run to run, so the program prints only totals, and the totals do not change.
queue: 6 deliveries, each event handled 1 time(s) topic: 18 deliveries, each event handled 3 time(s)
The queue made six deliveries for six events, and each event was handled once, by whichever worker was free. The topic made eighteen deliveries, three for each event, since each worker had its own inbox. The same code and the same events produced three times as much work, because the question being answered was different.
The workers in the queue case divide the work. The workers in the topic case are three different services, each doing its own job on every event. If the topic's three subscribers were three identical copies of one service, they would do the same job three times.
Using both together
Real designs combine them. A service that subscribes to a topic often has several instances, and the instances must not all handle every event. The usual layout is a topic for the event, then one queue for each subscribing service, and several workers sharing that queue. Billing has a queue with four workers, email has a queue with two, and analytics has its own. The topic fans out to the queues. Each queue shares the work inside its service.
Managed brokers give this to you in different forms. Kafka has consumer groups, which the next lesson covers. Other systems let a topic feed several queues. The names differ and the shape is the same: fan-out across services and sharing within a service.
Because the two answers are different, check which you need before you pick the tool. When the answer is both, use a topic and a queue for each reader.
You publish a photo-resize job to a topic that has three workers subscribed. What happens?
- Each of the three workers resizes the same photo, so the work is done three times.
- A queue gives each job to one worker.
In the run, six events gave six deliveries as a queue and eighteen as a topic. Why?
- In the queue, the three workers shared one inbox, so each event went to one of them.
- In the topic, each worker had its own inbox, so each event was copied three times.
A topic has billing as a subscriber, and billing runs four instances. How should the instances be arranged?
- Give billing its own queue fed by the topic, and let the four instances share that queue, so each event is handled once by billing.
Part 3 · Consumer groups and offsets
A log with positions
The simple topic of the last lesson deletes an event from a subscriber's inbox when it is read. Many systems, Kafka the best known, keep events in an append-only log instead and let each reader keep its own position. The position is an offset: the number of the next event that reader will read. The Kafka documentation describes a consumer's position in a partition as a single integer, the offset of the next message to consume.
This changes what a subscriber is. It is no longer an inbox that the broker empties. It is a position in a log that the broker keeps. Reading does not remove anything, so any number of readers can read the same events, and each reader can go back or forward by changing its offset. The documentation notes that consumers can rewind to re-consume data, and that offsets can be checkpointed periodically, which keeps the record of what has been acknowledged small.
A consumer group is a set of consumers that share one subscription. The group has one committed offset per partition, and the group as a whole is a single subscriber. Within the group, each partition is read by exactly one consumer at a time, which is how the work is divided. Different groups are independent: billing is one group, analytics is another, and each has its own offsets.
When consumers join or leave, the group is rebalanced and its partitions are reassigned among the members. A member normally has a generated id that changes when it restarts, so even a quick restart causes a rebalance. The Kafka documentation describes static membership, where each member gives a persistent id: membership then stays the same across a restart and no rebalance is triggered.
A log and two groups
The code below is a model of this. Log keeps events in two partitions, using a hash of the key to choose the partition, as in the previous chapter. Group keeps an offset for each partition and can poll, commit, and report its lag, which is the number of events in the log that it has not yet committed.
import zlib class Log: """A topic stored as partitions: append-only lists of events.""" def __init__(self, partitions): self.parts = [[] for _ in range(partitions)] def publish(self, key, event): p = zlib.crc32(key.encode()) % len(self.parts) self.parts[p].append(event) class Group: """A consumer group: one committed offset per partition.""" def __init__(self, log): self.log = log self.offset = [0] * len(log.parts) # next offset to read def poll(self, partition, limit): start = self.offset[partition] return self.log.parts[partition][start:start + limit] def commit(self, partition, count): self.offset[partition] += count def lag(self): parts = zip(self.log.parts, self.offset) return sum(len(p) - o for p, o in parts)
l3_log.py: partitions, groups, offsets and lag
The run publishes eight orders, then has two groups read. Billing reads everything. Analytics reads only two events from each partition, as if it were slow or had been stopped.
from l3_log import Log, Group log = Log(partitions=2) for n in range(1, 9): log.publish(f"order-{n}", f"order {n}") print("partition 0:", log.parts[0]) print("partition 1:", log.parts[1]) billing, analytics = Group(log), Group(log) for p in range(2): # billing keeps up billing.commit(p, len(billing.poll(p, 100))) for p in range(2): # analytics reads 2 each analytics.commit(p, len(analytics.poll(p, 2))) print("billing offsets", billing.offset, "lag", billing.lag()) print("analytics offsets", analytics.offset, "lag", analytics.lag()) # In one group each partition has one reader: two consumers share. for consumer in (0, 1): mine = [p for p in range(2) if p % 2 == consumer] print(f"analytics consumer {consumer} owns partitions {mine}")
l3_run.py: two groups with their own offsets
It was run with Python 3.12.10. The partition for a key comes from a stable hash, so the layout repeats exactly.
partition 0: ['order 4', 'order 5', 'order 6', 'order 7'] partition 1: ['order 1', 'order 2', 'order 3', 'order 8'] billing offsets [4, 4] lag 0 analytics offsets [2, 2] lag 4 analytics consumer 0 owns partitions [0] analytics consumer 1 owns partitions [1]
Lag, and one reader per partition
Lag is the first number to watch on a log-backed topic. A subscriber whose lag keeps rising is not keeping up, in the same way that a queue whose depth keeps rising is not keeping up. Alerts are normally set on lag, or on the age of the oldest unread event.
The last lines of the output show how one group shares the work. With two partitions and two consumers, each consumer owns one partition. The rule that each partition has one reader within a group also sets a ceiling: a topic with two partitions can keep two consumers of a group busy and no more. If the group needs more parallelism, the topic needs more partitions, and that has to be planned when the topic is created.
Commit after the work, not before. If a consumer commits offset 6 and then crashes while handling event 5, the group resumes at 6 and event 5 is never handled. If it handles the event first and commits after, a crash repeats the event and does not skip it. That is the at-least-once choice from the message queue chapter, and it makes idempotent handlers necessary here as well.
What is an offset?
- The number of the next event a reader will read in a partition.
- Changing it lets a reader rewind to read old events again.
In the run, billing has offsets 4 and 4 and analytics has 2 and 2. What are their lags?
- Billing has lag 0, and analytics has lag 4, since it is two behind in each of two partitions.
- Neither group affects the other, because each keeps its own offsets.
Why commit an offset after handling the event and not before?
- A crash after a commit but before handling would skip the event for good.
- Committing afterwards means a crash repeats the event, which an idempotent handler can absorb.
Part 4 · Retention and replay
How long events are kept
A log cannot keep every event forever. Disks fill, so the broker applies a retention policy that decides when old events are deleted. The usual choices are by age and by size. The Kafka topic configuration reference gives the defaults: delete as the cleanup policy, a retention of 604800000 milliseconds, which is 7 days, and no size limit.
A second policy, log compaction, keeps the newest event for each key instead of deleting by age. The documentation describes it as keeping at least the last value for each key in a partition, and a record with a key and a null payload, called a tombstone, deletes that key. Compaction suits a topic that represents the current state of things, such as the latest address of each customer, and not a stream of things that happened.
Retention sets how far back a subscriber can go. A subscriber that was down for three days still finds its events if retention is seven days. A subscriber that was down for ten days has lost its place, because the events that it had not read were deleted. That is why lag matters, and why retention is chosen against the longest outage you want to survive.
Replay in code
Replay means reading events again from an earlier offset. It has three uses. A new subscriber starts at the beginning and builds its own view of the past. A subscriber that had a bug fixes it and reads the same events again. And a service that lost its data rebuilds it from the log. The Google Cloud Pub/Sub subscription documentation says that retention on the topic is what enables replay of previously published messages.
The model below keeps only the last five events. Eight orders are published, with amounts of 100 up to 800. A new subscriber then asks for offset 0, and another starts at the earliest offset still held.
class OutOfRange(Exception): pass class RetainedLog: def __init__(self, keep): self.keep, self.base, self.events = keep, 0, [] def publish(self, event): self.events.append(event) while len(self.events) > self.keep: # drop the oldest self.events.pop(0) self.base += 1 # offsets never change def read_from(self, offset): if offset < self.base: raise OutOfRange(f"{offset} deleted, earliest {self.base}") return self.events[offset - self.base:] log = RetainedLog(keep=5) for n in range(8): log.publish({"offset": n, "amount": 100 * (n + 1)}) try: log.read_from(0) except OutOfRange as err: print("new subscriber from offset 0:", err) replayed = log.read_from(log.base) # start at the earliest print("replayed offsets:", [e["offset"] for e in replayed]) print("total rebuilt from the log:", sum(e["amount"] for e in replayed))
l4_replay.py: a log that keeps five events
It was run with Python 3.12.10 and is deterministic.
new subscriber from offset 0: 0 deleted, earliest 3 replayed offsets: [3, 4, 5, 6, 7] total rebuilt from the log: 3000
Offsets never change when old events are deleted, which is why the first retained event is still numbered 3. The request for offset 0 failed, because that event was deleted, and the program reports the earliest offset that remains. The second subscriber started at the earliest and replayed offsets 3 to 7. The total that it rebuilt was 3,000.
That total is a warning. The true total of all eight orders is 3,600. The three oldest events, worth 600, were gone, so a view rebuilt from this log alone is wrong. Replay can only recover what the log still holds. If a subscriber must be able to rebuild everything, keep a longer retention, store the events in a durable archive as well, or rebuild from the database that is the source of truth.
Using replay safely
Replay re-delivers events that were already handled once. A replaying subscriber must therefore either be idempotent, as the previous lessons described, or write its results into a fresh store and switch over when it has caught up. The second approach lets you replay without touching live data, and it is how a new view of old events is usually built.
It also changes how you think about fixing mistakes. If a subscriber wrote wrong results because of a bug, you can deploy the fix, reset the subscriber's offset to a point before the bug, and let it process again. This is only possible because the log keeps events after they are read. A queue that deletes on acknowledgement cannot do it.
Choose retention with a number in mind: the longest outage of a subscriber that you intend to survive, and the longest history a new subscriber needs. Disk cost follows from the event rate and the event size, which you can estimate with the method of the estimates chapter.
What are the usual ways a log decides which events to delete?
- By age and by size. The Kafka defaults are 7 days and no size limit.
- Compaction instead keeps the newest event for each key.
In the run, the replayed total was 3,000 but the true total was 3,600. Why?
- Retention had deleted offsets 0 to 2, the three oldest orders, worth 600, so replay could not see them.
- Replay recovers only what the log still holds.
What must a replaying subscriber do, because replay redelivers events?
- Be idempotent, or write to a fresh store and switch over when it has caught up.
Part 5 · Push versus pull delivery, ordering and duplicates
Who starts the delivery
A subscriber can receive events in two ways. In pull delivery, the subscriber asks the broker for the next events whenever it is ready. In push delivery, the broker sends each event to the subscriber, usually by calling a web address that the subscriber has registered. The Google Cloud Pub/Sub documentation describes the two in these terms: in pull, the subscriber client requests messages from the server, and in push, the server sends requests to the subscriber application.
| Feature | Pull | Push |
|---|---|---|
| Who sets the pace | The subscriber, which asks when it is ready | The broker, which sends when an event arrives |
| Back-pressure | Natural: a busy subscriber simply asks less often | The broker must slow down when responses fail |
| Latency | Depends on how often it asks, or on a held-open request | Low: the event is sent at once |
| What the subscriber needs | A client that can reach the broker | A reachable endpoint that the broker can call |
| Good for | Batch workers and heavy processing | Web services and short handlers |
Pull gives the subscriber control, which is why heavy workers prefer it. Push suits a small web service that is already listening for requests, and it avoids a polling loop. With push, the broker has to treat a failed call as a failure to deliver.
How a push acknowledgement works
In the Pub/Sub push documentation, the subscriber's HTTP response is the acknowledgement. A response of 102, 200, 201, 202 or 204 acknowledges the message. Any other status is a negative acknowledgement, and Pub/Sub sends the message again. It also resends the message if the acknowledgement deadline passes before a reply arrives. After repeated failures, Pub/Sub applies a push backoff, a pause between 100 milliseconds and 60 seconds with exponential growth, which the documentation says applies to the whole subscription. Messages arrive as HTTPS POST requests, wrapped by default in a JSON object that carries the message data and some metadata.
The important consequence is the same as in a queue. A reply can fail after the work was done, so the broker cannot tell the difference between a message that was not processed and one that was. The documentation says plainly that at-least-once delivery is the default for all subscription types, that a message can be redelivered at any time, and that subscribers should be idempotent. Ordering is not guaranteed by default either, and it is available as an option for messages that share an ordering key.
A push subscriber that fails
The program runs a real local web server as the subscriber. A publisher pushes three events to it by HTTP POST and retries until it sees a 2xx reply. The server misbehaves in two ways. For event e3 the first call returns 503 without doing the work. For event e2 the first call does the work and then returns 500, which is the case where the work happened but the reply says it failed. The program runs twice: first with a subscriber that does the work every time, then with one that remembers event ids.
import json from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer def make_server(port, dedupe): seen, work, tries = set(), [], {} class Handler(BaseHTTPRequestHandler): def do_POST(self): size = int(self.headers["Content-Length"]) event = json.loads(self.rfile.read(size)) eid = event["id"] tries[eid] = tries.get(eid, 0) + 1 if eid == "e3" and tries[eid] == 1: return self.reply(503) # busy: no work done if not (dedupe and eid in seen): work.append(eid) # the real work seen.add(eid) # e2: work done, but the first reply is a failure self.reply(500 if eid == "e2" and tries[eid] == 1 else 200) def reply(self, code): self.send_response(code) self.send_header("Content-Length", "0") self.end_headers() def log_message(self, *args): pass server = ThreadingHTTPServer(("127.0.0.1", port), Handler) return server, work, tries
l5_subscriber.py: a subscriber with two planned failures
import json import threading import time import urllib.error import urllib.request from l5_subscriber import make_server def push(port, event, max_tries=5): body = json.dumps(event).encode() for attempt in range(1, max_tries + 1): url = f"http://127.0.0.1:{port}/events" req = urllib.request.Request(url, body) try: urllib.request.urlopen(req).close() return attempt # a 2xx reply is the ack except urllib.error.HTTPError: time.sleep(0.02) # not acked: send again return None for port, dedupe in ((55472, False), (55473, True)): server, work, tries = make_server(port, dedupe) threading.Thread(target=server.serve_forever, daemon=True).start() attempts = {e: push(port, {"id": e}) for e in ("e1", "e2", "e3")} server.shutdown() server.server_close() print(f"subscriber dedupes: {dedupe}") print(" attempts needed:", attempts) print(" work done :", work)
l5_run.py: push with retries, run twice on ports 55472 and 55473