MQTT/The post office/Why a post office

Why a post office

A sensor that sends its reading straight to a phone has to know the phone's address, and breaks the day the phone moves. MQTT puts a post office in the middle, and every device needs only one address.

The obvious way to get a temperature from a sensor to a phone is to have the sensor send it to the phone. For that, the sensor's program has to hold the phone's address — an IP address such as 192.168.1.23 — and the phone has to be switched on and listening when the reading goes out.

Both of those stop being true in ordinary use. A phone that joins another Wi-Fi network gets a new address, and the sensor keeps posting to the old one. A phone that is asleep takes nothing. A second phone, or a laptop that wants to log the readings, means another address typed into the sensor's program and the program loaded again, for every new reader.

One address for everybody

MQTT's answer is a post office in the middle, called the broker. Every device connects to the broker and to nothing else. The sensor posts its reading to the broker; the broker delivers a copy to every device that has asked for it.

So each device needs exactly one address, the broker's, and nobody needs anybody else's. A phone that changes network connects to the broker again and carries on. A new reader tells the broker what it wants, and the sensor's program never changes.

A single lit post-office counter in a dark room, lines of light converging on it from every direction
Everybody connects to the post office, and to nothing else.Generated illustration

The broker is a program on a computer that is always on: a Raspberry Pi at home, a server, or a service on the internet. The devices are its clients — every one of them, whether it sends readings, receives them, or both.

The post office is a picture, and one thing about it is wrong: a real broker delivers in a few thousandths of a second, not in days. The rest of this course keeps the picture, because every rule in MQTT is a rule of this post office — what is written on the envelope, who gets a copy, what is kept, and what happens when a letter or a device goes missing.

Common mistakes

  • Hard-coding a phone's address into the board. It works on the desk and fails the first time the router hands out a different address.
  • Thinking of the broker as the phone's app. The broker is a separate program, on a computer that stays on. The phone is a client of it, exactly as the sensor is.
  • Two devices "talking MQTT" to each other. They never do. Both talk to the broker; there is no MQTT between two clients.

Edit this page — content/fundamentals/mqtt/why-a-post-office.mdx

Discuss this article

Ask about this page. The answer stays here, on the page it belongs to, for whoever hits the same wall next.

Browse Fundamentals on the forum →