DEV Community

Cover image for MQTT Explained: Packets, Topics, QoS, and a Working C++ Client
Hollson
Hollson

Posted on Originally published at hollson.github.io

MQTT Explained: Packets, Topics, QoS, and a Working C++ Client

MQTT is a messaging protocol built for weak networks and low-power devices: a device keeps one long-lived connection to a server, tags each message with a topic, and the server forwards it according to who subscribed. It does not care where data is stored or who processes it — only how one message gets from A to B.

This article walks from the conceptual model down to individual bytes in a packet, then ends with working C++ publish/subscribe code.

🌐 1. What MQTT Is

IBM and Arcom designed it in 1999 for satellite telemetry links: narrow bandwidth, high latency, billed per byte, so packets had to be short. Today OASIS maintains it. The mainstream versions are 3.1.1 (standard in 2014, ISO/IEC 20922 in 2016) and 5.0 (2019).

It runs over TCP. Default port is 1883, TLS uses 8883, WebSocket uses 8083/8084. Packets are remarkably compact: a 2-byte minimum fixed header, and a complete CONNECT is usually a few dozen bytes — smaller than the headers of one HTTP request.

The division of labor with HTTP is clear. HTTP is client asks, server answers; the server cannot reach the client on its own. MQTT is a persistent connection where the server can push at any time, and one message can fan out to hundreds of subscribers at once. When you have many field devices, frequent uplink, and a need for instant downlink, that is when MQTT earns its place.

Connecting sensors, a broker, a backend, and end users gives the typical topology: sensors publish to the broker, the broker forwards to subscribed services, services write to a time-series store and serve phones and laptops over HTTPS. Devices only publish to the broker; services only read from it; neither side needs to know the other exists.

🧩 2. Core Concepts

The whole protocol is nine concepts. Everything else is detail.

Concept Role
Broker Message hub: keeps sessions, matches subscriptions, forwards
Client Any connected device or service; can publish and subscribe
Topic Hierarchical string like home/1f/bedroom/temp, levels split by /
Subscription A client's interest in a set of topics, wildcards allowed
QoS Delivery guarantee level: 0, 1, or 2
Retained Broker keeps the last message on a topic for new subscribers
LWT Last Will: sent by the broker when a client drops unexpectedly
Session Whether subscriptions and unacknowledged messages survive a disconnect
Keep Alive Heartbeat interval; no traffic for 1.5× and the peer is considered gone

Three of them get overlooked most often. Retained lets a dashboard that just came online show the current value without waiting for the next report. LWT is the only reliable signal that a device went away — a dead device cannot announce its own death. Clean Session decides whether subscriptions survive a reconnect; set it to false and offline delivery becomes possible at all.

🏷️ 3. Topics and Wildcards

A topic is a UTF-8 string split by /, case-sensitive, up to 65535 bytes, and needs no pre-creation. Wildcards only work on the subscriber side and are not allowed when publishing:

Subscription Matches
home/+/temp home/1f/temp, but not home/1f/room/temp
home/# Everything under home
# All topics except $SYS/ system topics

+ matches exactly one level; # matches all remaining levels and must come last. Under $SYS/ are the broker's own metrics; $share/ is the shared-subscription prefix that lets several consumers in a group split the load.

For naming, use {location}/{device type}/{device id}/{metric}, for example home/1f/sensor-03/temp. Two things to avoid: never start a topic with /, which creates an empty first level and makes it a different topic from home/1f; and never put values in topics — temp/23.5 creates a new topic per reading and subscribers cannot aggregate anything.

📦 4. Packet Format

Every packet is three concatenated parts: fixed header, variable header, payload. The last two are optional.

In the fixed header, the high 4 bits of the first byte are the packet type and the low 4 bits are flags (PUBLISH uses them for DUP, QoS level, and Retain). From the second byte comes the remaining length: how many bytes follow.

Remaining length uses variable-length encoding: 7 bits per byte, high bit meaning "more to come", up to 4 bytes and 268435455 bytes (about 256MB). So lengths under 128 take one byte — 127 encodes as 7F, 128 as 80 01, 16383 as FF 7F.

There are 15 packet types:

Value Name Purpose
1 CONNECT Client opens a connection
2 CONNACK Broker answers the connection
3 PUBLISH Publish a message
4 PUBACK QoS 1 acknowledgement
5 PUBREC QoS 2, first acknowledgement
6 PUBREL QoS 2, release
7 PUBCOMP QoS 2, completion
8 SUBSCRIBE Subscribe
9 SUBACK Subscription result
10 UNSUBSCRIBE Unsubscribe
11 UNSUBACK Unsubscribe result
12 PINGREQ Heartbeat request
13 PINGRESP Heartbeat response
14 DISCONNECT Client disconnects
15 AUTH Enhanced authentication in 5.0

