Skip to content

Guide

MQTT Explained: Broker, Topics, Wildcards, QoS, Retained Messages and Last Will

Understand MQTT properly: publish/subscribe, topics and wildcards, QoS levels, retained messages, sessions and Last Will, with hands-on terminal demos and ESP32 code.

  • 9 min read
  • Updated November 2, 2026
MQTT Explained: Broker, Topics, Wildcards, QoS, Retained Messages and Last Will

Quick answer: MQTT is a lightweight publish/subscribe messaging protocol. Devices never talk to each other directly. They connect to a broker (such as Mosquitto on port 1883, or 8883 with TLS), publish messages to topics like home/kitchen/temperature, and subscribe to topics they care about, using the wildcards + (one level) and # (everything below). QoS sets how hard each hop tries to deliver: 0 = at most once, 1 = at least once (duplicates possible), 2 = exactly once. A retained message is the "last known value" the broker hands to new subscribers. A Last Will (LWT) is a message the broker publishes for a client that disconnects unexpectedly, which is how dashboards show "offline".

TermOne-line meaning
BrokerServer that routes every message (Mosquitto, EMQX, HiveMQ)
ClientAny device or program connected to the broker; needs a unique client ID
TopicSlash-separated channel name, e.g. home/kitchen/light/set
+ / #Single-level / multi-level wildcard, subscribe only
QoS 0 / 1 / 2At most once / at least once / exactly once, per hop
RetainedBroker keeps the latest message per topic for new subscribers
Last WillMessage the broker sends if a client vanishes
Keep-alivePing interval; ~1.5× without contact = connection treated as dead
Clean / persistent sessionForget / remember subscriptions and queued messages while offline

Why MQTT Exists

MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol built for devices that are small, numerous and connected over networks that are not always reliable. It lets a sensor, a microcontroller, a server and a dashboard exchange data without any of them needing to know the address of the others.

Most beginners first meet it through an ESP32 publishing a temperature to a broker. Underneath that simple picture sits a carefully designed set of ideas: a publish/subscribe model, hierarchical topics, three delivery guarantees, saved state and a way to announce failure. Once you understand those five ideas, MQTT stops being mysterious, and most of its odd behaviours become predictable.

This guide explains the concepts without requiring any code, then gives you a few terminal commands so you can watch each idea happen on your own computer. It covers MQTT 3.1.1, which most hobby libraries use, and notes where MQTT 5 differs.

MQTT versus polling over HTTP

HTTP pollingMQTT
ModelClient asks, server answersClients publish and subscribe through a broker
New dataSeen only on the next pollDelivered as soon as it is published
OverheadFull request and headers every timeA persistent connection and a tiny packet header (as little as 2 bytes)
Many consumersEach one polls on its ownThe broker fans the message out
Delivery guaranteesBuilt by the applicationThree QoS levels in the protocol
Knowing a device diedBuild it yourselfLast Will and keep-alive are part of the protocol

HTTP is still the right tool for web pages and one-off requests. MQTT shines when many small messages move between many devices.

The Publish/Subscribe Model

In MQTT, the two ends of a conversation never talk to each other directly. A broker sits in the middle:

  • A publisher sends a message to the broker under a topic, such as home/kitchen/temperature.
  • A subscriber tells the broker which topics it is interested in. The broker forwards matching messages to it.
  • A single client can be both: an ESP32 might publish sensor readings and subscribe to a command topic.

This decouples publishers from subscribers in three ways. They do not need each other's addresses (space), they do not need to be online at the same moment when the right options are used (time), and the publisher never waits for subscribers (synchronisation). You can add a logger, a dashboard or a second controller without changing the sensor at all.

A message is just a topic plus a payload (bytes: text, a number or JSON) and a few flags. The broker does not interpret the payload, so the agreement about what 23.5 or {"t":23.5} means belongs to you.

Two ESP32 publishers send to an MQTT broker, which routes messages by topic to Node-RED, a phone dashboard and a data logger; a topic tree shows how the + and # wildcards match

The four pieces to remember

  • Broker: the server that accepts connections and routes messages. Eclipse Mosquitto is the most common open-source choice. Standard ports are 1883 (plain) and 8883 (TLS).
  • Client: anything that connects, whether a microcontroller, a script or a phone app. Each needs a client ID that is unique on the broker.
  • Topic: a UTF-8 string with levels separated by slashes.
  • Payload: the data. It can be up to 256 MB in the specification, but IoT messages are normally a few bytes.

