Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 36 ยท MQTT and Messaging

MQTT: The Publish/Subscribe Model

Learn how MQTT works: brokers, clients, topics, publishers and subscribers, why pub/sub suits IoT devices, and a runnable in-process broker to try it.

Most IoT devices are small, battery powered and connected through links that drop out without warning. A thermostat in a basement and a dashboard in a browser cannot call each other directly: one is asleep most of the time, the other does not know the thermostat's address. MQTT (Message Queuing Telemetry Transport) solves this with a middleman called a broker. Devices never talk to each other; they talk to the broker, and the broker passes messages along.

MQTT is a lightweight protocol that runs on top of TCP (usually port 1883, or 8883 with TLS). Its fixed header is only two bytes, which is why it became the default language of sensors, gateways and cloud IoT services. In this lesson you will learn the roles in the model and build a miniature broker you can run in the editor. The next lessons add topics and wildcards, quality of service and retained messages.

Our editor has no network hardware. The broker below runs inside one program so you can see the logic. A real broker such as Mosquitto or EMQX uses the same ideas over TCP.

The three roles

MQTT has three roles

Publisher Sends a message to a topic
Broker Receives and routes messages
Subscriber Asks for messages on a topic

One client can be publisher and subscriber at once

1 / 2
  • A client is any program with an MQTT library: a microcontroller, a phone app, a server script. Every client connects to the broker with a client ID.
  • The broker keeps a list of subscriptions. When a message arrives, it delivers a copy to every client whose subscription matches.
  • A topic is a text label such as home/kitchen/temperature. Publishers choose it; subscribers filter by it.
  • A payload is the message body: bytes. Many projects use plain numbers or JSON, but MQTT does not care.

This pattern is called publish/subscribe. Compare it with request/response (HTTP), where the client must know the server and wait for an answer. With pub/sub, the publisher does not know who, if anyone, is listening. That property is called decoupling, and it has three flavors: in space (no addresses), in time (the broker can hold messages for offline clients, see sessions) and in synchronization (publishing does not block until someone reads).

flowchart LR
  S1["Temp sensor<br/>publishes home/temp"] --> B(("Broker"))
  S2["Door sensor<br/>publishes home/door"] --> B
  B --> D["Dashboard<br/>subscribed to home/#"]
  B --> A["Alert service<br/>subscribed to home/door"]

Publishers and subscribers never see each other, only the broker.

A broker in 20 lines

The program below implements the core of a broker: a table of subscriptions and a publish function that calls each subscriber. It matches topics by exact text only; the next lesson adds wildcards.

Node.js A minimal in-process broker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The garage reading was accepted and thrown away. That is normal MQTT behavior: a message to a topic with no subscribers is not an error. Notice that sensor-1 never mentions the dashboard or the logger; adding a third subscriber changes nothing for the sensor.

Many publishers, many subscribers

Real systems have dozens of devices. The next example adds a controller that both subscribes and publishes, which is how rules and automation are usually built: read a sensor topic, publish a command topic.

Node.js Subscribing and publishing from one client

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The controller is a subscriber (to the sensor) and a publisher (to the heater) at once. Neither the sensor nor the heater knows the controller exists, so you can replace it with a smarter one without touching any device.

How real clients look

On a microcontroller you would use a library such as PubSubClient. This code is read-only (it needs an ESP32 and Wi-Fi):

C++
#include <WiFi.h>
#include <PubSubClient.h>

WiFiClient net;
PubSubClient mqtt(net);

void setup() {
  WiFi.begin("my-ssid", "my-password");
  while (WiFi.status() != WL_CONNECTED) delay(200);
  mqtt.setServer("broker.local", 1883);
  mqtt.connect("esp32-kitchen");
}

void loop() {
  mqtt.loop();                                  // keep the connection alive
  mqtt.publish("home/kitchen/temp", "21.5");
  delay(10000);
}

On a laptop, Mosquitto's command-line tools do the same (read-only, they need an installed broker):

Terminal
mosquitto_sub -h localhost -t "home/#" -v
mosquitto_pub -h localhost -t "home/kitchen/temp" -m "21.5"

Common mistakes

  • Treating MQTT as a queue. Plain subscriptions are not queues; a message goes to whoever is connected and subscribed at that moment.
  • Using one client ID for two devices. The broker disconnects the older one, and both devices keep reconnecting in a loop.
  • Forgetting mqtt.loop() (or the equivalent). Without it the client misses pings and the broker drops it.
  • Publishing huge payloads. MQTT allows up to 256 MB, but constrained devices and many brokers do not cope; keep messages small.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which component receives every message and decides which clients get a copy?

    The broker keeps the subscription table and routes each message to matching subscribers.
  2. 2. What does it mean that publishers and subscribers are decoupled?

    Decoupling means no addresses and no direct connection between the two sides; only the broker is known.
  3. 3. A device publishes to a topic that has no subscribers. What happens?

    Without retained messages, a message with no matching subscriber is simply discarded.
  4. 4. Which TCP port does MQTT without TLS use by default?

    1883 is plain MQTT and 8883 is MQTT over TLS. 5683 is CoAP.

Summary

  • MQTT is a small publish/subscribe protocol over TCP, built for constrained devices and unreliable links.
  • Clients connect to a broker; they never connect to each other.
  • Publishers send payloads to topics; the broker delivers copies to matching subscribers.
  • Decoupling in space, time and synchronization makes systems easy to extend.
  • A client can be publisher and subscriber at the same time, which is how automation rules work.

Next: Topics, Wildcards and Best Practices