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.

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

Our systemPublisherAPI gatewayauth, routingBrokerleader of P2Message logreplicatedPull readerPush workerretriesEndpoint

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

Our systempublishcopycopyPublisherBroker A leader500Broker B500Broker C500

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

    critical

    The leader can die before anyone else has the record.

    Wrong
    log.append(record)return "ok"
    Right
    log.append(record)wait_for_in_sync(record)return "ok"
  • A failing filter that lets everything in

    major

    A filter that cannot be read should be refused when the subscription is created, not treated as no filter.

    Wrong
    except Exception:    return True
    Right
    raise InvalidFilter(text)  # at creation
  • Reading from the start every time

    major

    Without moving the cursor, each pull scans more finished messages until it finds nothing new.

    Wrong
    log[0:limit] minus acked
    Right
    log[cursor:] minus done above cursor
  • Dead letters nobody reads

    major

    Messages disappear politely.

    Wrong
    dead.append(m)
    Right
    dead.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.