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.
See it run
How a message is accepted, copied, delivered, acknowledged, retried and set aside.
Operations
One message, end to end
Seven moments from the publisher to two acknowledgements, with one pull reader and one push endpoint.
Step 1 of 7
Publish
The publisher sends a topic, a key and a payload to the gateway.
Step 1: Publish
def publish(topic, message, key): check_permission(topic) broker = owner(topic, partition(key)) offset = broker.append(message) wait_for_in_sync(offset) return offsetdef deliver(sub): if sub.kind == "push": worker.post(sub.endpoint, sub.lease())- Costs
- 1 write, 3 copies
- Protects
- Every reader
The message is stored once. The pull reader and the push endpoint share that copy.
In the real world
The same inside a pub-sub system doing real jobs. Pick one and step through it.
A follower that has every committed record takes over.
Step 1 of 4
Normal
Broker A leads. B and C have all committed records.
Step 1: Normal
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Confirming too early
criticalThe leader can die before anyone else has the record.
Wronglog.append(record)return "ok"Rightlog.append(record)wait_for_in_sync(record)return "ok"A failing filter that lets everything in
majorA filter that cannot be read should be refused when the subscription is created, not treated as no filter.
Wrongexcept Exception: return TrueRightraise InvalidFilter(text) # at creationReading from the start every time
majorWithout moving the cursor, each pull scans more finished messages until it finds nothing new.
Wronglog[0:limit] minus ackedRightlog[cursor:] minus done above cursorDead letters nobody reads
majorMessages disappear politely.
Wrongdead.append(m)Rightdead.append(m)alert_if(dead.count > 0)
Interview tips
How to explain it
- Control plane knows, data plane moves.
- Write once, replicate, confirm.
- A cursor per subscription.
Memory trick: BAST
- Broker routes.
- Ack confirms.
- Store keeps, Topic organises.
Size it
- Writes: in times copies.
- Reads: in times subscriptions.
- Add room for a lost zone.
Watch
- Oldest unacknowledged message.
- Redelivery rate.
- Dead letters and under-replicated partitions.