Every client also sets a keep-alive interval. If the broker hears nothing from a client for about one and a half times that interval, it treats the connection as dead. That timer is what makes the Last Will feature work.

Topics and Wildcards

Topic rules that save you pain

  • Topics are case sensitive: Home/Kitchen and home/kitchen are different.
  • A topic must contain at least one character, and it cannot contain the wildcard characters + or # when publishing.
  • A leading slash creates an empty first level, so /home is not the same as home. Avoid it.
  • Avoid spaces and non-ASCII characters, which cause trouble in many tools.
  • Topics starting with $ (such as $SYS/...) are reserved for the broker, and normal wildcards do not match them at the first level.

Wildcards: only for subscribing

WildcardMatchesExample filterMatches
+Exactly one levelhome/+/temperaturehome/kitchen/temperature, home/bedroom/temperature
#Everything below, and must be the last characterhome/kitchen/#home/kitchen/temperature, home/kitchen/humidity

# also matches the parent level itself, so home/# includes a message published to home. A subscription to plain # receives almost everything on the broker, which is useful for debugging and dangerous in production.

Designing a topic hierarchy

Spend ten minutes on naming before you deploy twenty devices. A pattern that scales well is where / what / property, with a separate branch for commands and status:

Output
home/kitchen/temperature       sensor data
home/kitchen/light/set         command to a device
home/kitchen/light/state       state reported by the device
devices/esp32-1/status         online / offline (retained)

Put the more general parts first so wildcards stay useful. Use one topic per measurement instead of one topic that carries unrelated data, and keep command topics clearly separate from state topics so a device cannot echo its own command in a loop.

terminal
mosquitto_pub -h localhost -t "home/kitchen/temperature" -m "23.5"
mosquitto_pub -h localhost -t "home/bedroom/temperature" -m "21.0"
mosquitto_pub -h localhost -t "home/kitchen/humidity" -m "48"

Try It in Two Minutes

If you have Mosquitto installed on a computer (see the Raspberry Pi 5 guide linked at the end), you can watch publish/subscribe happen. Open two terminals.

Terminal 1: subscribe with a wildcard and print topic names

terminal
mosquitto_sub -h localhost -t "home/+/temperature" -v

Terminal 2: publish to two matching topics and one that does not match

terminal
mosquitto_pub -h localhost -t "home/livingroom/temperature" -m "22.5"
mosquitto_pub -h localhost -t "home/kitchen/temperature" -m "24.1"
mosquitto_pub -h localhost -t "home/livingroom/humidity" -m "55"

Terminal 1 prints the first two messages with their topics and ignores the humidity message, because it does not match the filter home/+/temperature. Change the filter to home/# and publish again to see all three.

Two terminals: mosquitto_sub with a wildcard filter printing only the matching messages

Quality of Service (QoS)

QoS is an agreement between one sender and one receiver about how hard to try to deliver a single message. It applies separately on each hop: publisher to broker, then broker to each subscriber.

QoSGuaranteePacketsUse it for
0At most once. Fire and forget, with no acknowledgement.1Frequent readings where the next value replaces a lost one
1At least once. Resent until acknowledged, so duplicates are possible.2Events that must arrive, when your handler tolerates repeats
2Exactly once at the protocol level, through a four-step handshake.4Rare cases where a duplicate would be harmful and you cannot make the handler idempotent

Two details trip people up:

  1. The effective QoS is the lower of the two. If a client publishes at QoS 2 but the subscriber asked for QoS 1, the broker delivers to that subscriber at QoS 1.
  2. QoS is not application correctness. QoS 2 means MQTT will not hand your program the same message twice. It does not mean the relay physically switched exactly once. If a controller restarts before it records that it acted, you still need an acknowledgement, a sequence number, or a command that is safe to repeat ("set the light to ON" rather than "toggle the light").

For most hobby sensors, QoS 0 is fine and QoS 1 is a sensible choice for commands and state. Reach for QoS 2 only when you can explain why.

