AlgoViz

MQTT

medium 32 min

MQTT is a small publish/subscribe protocol for devices on weak networks.

See it run

Messages through a broker by topic: routing, delivery levels, stored state, absent clients and the last will.

Operations

Publish and subscribe

Two devices, two listeners, one broker.

Step 1 of 5

Connect

ThermometerkitchenDoor sensorhallBrokerMQTTPhone appconnectedRules serviceconnected

Four connections, none between clients

Each client opens one connection and sends CONNECT. The broker answers CONNACK.

Step 1: Connect

def publish(topic, payload, qos):    for client in sessions:        levels = [q for f, q in client.subs                  if matches(f, topic)]        if levels:            send(client, topic, payload,                 min(qos, max(levels)))
Time
Two hops
Broker keeps
Subscriptions

The device does not know who listens. Say that first.

In the real world

The same mqtt doing real jobs. Pick one and step through it.

100,000 devices come back after an outage.

Step 1 of 3

All at once

connect nowDevices100,000Brokerhandshakes
CPU
100%

Retries make it worse

Without a random delay, 100,000 TLS handshakes arrive within seconds. The broker's CPU is full and clients give up.

Step 1: All at once

Common mistakes

The bugs interviewers watch for, with the fix beside each.

  • Retaining a command

    critical

    A lock that restarts next week receives the old unlock again.

    Wrong
    publish("lock/cmd", "unlock", retain=True)
    Right
    publish("lock/cmd", "unlock", qos=1, expiry=10)
  • Anonymous broker on the internet

    critical

    Anyone can read all topics and send commands.

    Wrong
    listener 1883allow_anonymous true
    Right
    listener 8883allow_anonymous falserequire_certificate true
  • Same client ID in every device

    critical

    Each connection takes over the one before, without end.

    Wrong
    Client(client_id="sensor")
    Right
    Client(client_id=device_serial)
  • Reconnect without a random delay

    major

    After an outage all devices arrive in the same second.

    Wrong
    sleep(5); connect()
    Right
    sleep(random() * min(300, 2 ** tries)); connect()
  • QoS 2 as exactly-once processing

    major

    A crash between receiving and saving still loses or repeats work.

    Wrong
    on_message: charge(card)
    Right
    on_message:    if first_time(msg.id): charge(card)

Interview tips

  • How to explain it

    • Clients, one broker, topics.
    • Delivery level per hop.
    • Retained state, sessions, last will.
  • Memory trick

    • Whisper to the hub.
    • Plus is one level, hash is the rest.
    • A sealed note for the day you vanish.
  • Reach for it when

    • Many small devices on weak links.
    • You must know who is online.
    • Commands go to devices behind routers.
  • Be careful with

    • History and large files.
    • Slow subscribers and full queues.
    • Managed services that leave features out.