Skip to main content
Skip to main content

Protocols

MQTT

The standard pub/sub protocol of IoT

Official spec ↗
Audio summary
0:00 / 0:00
TopicsMQTT

If you're wondering what MQTT is exactly and why it dominates industrial IoT, here's the short answer: it's the lightest pub/sub protocol that exists for unreliable networks. If you're starting from scratch, it's worth first understanding what IoT is and how the ecosystem works; if you already have that foundation, read on.

Executive summary

  • MQTT (Message Queuing Telemetry Transport) is a lightweight pub/sub messaging protocol standardized under ISO/IEC 20922 and maintained by OASIS.
  • It runs over TCP/IP with tiny headers (2 fixed bytes), designed for devices with limited CPU, constrained battery, and unreliable networks.
  • Architecture: clients (publishers and subscribers) talk to a central broker that distributes messages across hierarchical topics.
  • It is the dominant protocol in industrial IoT (Industry 4.0), smart home (Home Assistant, Tasmota, Shelly), and large-scale messaging (WhatsApp and Facebook Messenger use it internally).
  • Versions: MQTT 3.1.1 (ubiquitous, 2014) and MQTT 5.0 (2019, adds shared subscriptions, reason codes, message expiry).
  • Ports: 1883 (plain TCP), 8883 (TLS), 80/443 (WebSockets).
  • Don't use it when: you need synchronous request/reply (use HTTP/CoAP), you have large messages (>256 MB), or you can't maintain a broker.

What MQTT is and what it's for

MQTT stands for Message Queuing Telemetry Transport. It's a machine-to-machine (M2M) communication protocol designed in 1999 by Andy Stanford-Clark (IBM) and Arlen Nipper (Cirrus Link) to monitor oil pipelines via satellite — environments with scarce bandwidth and connections that keep dropping. At Plataforma IoT we cover it alongside the rest of the IoT protocols that make up the connectivity ecosystem.

Unlike HTTP (which is point-to-point, request/response, with verbose headers), MQTT uses an asynchronous publish/subscribe model with an intermediary:

text
[Device A] → publishes to topic "factory/line1/temperature" → [Broker] → distributes to [Device B, C, D] subscribed

The broker (Mosquitto, EMQX, HiveMQ, AWS IoT Core, etc.) receives the messages and forwards them to every client subscribed to the corresponding topic. The sender doesn't know — and doesn't need to know — who's listening. That decouples producers from consumers and makes it possible to scale to millions of devices.

How MQTT works

1. Connection

A client opens a TCP connection to the broker (port 1883 by default) and sends a CONNECT packet with:

  • client_id (unique per device)
  • optional username and password
  • keep_alive (in seconds: how often the client sends a PINGREQ to keep the session alive)
  • optional will message: a message the broker will publish if the client disconnects abruptly
  • clean_session: whether subscriptions are preserved between connections

The broker responds with CONNACK (success or an error code).

2. Topics

Topics are hierarchical UTF-8 strings separated by /:

text
factory/lineA/machine01/temperature
factory/lineA/machine01/vibration
home/livingroom/light/state

Subscribers can use wildcards:

  • + (single level): factory/+/machine01/temperature receives the temperature of machine01 on any line.
  • # (multi level): factory/# receives everything under factory.

3. Publish / Subscribe

To publish: a PUBLISH packet with topic, payload (any bytes — text, JSON, binary up to 256 MB), qos, and retain.

To subscribe: a SUBSCRIBE packet with a list of topics and the desired QoS for each one.

4. QoS (Quality of Service)

MQTT defines 3 levels:

LevelGuaranteeCostWhen to use
**QoS 0**"Fire and forget" (at least 0, may be lost)1 packetContinuous telemetry data where losing one is acceptable
**QoS 1**"At least once" (may arrive duplicated)2 packets (PUBLISH + PUBACK)Most use cases
**QoS 2**"Exactly once" (no losses, no duplicates)4 packets (full handshake)Critical commands (door unlock, financial transfer)

Security note: QoS levels are independent of encryption. MQTT without TLS transmits everything in plain text, including credentials. For production deployments, see our IoT security guide, where we detail authentication and encryption best practices for brokers.

Note: QoS 2 adds significant latency. In industrial IoT, QoS 1 plus consumer-side idempotency is almost always better than QoS 2.

5. Retained messages

If you publish with retain=true, the broker stores the last message on the topic. When a new client subscribes, it immediately receives that last value. Useful for current state (e.g., "last known temperature").

6. Last Will & Testament (LWT)

If the client disconnects abruptly (network drop, crash), the broker automatically publishes the "will message" the client declared in CONNECT. A typical pattern: device/123/status with the value online retained, plus an LWT offline retained — this enables real-time presence.

Real-world use cases

SectorConcrete example
**Industry 4.0**Modern SCADA systems (Ignition, Node-RED) use MQTT to connect PLCs to real-time dashboards. Sparkplug B is a specification on top of MQTT for industry.
**Smart Home**Home Assistant + Mosquitto + Zigbee2MQTT + Tasmota: 2M+ homes worldwide. Shelly devices speak MQTT natively.
**Smart Cities**Traffic, air-quality, and parking sensors send telemetry to municipal brokers over MQTT on top of [LoRaWAN](/en/protocols/lorawan) or [NB-IoT](/en/protocols/nb-iot).
**Logistics / Asset tracking**GPS trackers with a 4G modem send positions every N seconds over MQTT — they survive coverage gaps thanks to the `will message`.
**Large-scale messaging**Facebook Messenger uses MQTT over TCP/TLS for its push notification system (40-100B msgs/day). WhatsApp has too, historically.
**Connected vehicles**Tesla, Volkswagen, and BMW use MQTT for fleet telemetry.