Message flow for QoS 0, 1 and 2: a single PUBLISH, a PUBLISH with PUBACK, and the four-packet PUBLISH, PUBREC, PUBREL, PUBCOMP handshake

Sessions: What Happens While a Client Is Offline

When a client connects, it can ask for a clean session (called clean start in MQTT 5), or for a persistent session. With a persistent session and a stable client ID, the broker remembers the client's subscriptions and queues QoS 1 and QoS 2 messages that arrive while it is away, then delivers them on reconnect. QoS 0 messages are not queued.

Two practical consequences:

  • Client IDs must be unique. If a second device connects with the same ID, the broker disconnects the first, which then reconnects and kicks out the second. The result is an endless reconnect loop that looks like a network problem. This is a classic bug when several ESP32 boards share a copied sketch.
  • Persistent sessions cost memory on the broker and can deliver stale commands after a long outage. Use them deliberately, not by default.

Retained Messages: The Current Value, Not the History

Normally a message is delivered to whoever is subscribed at that moment and then forgotten. A subscriber that arrives a second later sees nothing until the next publication, which may be an hour away for a slow sensor.

If a publisher sets the retain flag, the broker keeps the latest retained message for that topic and sends it immediately to every new subscriber whose filter matches. This is ideal for current state, such as the last temperature, a light's state or an online/offline flag.

Output
mosquitto_pub -h localhost -t "devices/esp32-1/status" -m "online" -r -q 1

A few rules to remember:

  • Only one value per topic is stored. A new retained message replaces the old one, so retained messages are not a history.
  • Clear a retained message by publishing an empty payload with the retain flag: mosquitto_pub -h localhost -t "devices/esp32-1/status" -n -r.
  • Never retain one-shot commands such as TOGGLE, UNLOCK or PULSE. A device that reconnects would receive the old command and repeat the action at a surprising moment.
  • Retained messages survive until cleared, so remember to clean up the topics of test devices that no longer exist.

Last Will and Testament (LWT)

Devices fail without saying goodbye: power is cut, Wi-Fi drops, a battery dies. MQTT's answer is the Last Will. When a client connects, it can register a will: a topic, a payload, a QoS and a retain flag. If the broker later decides the connection died unexpectedly, it publishes that message on the client's behalf.

The standard availability pattern uses two retained messages on one status topic:

  1. On connect, register a will of offline (retained) on devices/esp32-1/status.
  2. Right after connecting, publish online (retained) to the same topic.
  3. If the device vanishes, the broker publishes the will, and the retained value flips to offline.
  4. Any dashboard that subscribes later immediately sees the correct state.
Timeline of the availability pattern: will registered, online published, link lost, broker publishes offline, and a late subscriber receiving the retained value

Seeing the will fire

You can reproduce this with the command line tools. In one terminal, watch the status topic. In a second, start a subscriber that registers a will:

terminal
# Terminal 1: watch status
mosquitto_sub -h localhost -t "devices/demo/status" -v
terminal
# Terminal 2: a client that registers a will
mosquitto_sub -h localhost -t "test" -q 1 \
  --will-topic "devices/demo/status" --will-payload "offline" --will-retain
terminal
# Terminal 3: find the process and kill it abruptly
pkill -9 -f "mosquitto_sub.*--will-topic"

Terminal 1 prints devices/demo/status offline after the broker notices the dead connection. A normal Ctrl+C will not trigger it, because a clean DISCONNECT tells the broker the exit was intentional and the will is discarded. For a planned shutdown, publish offline yourself first.

What the will cannot do

The will is not an instant hardware alarm. The broker acts only after it detects the broken connection, which can take up to about one and a half times the keep-alive interval, so a 60-second keep-alive can mean a delay of around 90 seconds. For a dependable dashboard, combine availability with a timestamp of the last valid reading and a clearly defined "stale data" threshold.

The Same Ideas in ESP32 Code

With the PubSubClient library, QoS, retain and Last Will are just arguments:

sketch.ino
// connect(clientId, user, pass, willTopic, willQos, willRetain, willMessage)
mqtt.connect("esp32-kitchen", "kitchen", "secret",
  "home/kitchen/status", 1, true, "offline");   // Last Will