Take a real CONNECT with client ID sensor-01, Keep Alive 60 seconds, Clean Session true:

10 15 00 04 4D 51 54 54 04 02 00 3C 00 09 73 65 6E 73 6F 72 2D 30 31
Enter fullscreen mode Exit fullscreen mode
Bytes Meaning
10 CONNECT, all flags zero
15 Remaining length 21 bytes
00 04 4D 51 54 54 Protocol name: length prefix plus MQTT
04 Protocol level 4, i.e. 3.1.1; 5.0 uses 05
02 Connect flags, bit 1 is Clean Session
00 3C Keep Alive, 60 seconds
00 09 73…31 Client ID sensor-01

The entire connection setup took 23 bytes. Version 5.0 inserts a properties block here, so the same fields come after an extra 00 (zero-length properties) following the protocol level — watch that offset when reading packets.

🔄 5. Connect and Exchange Flow

A complete interaction has five stages — connect, subscribe, publish, heartbeat, disconnect — with QoS 1 acknowledgements folded into the publish stage:

  1. Client → Broker: CONNECT(clientId, keepAlive, cleanSession).
  2. Broker → Client: CONNACK(0x00 accepted).
  3. Client → Broker: SUBSCRIBE(home/+/temp, QoS 1).
  4. Broker → Client: SUBACK(granted QoS 1).
  5. Client → Broker: PUBLISH(home/1f/temp, QoS 1, id=10).
  6. Broker → Client: PUBACK(id=10).
  7. Broker → Client: PUBLISH(to subscribers, QoS 1, id=7).
  8. Client → Broker: PUBACK(id=7).
  9. Client → Broker: PINGREQ; broker replies PINGRESP.
  10. Client → Broker: DISCONNECT.

The connect stage negotiates four things: client ID, Keep Alive, whether to wipe the session, and the will message. CONNACK returning 0x00 means accepted; every other value is a rejection reason code.

Once in steady state, an idle connection sends nothing at all, only PINGREQ/PINGRESP before Keep Alive expires. The cost of that design is that disconnect detection depends on a timeout: the broker will not declare you dead until 1.5× Keep Alive has passed. So do not set Keep Alive too large — 30 to 60 seconds is common for field devices.

🎚️ 6. The Three QoS Levels

QoS is negotiated separately between publisher and broker, and between broker and subscriber. It only concerns "did this message arrive", never business semantics.

QoS Exchange Cost Use
0 Fire and forget May lose messages High-frequency telemetry
1 PUBLISH → PUBACK May duplicate The sane default
2 PUBREC → PUBREL → PUBCOMP Two round trips, broker state Billing, switch commands

The effective level is the minimum of the two sides: if the publisher uses QoS 0, a subscriber asking for QoS 2 still gets 0. So "I subscribed with QoS 2, why did I lose messages?" is answered on the publishing side.

QoS does not guarantee ordering either. Serial publishing on one connection preserves order; across topics or connections there is no ordering promise at all. When order matters, put a monotonic sequence number in the payload and sort on the business side.

🖥️ 7. Running a Local Broker

Mosquitto is enough for development and verification: one binary, no extra dependencies.

brew install mosquitto
Enter fullscreen mode Exit fullscreen mode

Add two lines to /opt/homebrew/etc/mosquitto/mosquitto.conf so it listens on all interfaces and allows anonymous access (local debugging only):

listener 1883
allow_anonymous true
Enter fullscreen mode Exit fullscreen mode

Start it in the foreground to watch every packet:

mosquitto -c /opt/homebrew/etc/mosquitto/mosquitto.conf -v
Enter fullscreen mode Exit fullscreen mode

One behavior change from 2.0 to know: with no listener line it binds 127.0.0.1 and allows anonymous access; as soon as you add listener, it binds 0.0.0.0 and allow_anonymous defaults to false. Devices on the LAN failing to connect almost always trace back to these two lines.

If you would rather not install anything, use the container image, which ships an auth-free config:

docker run -d --name mqtt -p 1883:1883 eclipse-mosquitto:2 \
  mosquitto -c /mosquitto-no-auth.conf
Enter fullscreen mode Exit fullscreen mode

