Imagine a battery-powered temperature sensor sitting in a remote greenhouse, waking up every five minutes to send a 20-byte payload ({"temp": 26.4}). If that device uses standard HTTP POST over TLS, it must perform a full TCP handshake, negotiate a TLS session, transmit hundreds of bytes of verbose text headers (Host, User-Agent, Content-Type, Authorization), and wait for a synchronous server response before going back to sleep. Over thousands of wake cycles, the radio spends more time and energy transmitting protocol overhead than actual sensor data.
Web protocols like HTTP were engineered for human-driven browsers requesting multi-megabyte documents over reliable broadband connections. Constrained IoT devices operate under the opposite reality: tiny payloads, strict battery budgets, asymmetric bandwidth, and intermittent cellular or Wi-Fi links.
Choosing the right messaging protocol determines whether your fleet scales smoothly to thousands of nodes or collapses under bandwidth bills, battery drain, and dropped commands.
Protocol Comparison Matrix: HTTP, MQTT, CoAP, and WebSockets #
Before diving into packet internals, the table below compares the four primary application-layer protocols used in modern IoT architectures (typical header overhead and power efficiency vary depending on TLS/DTLS framing and payload encoding):
| Dimension | HTTP / REST | MQTT | CoAP | WebSockets |
|---|---|---|---|---|
| Underlying Transport | TCP | TCP | UDP | TCP (upgraded from HTTP) |
| Communication Pattern | Synchronous Request / Response | Asynchronous Publish / Subscribe | Request / Response (+ Observe) | Full-Duplex Bi-directional |
| Minimum Header Overhead | ~100–800+ bytes (ASCII text) | 2 bytes (binary fixed header) | 4 bytes (binary header) | 2–14 bytes (binary framing) |
| Power & Bandwidth Cost | High | Low | Very Low (ideal for NB-IoT/LoRa) | Moderate to High |
| Built-in Delivery Guarantees | Relies on TCP + status codes | 3 QoS levels (0, 1, 2) | Confirmable (CON) / Non-CON | Relies on TCP framing only |
| NAT & Firewall Traversal | Easy (Ports 80 / 443) | Easy (Outbound TCP 1883 / 8883) | Harder (UDP NAT state timeouts) | Easy (Standard HTTP Upgrade) |
| Best-Fit Role | Cloud webhooks, REST APIs, OTA binary downloads | Device telemetry, remote commands, fleet state | Ultra-constrained cellular or mesh nodes | Real-time browser dashboards |
Deep Dive: How MQTT Works Under the Hood #
MQTT (Message Queuing Telemetry Transport) has become the de facto standard for IoT telemetry because it solves two fundamental problems simultaneously: protocol overhead and tight coupling.
1. Decoupling Space and Time via a Broker #
In traditional HTTP architectures, a sensor must know the exact IP address or domain name of the server, and the server must be online and ready to accept the connection at the exact millisecond the sensor wakes up.
MQTT replaces direct client-to-server connections with a Publish/Subscribe (Pub/Sub) architecture centered around an MQTT Broker (such as EMQX, Mosquitto, or HiveMQ):
- Publishers (sensor nodes) send messages tagged with a topic string to the broker without knowing or caring who consumes them.
- Subscribers (backend ingestion workers, alerting rules, or dashboards) register interest in specific topic patterns with the broker.
- Space & Time Decoupling: You can restart your backend ingestion service, add a new analytics worker, or scale databases without changing a single line of firmware or reconfiguring any edge device.
2. Anatomy of a 2-Byte MQTT Packet #
Unlike HTTP’s human-readable text headers, MQTT uses compact binary framing:
- Byte 1 (Fixed Header — Control Packet Type & Flags): Encodes the packet type in the upper 4 bits (such as
CONNECT,PUBLISH,PUBACK,PINGREQ, orDISCONNECT) and control flags in the lower 4 bits (DUP,QoS,RETAIN). - Byte 2+ (Remaining Length): Uses a variable-length encoding scheme where 1 byte represents payloads up to 127 bytes, and up to 4 bytes can represent payloads up to 256 MB.
For a small sensor reading over an established TCP connection, the protocol framing adds just a few bytes on top of the topic name and payload.
Designing Clean MQTT Topic Hierarchies #
MQTT routes messages using UTF-8 hierarchical topic strings separated by forward slashes (/). Unlike HTTP routes, MQTT topics are created dynamically when published—there is no need to pre-register topics on the broker.
A scalable production hierarchy moves from broadest scope to most specific attribute:
<organization>/<site>/<device_type>/<device_id>/<category>/<metric>
# 1. Telemetry (Device -> Cloud) - High frequency, QoS 0 or 1
rikode/bandung-lab/esp32-env/node-01/telemetry/temperature
rikode/bandung-lab/esp32-env/node-01/telemetry/humidity
# 2. Device Presence & LWT (Device -> Cloud) - Retained = true, QoS 1
rikode/bandung-lab/esp32-env/node-01/status/online
# 3. Boot Metadata (Device -> Cloud) - Sent once on startup, Retained = true
rikode/bandung-lab/esp32-env/node-01/info/firmware
# 4. Remote Actuation Commands (Cloud -> Device) - QoS 1, Retained = false
rikode/bandung-lab/esp32-env/node-01/cmd/relay
# 5. Command Acknowledgment (Device -> Cloud) - Confirms physical execution
rikode/bandung-lab/esp32-env/node-01/ack/relayWildcard Subscriptions (+ vs. #)
#
Subscribers use two wildcard characters to listen across multiple devices without subscribing to thousands of individual topics:
- Single-Level Wildcard (
+): Matches exactly one hierarchy level. For example,rikode/bandung-lab/+/+/status/onlinereceives online/offline status updates from every device type and node ID insidebandung-lab. - Multi-Level Wildcard (
#): Matches all remaining levels and must always appear as the final character. For example,rikode/bandung-lab/+/+/telemetry/#captures every sensor metric across the entire facility.
Design rule: Never begin a topic with a leading slash (e.g.,
/rikode/...). A leading slash creates an empty root level before the first delimiter, complicating broker Access Control Lists (ACLs) and wildcard matching.
Quality of Service (QoS 0, 1, and 2) Under the Hood #
Wireless networks drop packets. Rather than forcing firmware engineers to write custom retry and deduplication timers from scratch, MQTT builds three selectable Quality of Service (QoS) delivery guarantees directly into the protocol:
QoS 0 — At Most Once (Fire and Forget) #
- Packet Flow:
Publisher→PUBLISH→Broker - Under the Hood: The sender transmits the
PUBLISHpacket once and immediately discards it from memory. No acknowledgment is returned at the MQTT layer (delivery relies solely on underlying TCP). - Best For: High-frequency telemetry (such as vibration or room temperature sampled every few seconds) where losing an occasional reading is harmless because fresh data arrives moments later.
QoS 1 — At Least Once (Acknowledged Delivery) #
- Packet Flow:
Publisher→PUBLISH (Packet ID)→Broker→PUBACK (Packet ID) - Under the Hood: The sender stores the message in RAM/flash until the broker replies with a matching
PUBACKpacket. If the timer expires without aPUBACK, the sender retransmits thePUBLISHpacket with theDUP(Duplicate) flag set to1. Because aPUBACKitself can be lost on a noisy cellular link, QoS 1 guarantees delivery at least once, but duplicates can occur. - Best For: The production standard for critical telemetry, alert events, and actuator commands. Backend ingestion pipelines should treat incoming QoS 1 messages as idempotent using device timestamps or sequence counters.
QoS 2 — Exactly Once (Four-Way Handshake) #
- Packet Flow:
PUBLISH→PUBREC→PUBREL→PUBCOMP - Under the Hood: Both sides store the Packet ID state across a four-step handshake to guarantee the payload is processed exactly once without duplication.
- Best For: Financial transactions, prepaid smart utility billing, or industrial valve commands where duplicate execution causes physical or accounting errors—generally avoided for routine sensor streams due to fourfold packet latency and higher RAM state overhead.
Stateful MQTT Features: Retained Messages and Last Will (LWT) #
By default, MQTT messages are ephemeral: if a dashboard opens five seconds after a sensor publishes its state, the dashboard misses the message until the next transmission cycle. Two built-in features solve state visibility:
1. Retained Messages #
When a publisher sets the RETAIN = true flag on a PUBLISH packet, the broker stores the single most recent message for that topic. Any new subscriber that subsequently subscribes to that topic immediately receives the stored value upon connection.
- Where to Use: Device status (
status/online), current relay state (state/relay), and firmware version (info/firmware). - Where NOT to Use: Remote commands (
cmd/relay). If a"toggle_door"or"dispense"command is published withRETAIN = true, the device will re-execute that command every single time it reboots and reconnects to the broker.
2. Last Will and Testament (LWT) #
Because TCP sockets can break silently when a device loses battery power or drives into a tunnel without sending a clean DISCONNECT packet, brokers need a mechanism to notify the fleet of unexpected dropouts.
During the initial CONNECT handshake, the device registers a Last Will and Testament (LWT) contract with the broker:
- Registration (
CONNECT):node-01connects with aKeep-Aliveinterval of 30 seconds, registeringWill Topic = rikode/bandung-lab/esp32-env/node-01/status/online,Will Payload = {"status":"offline"},Will QoS = 1, andWill Retain = true. - Presence Announcement (
PUBLISH): Immediately after connecting,node-01publishes{"status":"online"}withRetain = trueto that exact same topic, overwriting any previous offline state. - Normal Heartbeat: Whenever no telemetry is flowing, the microcontroller sends a tiny 2-byte
PINGREQpacket within the 30-second window, and the broker replies withPINGRESP. - Ungraceful Disconnect: If
node-01loses power abruptly, the broker waits 1.5 times the Keep-Alive period (45 seconds). Once the timeout expires without aPINGREQ, the broker automatically publishes the stored LWT"offline"payload withRetain = trueso dashboards and alerting services immediately detect the outage.
const char* statusTopic = "rikode/bandung-lab/esp32-env/node-01/status/online";
const char* lwtPayload = "{\"status\":\"offline\"}";
const char* onlinePayload = "{\"status\":\"online\"}";
void connectToBroker() {
// Register LWT during CONNECT (QoS 1, Retain = true)
bool connected = mqttClient.connect(
"esp32-node-01", // Unique Client ID across the entire broker
"mqtt_user",
"mqtt_pass",
statusTopic, // Will Topic
1, // Will QoS
true, // Will Retain
lwtPayload // Will Payload
);
if (connected) {
// Overwrite retained status to online and subscribe only to node-specific commands
mqttClient.publish(statusTopic, onlinePayload, true);
mqttClient.subscribe("rikode/bandung-lab/esp32-env/node-01/cmd/+", 1);
}
}When NOT to Use MQTT: HTTP, CoAP, and WebSockets #
While MQTT excels at persistent telemetry and fleet control, forcing every workload through MQTT creates unnecessary complexity:
- Use HTTP/REST for Bulk Transfers & External Webhooks: Downloading a 1.5 MB Over-The-Air (OTA) firmware binary or integrating with third-party SaaS webhooks works far better over standard HTTP/HTTPS with range requests and CDN caching.
- Use CoAP (Constrained Application Protocol) Over Lossy UDP Links: On ultra-constrained NB-IoT or mesh networks where TCP connection setup and keep-alive packets waste scarce radio airtime, CoAP mirrors HTTP’s REST semantics (
GET,POST,PUT,DELETE) in a compact 4-byte binary header over connectionless UDP, secured with DTLS. - Use MQTT over WebSockets for Browser Dashboards: Web browsers cannot open raw TCP sockets to port 1883/8883 for security reasons. Wrapping MQTT frames inside standard WebSockets (port 443) allows React or Next.js web dashboards to subscribe directly to live broker topics alongside backend workers.
4 Common MQTT Mistakes in Production #
- Reusing the Same
client_idAcross Multiple Devices: The MQTT specification enforces unique Client IDs per broker. If two ESP32 nodes connect using"esp32-client", the broker immediately disconnects the older session whenever the second node connects—triggering an endless reconnect loop that drains batteries and floods broker logs. Always deriveclient_idfrom hardware MAC addresses or provisioned serial numbers. - Subscribing to
#on Memory-Constrained Microcontrollers: Subscribing an edge node to a broad wildcard likerikode/#forces the broker to stream every message from the entire fleet down to that microcontroller, rapidly overflowing UART/Wi-Fi receive buffers and crashing the heap. Edge devices should subscribe narrowly to their own command topics. - Defaulting to QoS 2 for Routine Sensor Telemetry: Using QoS 2 for periodic environmental readings quadruples packet exchanges and requires tracking in-flight packet states across reconnects. Reserve QoS 2 strictly for non-idempotent financial or billing operations, and use QoS 0 or QoS 1 with idempotent backend processing for telemetry.
- Publishing Large Unchunked JSON Blobs: Packing 15 KB of verbose diagnostic JSON into a single MQTT payload fragments TCP packets and forces small microcontrollers to allocate massive contiguous buffers. Keep telemetry payloads concise (under 256–1024 bytes) and split distinct concerns across dedicated sub-topics.
Moving Forward in the Series #
Understanding MQTT framing, topic design, QoS guarantees, and Last Will contracts gives your devices an efficient, decoupled language for communicating with cloud infrastructure. However, even the cleanest protocol design fails if the firmware running on the microcontroller freezes whenever Wi-Fi drops, loses sensor data during a router reboot, or ships with hardcoded credentials.
In Part 4: Designing Resilient Edge Firmware: Wi-Fi Provisioning, Offline Buffering, and Auto-Recovery, we shift focus to firmware engineering on the edge—covering captive portal onboarding, flash ring buffers, and non-blocking reconnection state machines.