mqtt.publish("home/kitchen/status", "online", true);      // retained availability
mqtt.publish("home/kitchen/temperature", "23.5");         // normal reading, QoS 0
mqtt.subscribe("home/kitchen/light/set", 1);              // commands at QoS 1

PubSubClient publishes at QoS 0 only, but can subscribe at QoS 0 or 1. For QoS 1/2 publishing on an ESP32, use a library such as AsyncMqttClient or the ESP-IDF MQTT client. Full walk-throughs: ESP32 MQTT publish and subscribe and ESP32 retained messages and Last Will.

Which Broker Should You Use?

BrokerWhere it runsGood for
MosquittoRaspberry Pi, PC, NAS, DockerHome and lab use: tiny, reliable, the default choice
Home Assistant Mosquitto add-onInside Home AssistantHA users: one-click install, users managed in HA
EMQX / HiveMQ (self-hosted or cloud)Servers, cloudLarge numbers of devices, clustering, dashboards, MQTT 5 features
Public test brokers (test.mosquitto.org, broker.emqx.io, broker.hivemq.com)InternetTwo-minute experiments only: everyone can read and write your topics

For almost every hobby project, Mosquitto on a Raspberry Pi is the right start: install Mosquitto on a Raspberry Pi.

MQTT Does Not Make a System Secure

An MQTT broker is only as safe as its configuration:

  • Recent Mosquitto releases (2.0 and later) refuse remote connections until you configure a listener and an authentication method. That is deliberate. Older tutorials that open an anonymous listener are not a safe pattern to copy.
  • Authentication: give every device its own username and password, so you can revoke one without touching the others.
  • Authorisation: use ACLs so each client can read and write only the topics it needs. A thermometer should not be able to publish to a door-lock command topic.
  • Encryption: use TLS on port 8883 whenever traffic crosses a network you do not control. Plain 1883 sends credentials and payloads in clear text.
  • Exposure: never publish an anonymous broker straight to the internet.

Topic names are not access control. A hard-to-guess topic is not a substitute for authentication and ACLs.

MQTT 5 in One Paragraph

MQTT 5 keeps the same model and adds features that matter at scale: reason codes on acknowledgements, session and message expiry intervals, user properties, request/response hints, topic aliases, and shared subscriptions, which let several workers split a stream of messages. Many hobby libraries still speak 3.1.1, and everything above applies to both versions.

Common Mistakes

MistakeWhat happensFix
Two devices share a client IDConstant disconnects and reconnectsBuild the ID from the chip's unique MAC address.
Retaining commandsDevices act on stale commands after reconnectingRetain state, never commands.
Subscribing to # in productionFloods the client and exposes private dataSubscribe to specific filters.
Using QoS 2 everywhereSlower throughput and no real benefitChoose the lowest QoS that meets the need.
Trusting LWT to be instantA device looks online for a while after failingAdd a last-seen timestamp.
Leading slash in topicsAn empty first topic level and confusing filtersStart topics with a word.
Anonymous broker on the internetAnyone can read and control your devicesUse credentials, ACLs and TLS.

Frequently Asked Questions

Is MQTT only for IoT? No. It is also used in messaging backends, telemetry pipelines and mobile notifications, but its small footprint makes it a natural fit for devices.

Does the broker store my data? Only retained messages and queued messages for persistent sessions. For history, subscribe with a logger that writes to a database.

Can a client be offline and still receive messages? Yes, with a persistent session and QoS 1 or 2, the broker queues messages until it returns.

How big can a message be? The specification allows 256 MB, but brokers and devices usually set far lower limits. Keep IoT payloads small.

Should I send plain text or JSON? Plain numbers are lightest for single values. Use JSON when a reading has several fields, and keep the format consistent.

Summary

MQTT is a broker-centred publish/subscribe protocol. Topics name the channels, wildcards select groups of them, QoS describes how hard each hop tries to deliver, retained messages give newcomers the current state, sessions decide what an offline client misses, and Last Will lets the broker announce that a device has vanished. Pair that with authentication, ACLs and TLS, and you have a solid base for a connected project.

Continue learning

Related articles

All articles

Signal In

Built from what makers search for

The lookups piling up in SolderHub's search bar every day shape what we publish next — new component pages, board guides, and firmware notes, sent out as they go live.

By subscribing you agree to our Privacy Policy. Unsubscribe anytime.