Verify before writing code; two CLI clients are enough:

mosquitto_sub -h localhost -t 'home/+/temp' -v          # subscribe
mosquitto_pub -h localhost -t home/1f/temp -m 23.5      # publish
Enter fullscreen mode Exit fullscreen mode

⚙️ 8. C++ Client in Practice

Use Eclipse Paho on the C++ side: officially maintained, both sync and async APIs, supporting 3.1.1 and 5.0. On macOS the library is one line:

brew install paho-mqtt-cpp
Enter fullscreen mode Exit fullscreen mode

On other platforms, build the C library paho.mqtt.c first, then paho.mqtt.cpp with CMake. The two versions must match.

The publisher is a short program that reports temperature in a loop, QoS 1 and Retained:

#include <chrono>
#include <iostream>
#include <mqtt/client.h>
#include <thread>

int main() {
  mqtt::client cli{"tcp://localhost:1883", "sensor-pub-01"};

  mqtt::connect_options opts;
  opts.set_keep_alive_interval(30);
  opts.set_clean_session(true);
  opts.set_automatic_reconnect(1, 30);  // retry from 1s, up to 30s

  try {
    cli.connect(opts);
    for (int i = 0; i < 5; ++i) {
      const std::string payload = std::to_string(20.0 + i * 0.5);
      // topic, payload, length, QoS, retained
      cli.publish("home/1f/temp", payload.data(), payload.size(), 1, true);
      std::cout << "publish " << payload << "\n";
      std::this_thread::sleep_for(std::chrono::seconds(2));
    }
    cli.disconnect();
  } catch (const mqtt::exception& e) {
    std::cerr << "mqtt error: " << e.what() << "\n";
    return 1;
  }
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

The subscriber uses the timed consume API and drains messages from its own loop, with no callback thread to manage:

#include <chrono>
#include <iostream>
#include <mqtt/client.h>

int main() {
  mqtt::client cli{"tcp://localhost:1883", "sensor-sub-01"};

  mqtt::connect_options opts;
  opts.set_clean_session(true);

  try {
    cli.connect(opts);
    cli.subscribe("home/+/temp", 1);

    while (cli.is_connected()) {
      mqtt::const_message_ptr msg;
      if (cli.try_consume_message_for(&msg, std::chrono::seconds(1))) {
        std::cout << msg->get_topic() << " -> " << msg->to_string() << "\n";
      }
    }
  } catch (const mqtt::exception& e) {
    std::cerr << "mqtt error: " << e.what() << "\n";
    return 1;
  }
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Compile them separately, linking the C++ library and its C base (3as is the TLS build):

g++ -std=c++17 pub.cpp -o pub -lpaho-mqttpp3 -lpaho-mqtt3as
g++ -std=c++17 sub.cpp -o sub -lpaho-mqttpp3 -lpaho-mqtt3as
Enter fullscreen mode Exit fullscreen mode

On Apple Silicon, if headers are not found, add -I/opt/homebrew/include -L/opt/homebrew/lib. Run sub first, then pub; the subscriber prints a home/1f/temp -> 20.0 line every two seconds.

Two more things are needed for stable field deployment: fix the client ID and set clean_session=false so subscriptions survive a short reconnect; and add retries plus a local buffer for publishes, because Paho's reconnect restores the connection but does not resend the message you dropped.

⚖️ 9. Choosing a Broker and Knowing the Limits

Broker choice is mostly a function of connection scale:

Broker Traits Fits
Mosquitto Single binary, few options, C Single host, edge gateway, debugging
EMQX Erlang cluster, rule engine, dashboard 100k connections, multi-tenant
NanoMQ Lightweight C, strong at edge bridging Constrained devices, edge aggregation
HiveMQ Commercial, mature ecosystem and support Enterprises needing an SLA

Conversely, three situations should not use it. If you need the HTTP ecosystem of caches, gateways, and REST tooling, MQTT only adds an adapter layer. If you need to transfer files, MQTT packets can reach 256MB but there is no chunking or resume — put the file in object storage and send the address instead. If you need replay, batch consumption, and exactly-once across systems, that is a log-based broker such as Kafka.

In one line: MQTT moves a flood of small messages from devices to a backend; storage, computation, and orchestration are out of scope.

The test for whether MQTT is worth it is simple: do you have a pile of devices that are always online, upload frequently, and send short messages? If yes, it is the cheapest path. If not, HTTP or Kafka is usually less work.

📎 10. References

Top comments (0)