MQTT
Publish/subscribe, topics, wildcards, QoS, retained messages and wills.
A protocol built for small devices on bad networks
MQTT is a lightweight publish/subscribe messaging protocol running over TCP (port 1883, or 8883 with TLS). It is the most common way IoT devices send telemetry to the cloud and receive commands: AWS IoT Core, Azure IoT Hub, HiveMQ, Mosquitto and most industrial IoT platforms use it.
Its design goals match embedded constraints: a minimal 2-byte fixed header, a small client footprint, and features for unreliable links and devices that sleep.
Publish/subscribe through a broker
Clients never talk to each other directly. They connect to a broker and:
- publish messages to a topic (a string such as
site7/pump3/pressure) - subscribe to topics they are interested in
The broker forwards each published message to every client subscribed to a matching topic. Publishers and subscribers do not know about each other, do not need to be online at the same time (with persistent sessions), and can be added without changing anything else.
Topics and wildcards
Topics are hierarchical, separated by /. Subscriptions may use wildcards:
| Wildcard | Matches | Example subscription | Matches |
|---|---|---|---|
+ | Exactly one level | site7/+/pressure | site7/pump3/pressure, not site7/a/b/pressure |
# | Any number of levels; must be last | site7/# | everything under site7 |
#include <stdio.h>
#include <string.h>
/* Returns 1 if an MQTT topic matches a subscription filter with + and # wildcards. */
static int topic_matches(const char *filter, const char *topic) {
while (*filter) {
if (*filter == '#') return 1; /* matches the rest */
if (*filter == '+') { /* skip one level in the topic */
while (*topic && *topic != '/') topic++;
filter++;
} else {
if (*filter != *topic) return 0;
filter++; topic++;
continue;
}
if (*filter == '\0') return *topic == '\0';
if (*filter != *topic) return 0; /* both should be at '/' */
filter++; topic++;
}
return *topic == '\0';
}
int main(void) {
const char *t = "site7/pump3/pressure";
const char *filters[] = { "site7/pump3/pressure", "site7/+/pressure", "site7/#", "+/pump3/+", "site7/+", "site8/#" };
for (int i = 0; i < 6; i++) printf("%-22s %s\n", filters[i], topic_matches(filters[i], t) ? "match" : "-");
return 0;
}
Topic design tips: put the most general part first (tenant/site/device/measurement), keep topics short (they are sent in every publish), never put secrets in them, and use separate topics for telemetry (.../telemetry) and commands (.../cmd).
Quality of service
Each publish and subscription has a QoS level. The effective level is the lower of the publisher's and the subscriber's.
| QoS | Name | Guarantee | Packets | Use |
|---|---|---|---|---|
| 0 | At most once | Fire and forget; may be lost | PUBLISH | Frequent telemetry where the next sample replaces a lost one |
| 1 | At least once | Delivered, possibly duplicated | PUBLISH, PUBACK | Most events and commands; make handlers idempotent |
| 2 | Exactly once | Delivered once | PUBLISH, PUBREC, PUBREL, PUBCOMP | Rarely needed; costs a four-way handshake |
QoS is per hop (publisher to broker, broker to subscriber), not end to end. QoS 1 with idempotent processing (include a message ID or sequence number, ignore repeats) is the usual choice.
Sessions, retained messages and wills
- Clean session / persistent session: with a persistent session (
cleanSession=0, orClean Start=0and a session expiry in MQTT 5), the broker remembers the client's subscriptions and queues QoS 1 and 2 messages while it is offline. A device that sleeps for an hour receives the commands sent meanwhile when it reconnects. - Retained message: the broker stores the last message on a topic with the retain flag and sends it immediately to new subscribers. Use it for state ("the current set-point is 21"), not for events.
- Last will and testament (LWT): a message registered at connect time that the broker publishes if the client disconnects ungracefully (keep-alive timeout, dropped TCP). Combined with a retained "online" message published after connecting, it gives reliable presence detection:
device/42/statusisonlineoroffline.
Keep-alive
The client promises to send something at least every keep-alive interval (for example 60 s); if idle, it sends PINGREQ and the broker answers PINGRESP. If the broker hears nothing for 1.5 times the interval, it closes the connection and publishes the will. On cellular links, NAT gateways often drop idle TCP connections after a few minutes, so the keep-alive must be shorter than that.
MQTT 5 additions
User properties (metadata), reason codes on every acknowledgement, shared subscriptions (load balancing across several consumers), topic aliases (replace long topic strings with a 2-byte number), message expiry, and request/response with correlation data.
On a microcontroller
Libraries: Paho Embedded C, coreMQTT (FreeRTOS/AWS), lwIP's MQTT client, ESP-MQTT, Zephyr's MQTT library. Practical points:
- MQTT needs TCP, and on any real network, TLS (the TLS library usually costs more RAM than MQTT itself).
- Buffer sizes cap message size; keep payloads small and consider a compact encoding (CBOR, protobuf) instead of JSON.
- Implement reconnection with exponential backoff and jitter, so a fleet does not stampede the broker after an outage.
- Store unsent QoS 1 messages if they must survive a reset.
Pitfall: Using a fixed or duplicated client ID across devices makes the broker disconnect the older connection whenever a new one connects, and the two devices knock each other off endlessly. Derive the client ID from a unique hardware ID.
Interview question: Which MQTT QoS level would you use for device telemetry and for commands, and why?
Answer: Telemetry sent every few seconds usually uses QoS 0 or 1: a lost sample is replaced by the next, and QoS 0 saves bandwidth and power. Commands and important events use QoS 1, which guarantees delivery but may duplicate, so handlers must be idempotent, for example by including a command ID and ignoring repeats. QoS 2 is rarely worth its extra round trips on constrained devices. Combine with persistent sessions so commands sent while a device sleeps are delivered on reconnect.
Interview question: How would you show in a dashboard whether each device is online, using MQTT?
Answer: At connect, each device registers a last-will message "offline" on its status topic with the retain flag. Immediately after connecting it publishes "online" to the same topic, also retained. If it disconnects cleanly it publishes "offline" itself; if it drops off the network, the broker publishes the will after the keep-alive timeout. The dashboard subscribes to the status topics and, thanks to retain, receives every device's current state immediately on subscribing.
Build it: publish the readings over MQTT
This is step 4 of the module project, the office air-quality monitor. The cloud service is moving to an MQTT broker, and the monitor has too little flash for a full client library, so it builds the few packets it sends itself. Every reading goes out as a PUBLISH: the CO2 level each minute at QoS 0 (a lost one is replaced a minute later), and the monitor's status at QoS 1 with the retain flag, so a dashboard that subscribes later still sees whether the monitor is online.
Lab: Encode MQTT PUBLISH packets
mqtt_put_len(out, len)writes MQTT's remaining length: 7 bits per byte, lowest 7 bits first, bit 7 set on every byte except the last. It returns the number of bytes written (1 to 4), or 0 whenlenis over 268 435 455, the most that 4 bytes can hold.mqtt_publish(out, cap, topic, payload, plen, qos, retain, id)builds one PUBLISH packet inoutand returns its length:- the first byte is
0x30, with the QoS in bits 2 and 1 and the retain flag in bit 0; - then the remaining length: the number of bytes that follow it;
- the topic as a 2-byte big-endian length and its characters (no terminating zero);
- at QoS 1 only, the 2-byte big-endian packet identifier;
- then the payload, with no length of its own (the remaining length implies it).
Return 0, writing nothing that matters, when the packet would not fit in cap bytes, when qos is above 1 (this client does not do QoS 2), or for QoS 1 with packet identifier 0, which MQTT does not allow.
Going deeper
Interview question: How would you design MQTT messaging for a fleet of connected greenhouses?
Answer: A topic hierarchy per site and device (site/greenhouse/telemetry, .../commands), telemetry at QoS 0 or 1 depending on value, commands at QoS 1 with idempotent handling, retained state messages, and a last-will message to show a device offline. Authenticate each device with its own certificate over TLS, and buffer telemetry locally during outages.
Interview question: What are shared subscriptions in MQTT 5 and why are they useful?
Answer: A shared subscription ($share/group/topic) lets several clients subscribe as a group; the broker delivers each message to only one member of the group, balancing load among them. This allows horizontally scaling the backend services that consume device telemetry without each message being processed several times.
Interview question: How do you send a command to a device and get a reply over MQTT?
Answer: The device subscribes to its command topic. The sender publishes the command (QoS 1, with a unique command ID) and, in MQTT 5, sets a response topic and correlation data; the device processes it idempotently and publishes the result to the response topic with the same correlation data. With MQTT 3.1.1 the same pattern uses conventional topic names and an ID in the payload. Persistent sessions ensure commands reach devices that were offline.
Explain it: In your own words, explain the difference between QoS 0, 1 and 2 in MQTT.
Answer: QoS 0 sends a message once with no acknowledgement, so it may be lost but costs the least, which suits frequent telemetry. QoS 1 resends until the receiver acknowledges, so the message is guaranteed to arrive but may arrive more than once, so the receiver must tolerate duplicates. QoS 2 uses a four-step handshake so each message is delivered exactly once, at the cost of extra round trips, and is rarely needed. QoS applies to each hop, publisher to broker and broker to subscriber, and the effective level is the lower of the two.