MQTT
medium 32 minMQTT 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
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
- 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
criticalA lock that restarts next week receives the old unlock again.
Wrongpublish("lock/cmd", "unlock", retain=True)Rightpublish("lock/cmd", "unlock", qos=1, expiry=10)Anonymous broker on the internet
criticalAnyone can read all topics and send commands.
Wronglistener 1883allow_anonymous trueRightlistener 8883allow_anonymous falserequire_certificate trueSame client ID in every device
criticalEach connection takes over the one before, without end.
WrongClient(client_id="sensor")RightClient(client_id=device_serial)Reconnect without a random delay
majorAfter an outage all devices arrive in the same second.
Wrongsleep(5); connect()Rightsleep(random() * min(300, 2 ** tries)); connect()QoS 2 as exactly-once processing
majorA crash between receiving and saving still loses or repeats work.
Wrongon_message: charge(card)Righton_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.