Leading MQTT brokers

BrokerTypeWhen to choose it
**Mosquitto**Open source, C, single nodeSmall/medium projects, edge gateway, on-premises
**EMQX**Open source + commercial, Erlang, clusterProduction at scale (10M+ connections), multi-protocol
**HiveMQ**Commercial (free CE), Java, clusterEnterprise IoT with SLAs, Kafka integration
**VerneMQ**Open source, Erlang, clusterFree alternative to EMQX, strong on latency
**AWS IoT Core**Managed cloudIf you're already on AWS and want to forget about operations
**Azure IoT Hub**Managed cloud (MQTT subset)Microsoft stack, Stream Analytics integration
**NanoMQ**Open source, C, edge-firstConstrained industrial IoT gateways

Pros and cons

Pros

  • Lightweight: a fixed 2-byte header, ideal for microcontrollers (ESP32, nRF52).
  • Resilient on poor networks: designed for intermittent connections.
  • Asynchronous: decouples producers and consumers, scales well.
  • Mature standard: ISO/IEC 20922, a huge ecosystem.
  • TLS support: end-to-end encryption at the transport layer.

Cons

  • Requires a broker: it isn't peer-to-peer; the broker is a single point of failure unless you cluster it.
  • Not secure by default: without TLS, everything travels in the clear. Without auth, anyone can publish. You have to configure it.
  • Hard to debug: binary payloads, multiple publishers — you need tools (MQTT Explorer, mosquitto_sub).
  • QoS 2 is expensive: the 4-way handshake adds latency.
  • No automatic discovery: there's no standard way to list active topics (in MQTT 5 you can do it with $SYS/, but it depends on the broker).

MQTT vs HTTP vs CoAP

AspectMQTTHTTPCoAP
ModelAsynchronous pub/subRequest/responseRequest/response
TransportTCP (+ WebSockets)TCPUDP
OverheadMinimal (2B header)High (text headers)Low (4B header)
MulticastNoNoYes
DevicesMCU+ (32 KB RAM)Constrained is hardVery constrained (8 KB)
Use casesContinuous telemetryREST APIsExtreme low-power sensors

Summary: MQTT wins when you have many devices sending continuous data. HTTP wins for request/response APIs and catalogs. CoAP wins on extremely constrained devices that can't sustain TCP. If you're still evaluating which protocol fits your project, the IoT platforms section can help you understand the full stack.

Getting started: minimal setup

1. Spin up a local broker (Mosquitto)

bash
# macOS
brew install mosquitto
brew services start mosquitto

# Docker (cross-platform)
docker run -d --name mosquitto -p 1883:1883 eclipse-mosquitto

2. Subscribe to a topic

bash
mosquitto_sub -h localhost -t "test/topic" -v

3. Publish from another terminal

bash
mosquitto_pub -h localhost -t "test/topic" -m "Hello IoT"

You'll see the message appear in the subscriber. You now have pub/sub working.

MQTT is also the protocol of choice for edge computing in IoT patterns: the broker can run on a local gateway and process data before pushing it to the cloud, reducing latency and transmission cost.

4. Connect an MCU (ESP32 + Arduino)

cpp
#include <WiFi.h>
#include <PubSubClient.h>

WiFiClient espClient;
PubSubClient client(espClient);

void setup() {
  WiFi.begin("ssid", "pass");
  client.setServer("192.168.1.10", 1883);
  client.connect("esp32-01");
  client.publish("home/livingroom/temperature", "22.5");
  client.subscribe("home/livingroom/light/cmd");
}

void callback(char* topic, byte* payload, unsigned int length) {
  // process incoming command
}

Primary sources

Frequently asked questions

Which ports does MQTT use?+

By default, 1883 (plain TCP, never use in production) and 8883 (TLS). Over WebSockets: 80 (ws) and 443 (wss). Brokers allow custom ports to be configured.

Is WhatsApp MQTT?+

Historically yes — WhatsApp used MQTT over TCP/TLS for its messaging system. Facebook Messenger did too. Today they likely use a proprietary variant derived from MQTT rather than the pure standard.

What are the downsides of MQTT?+

It requires a broker (a single point of failure without clustering), security isn't the default (you have to configure TLS + auth), QoS 2 is expensive, and binary payloads are hard to debug without tooling.

What is an MQTT broker?+

The central server that receives messages from publishers and forwards them to subscribers based on topics. Examples: Mosquitto, EMQX, HiveMQ, AWS IoT Core.

MQTT vs HTTP — which is better for IoT?+

MQTT for continuous telemetry from many devices. HTTP for REST APIs and catalogs. They can coexist in the same project: devices speak MQTT, dashboards consume HTTP.

MQTT 5 vs MQTT 3.1.1 — is it worth it?+

Yes, if your broker and client libraries support it. MQTT 5 adds: shared subscriptions (load balancing), reason codes (better debugging), message expiry, user properties, and a request/response pattern. Most modern brokers support it.

Compatible devices

  • ESP32, ESP8266, RPi, AVR with sockets, gateways

Related hardware

Companies

Related articles