Free tech learning for everyone, from basics to pro

IoT NetworkingIoT SecurityIntermediate

MQTT explained: brokers, topics, QoS and retained messages

In short: MQTT is a lightweight publish/subscribe protocol in which devices send messages to a broker under named topics and other clients subscribe to the topics they care about. QoS levels, retained messages and the last will feature make it reliable on poor networks. It is simple, but it must be secured with authentication, TLS and topic permissions.

Why publish/subscribe suits IoT

MQTT (originally MQ Telemetry Transport) is a messaging protocol designed for small devices on unreliable links. It runs over TCP, normally on port 1883, or port 8883 when wrapped in Transport Layer Security (TLS). The current versions are 3.1.1 and 5.0, both OASIS standards.

Instead of a device talking directly to the system that needs its data, every client connects to a central server called the broker. A client publishes a message to a topic, and the broker forwards it to every client that has subscribed to that topic. Publishers and subscribers do not need to know each other's addresses, or even be online at the same time.

Publish/subscribe around a brokerBrokerroutes by topicSensor Apublishes tempSensor Bpublishes humidityDashboardsubscribes home/#Rules enginesubscribes alertsActuatorsubscribes cmd topicLoggersubscribeseverything
Figure 1. Clients never talk to each other directly; they publish to and subscribe through a central broker.

This decoupling is the main attraction. You can add a new dashboard, database or alerting service just by subscribing, without touching the sensors. The connection is opened by the device outwards to the broker, so devices behind Network Address Translation (NAT) work without port forwarding. Popular brokers include Eclipse Mosquitto, EMQX, HiveMQ and VerneMQ, and the large cloud IoT platforms offer MQTT endpoints too.

Topics and wildcards

A topic is a UTF-8 string split into levels by forward slashes, for example site1/lab/rack3/temperature. Topics are created on the fly; there is nothing to register. Subscribers can use two wildcards:

  • + matches exactly one level: site1/+/rack3/temperature matches any room.
  • # matches all remaining levels and must come last: site1/lab/# matches everything in the lab.

Good topic design pays off later. Put the general part first and the specific part last, keep a consistent pattern such as <site>/<area>/<device-id>/<measurement>, avoid spaces and leading slashes, and keep commands on separate topics from telemetry (for example .../cmd/relay) so you can grant permissions precisely. Topics beginning with $, such as $SYS/, are reserved for broker information.

mosquitto_sub -h broker.example.com -p 8883 --cafile ca.crt -u dash -P '<password>' -t 'site1/lab/#' -v
mosquitto_pub -h broker.example.com -p 8883 --cafile ca.crt -u sensor01 -P '<password>' -t 'site1/lab/sensor01/temperature' -m '21.4' -q 1

Quality of service, retained messages and last will

MQTT quality of service levelsQoS 0: at most oncefire and forget, may be lostQoS 1: at least oncePUBACK, duplicates possibleQoS 2: exactly oncefour-step handshake, slowest
Figure 2. Higher QoS levels add acknowledgements, trading bandwidth and battery for delivery guarantees.

Each publish and subscription carries a quality of service (QoS) level. The broker delivers at the lower of the publisher's and the subscriber's QoS. Use QoS 0 for frequent readings where losing one does not matter, QoS 1 for most events and alerts (make the receiver tolerate duplicates), and QoS 2 only when a duplicate would cause harm, such as a billing count.

FeatureWhat it doesTypical use
Retained messageBroker keeps the last message on a topic and sends it to new subscribers at onceCurrent state: "door closed", last temperature
Last will and testament (LWT)Message the broker publishes if a client disconnects without saying goodbyeMark a device offline
Keep aliveClient pings within an agreed interval so dead links are detectedBattery and cellular devices
Persistent sessionBroker remembers subscriptions and queues QoS 1/2 messages while a client is awayDevices that sleep

MQTT 5 adds useful features: reason codes on every acknowledgement, message and session expiry, user properties (key/value metadata), shared subscriptions for load balancing ($share/group/topic), topic aliases to save bytes, and request/response helpers. If your broker and libraries support version 5, prefer it for new projects.

Security and common mistakes

MQTT itself provides only a username and password field. Everything else comes from the broker configuration. Brokers left open on the internet with anonymous access are regularly found by scanners, exposing data and sometimes allowing anyone to publish commands.

  • Turn off anonymous access and give every device its own credentials or, better, its own client certificate.
  • Use TLS on 8883 so passwords and data are not sent in clear text.
  • Apply access control lists (ACLs): a sensor may publish only to its own topics, and only the controller may publish to cmd topics.
  • Validate payloads on the subscriber side; a broker forwards whatever it receives.
  • Do not subscribe to # in production apps; it wastes bandwidth and hides permission mistakes.

Tip: in exams, remember three numbers: port 1883 (plain), port 8883 (TLS) and QoS 0, 1 and 2. At work, the most valuable habit is writing the topic plan and the ACL file together, before any device is flashed.

Practice

A subscriber uses QoS 0 and the publisher uses QoS 2. Which QoS is used for delivery to that subscriber?
QoS 0. The broker delivers at the lower of the two levels, so the subscriber gets at-most-once delivery.
Which wildcard would match home/kitchen/temp and home/garage/temp but not home/garage/fridge/temp?
home/+/temp. The + wildcard matches exactly one level, whereas # would also match deeper levels.
How can a dashboard show that a device has lost power?
Configure a last will message such as 'offline' on the device's status topic, ideally retained. The broker publishes it when the device disappears without a clean disconnect.

Key takeaways

  • MQTT is publish/subscribe: clients talk only to a broker, using topics.
  • Wildcards: + matches one level, # matches all remaining levels.
  • QoS 0, 1 and 2 trade overhead for delivery guarantees.
  • Retained messages, last will and persistent sessions handle state and sleepy devices.
  • Secure it with unique credentials, TLS on port 8883 and per-topic ACLs.
Tracks your learning on this device only. See your progress on the learning paths.

About the author

Mohamed Fayas

Founder of FM TecHub. CCNA certified, with a BTEC HND in Network Engineering, and BEng (Hons) in Computer Networking and Cloud Security. He writes practical, plain-English guides on networking, security and cloud.

More about the author

Original content written by Mohamed Fayas for FM TecHub. © 2026 FM TecHub. You're welcome to share a link to this page; please don't copy the text elsewhere without permission.

Stay up to date by email

New notes, tools and security news from FM TecHub, explained simply. Free.

We only use your email to send these updates. See our privacy policy.