MQTT: Publish/Subscribe for IoT and mobile push
Updated November 1, 2026
MQTT is a lightweight pub/sub protocol over TCP. Topics with wildcards, QoS 0/1/2, retained messages, last will. Minimal overhead (2-byte minimum header). A broker is required (mosquitto/EMQX/HiveMQ). Use cases: IoT, telemetry, mobile push.
Why MQTT
IoT devices (sensors, ESP32, industrial PLC) are constrained:
- Limited RAM/Flash: no room for an HTTP stack with a JSON parser
- Battery-powered: every wakeup costs energy
- Flaky networks (cellular, mesh): delivery guarantees are required
- One device, many subscribers (telemetry to dashboard, DB, alerting)
HTTP does not fit: a server cannot push to a device without long-polling (which requires an open connection and keepalive). REST request/response does not map to "an event on every sensor."
MQTT (MQ Telemetry Transport) is a lightweight publish/subscribe protocol over TCP (or TLS). Born in 1999, it became an OASIS standard in 2014. Versions: MQTT 3.1.1 (2014 standard), MQTT 5 (2019, significantly extended).
Use cases:
- IoT telemetry: device to broker to consumers (DB, alerts, dashboard)
- Mobile push notifications: AWS IoT, Facebook Messenger
- Industrial IoT: SCADA, smart factory
- Smart home: Home Assistant, Zigbee2MQTT
- Connected car: telemetry to the cloud
Pub/sub model
Three participants:
- Publisher - sends messages to a topic
- Subscriber - subscribes to a topic (or pattern) and receives messages
- Broker - the central node that routes publish to subscribers
┌─────────┐ PUBLISH ┌────────┐ SUBSCRIBE ┌──────────┐
│ device1 │ ──"temp"──► │ │ ◄─────────── │ dashboard │
└─────────┘ │ │ └──────────┘
│ broker │
┌─────────┐ │ │ ┌──────────┐
│ device2 │ ──"temp"──► │ │ ──"temp"──► │ database │
└─────────┘ └────────┘ └──────────┘Publishers and subscribers know nothing about each other, only about the broker.
Topics: hierarchical with wildcards
A topic is a string with / separators:
home/livingroom/temperature
home/livingroom/humidity
home/kitchen/temperature
factory/line1/machine42/errorWildcards in subscriptions:
+- one level (home/+/temperaturematches livingroom and kitchen)#- everything below (home/#matches all topics under home/, at any depth)
Subscribe: home/+/temperature → receives home/livingroom/temperature,
home/kitchen/temperature
Subscribe: home/# → receives everything under home/...# is only valid at the end; + can appear at any position. The publisher defines the topic freely (no schema or discovery in core MQTT).
QoS: three delivery levels
QoS 0 - "fire and forget"
publisher ──PUBLISH──► broker ──PUBLISH──► subscriberOne packet, no acknowledgment. If lost, it is gone. Fastest, and the default.
Suitable for sensors where a stale reading does not matter (a new one arrives within a second).
QoS 1 - "at least once"
publisher ──PUBLISH (id=42)──► broker
publisher ◄──────PUBACK 42────── brokerThe publisher holds messages until PUBACK arrives. On timeout it retries with the DUP flag set.
The receiver may get a duplicate (if PUBACK was lost and the publisher retried). The application must be idempotent.
QoS 2 - "exactly once"
Four-way handshake:
publisher ──PUBLISH (id=42)──►
◄──PUBREC 42─────
──PUBREL 42────►
◄──PUBCOMP 42─── brokerDuplicates are eliminated at the protocol level. This is the most expensive level; it is really needed for financial transactions and state changes. For most IoT workloads, QoS 1 is sufficient.
The subscriber requests its own QoS at subscribe time; effective QoS = min(publisher_qos, subscriber_qos).
Retained messages: last known state
Normally a subscriber receives only messages published after it subscribed. If it subscribes an hour later, it has no knowledge of the current temperature.
Retained flag: the publisher sends with retain=true, and the broker stores it as the "last value" for that topic. A new subscriber immediately receives the retained message:
$ mosquitto_pub -t home/temperature -r -m "21.5"
# stored
$ mosquitto_sub -t home/temperature
21.5 ← delivered immediately on subscribeThis is used for shadow state: the current state of a device. To clear it, publish an empty payload with retain=true.
Last will and testament (LWT)
At CONNECT time a client can specify an LWT message: a topic and payload that the broker will automatically publish when the client abnormally disconnects (TCP timeout, not a graceful DISCONNECT).
Usage:
- Device publishes to
devices/dev42/statuswith payload "online" and retain - LWT: same topic, payload "offline" with retain
- If the device drops off, all subscribers learn it is offline
Wire format: binary and minimal
Minimal CONNECT for MQTT 3.1.1:
10 14 Fixed header: type=CONNECT, length=20
00 04 4D 51 54 54 protocol name: "MQTT"
04 protocol version: 4 (=3.1.1)
02 flags: clean session
00 3C keepalive: 60s
00 08 64 65 76 69 63 65 31 32 client id: "device12"PUBLISH is even shorter: 2-byte header plus topic plus payload. That is enough for a constrained device.
Connection: keepalive and persistent session
Keepalive
At CONNECT you set keepalive in seconds. If the client sends nothing for that many seconds, it must send PINGREQ; the broker replies with PINGRESP. If the broker receives nothing within 1.5 x keepalive, it closes the connection.
For battery-powered devices: a small keepalive (15-30 s) gives fast detection. A large one (300+ s) reduces radio wakeups but slows detection.
Persistent session
CONNECT with clean session = false and a client_id causes the broker to remember:
- The client's subscriptions
- QoS 1/2 messages not delivered while the client was offline
When the client reconnects with the same client_id, it receives pending messages. This is offline delivery.
Clean session=true (default in mqtt.js) means everything is forgotten at disconnect.
MQTT 5: what was added
- Reason codes - instead of a bare "disconnect," the broker says why (
Server busy,Unauthorized,Topic name invalid) - User properties - custom key-value pairs in headers (like HTTP)
- Shared subscriptions -
$share/group/topicfor load-balancing across N instances - Topic alias - compression of repeated topic names
- Session expiry interval - explicit, replacing binary clean/persistent
- Enhanced authentication - challenge-response via SASL
- Server redirect - broker redirects clients to another broker
Brokers are migrating gradually. Mosquitto supports MQTT 5 since version 2.0. EMQX supports it natively.
Brokers: comparison
| Broker | License | Notes |
|---|---|---|
| Mosquitto | EPL | Most popular, lightweight, single-node |
| EMQX | Apache 2.0 | Clustered, millions of connections, native MQTT 5 |
| HiveMQ | Commercial (CE free) | Enterprise, clustered |
| VerneMQ | Apache 2.0 | Erlang-based, clustered |
| AWS IoT Core | managed | AWS-integrated, per-message billing |
| Azure IoT Hub | managed | Azure-integrated |
Mosquitto is the quick start for testing, home use, and small deployments. EMQX and HiveMQ target production at millions of devices.
TLS and authentication
Plain MQTT runs on TCP/1883. With TLS it is MQTT over TLS on port 8883.
Mutual TLS (mTLS) is the standard in IoT: each device has its own client certificate, the broker verifies it and derives a unique client_id. AWS IoT Core is built exactly on this model.
Alternatives:
- Username/password in CONNECT (must be over TLS)
- JWT/token in the username field (broker validates it)
- MQTT 5 enhanced auth - challenge-response via SASL
MQTT vs alternatives
| Property | MQTT | CoAP | AMQP 0.9.1 (RabbitMQ) | WebSocket |
|---|---|---|---|---|
| Transport | TCP/TLS | UDP/DTLS | TCP/TLS | TCP/TLS |
| Min header | 2 bytes | 4 bytes | 8+ bytes | 2-14 bytes |
| Pub/sub | yes (via broker) | observe-pattern | yes (queues+exchanges) | no (raw) |
| Reliable delivery | QoS 0/1/2 | confirmable yes/no | persistent queue | no |
| Battery-friendly | moderate | yes (UDP, minimal) | no | no |
| Schema/typing | no | no | no | no |
| Use case | IoT mobile telemetry | constrained device | enterprise message bus | bidir browser |
MQTT over WebSocket
Browsers cannot open a raw TCP/8883 socket (sandbox restrictions). The solution is MQTT over WebSocket: the broker listens on a WS port (8083, or 8084 with TLS) and carries MQTT inside WebSocket frames.
This is used by browser-based dashboards (HiveMQ Insights, MQTT.js client).
When things go wrong
- Connection refused (TCP): the broker is not listening. Check with
nc -zv host 1883. bad_username_or_password: usually the AUTH provider in the broker is not configured, or the client TLS certificate is invalid.- No messages after reconnect:
clean session=trueforgets subscriptions. Usefalsewith a persistent client_id. - Duplicates at QoS 1: this is normal behavior; the application must be idempotent. Switch to QoS 2 only if you truly need exactly-once.
- Retained message is stuck: publish an empty payload with retain=true to clear it.
- High message rate hitting broker ceiling: mosquitto is single-threaded and writes everything to one log. For heavy load, use an EMQX or HiveMQ cluster.
- Wildcards like
home/+/+/temperatureload the broker: topic matching is expensive, especially with millions of clients. Keep topics flat.
Further reading
- https://mqtt.org/ - specifications
- https://www.hivemq.com/blog/mqtt-essentials-part-1-introducing-mqtt/ - HiveMQ "MQTT Essentials" series (best introduction)
- https://mosquitto.org/man/ - mosquitto client tools
Commands
mosquitto_sub -h localhost -t 'home/#' -v: Subscribe to all topics under home/, print topic and payloadmosquitto_pub -h localhost -t home/temperature -m 21.5 -q 1 -r: Publish with QoS 1 and retain (broker stores it as last-known value)mosquitto_pub -h broker -p 8883 --cafile ca.pem --cert client.crt --key client.key -t devices/d1/temp -m 21.5: MQTT over TLS with mutual auth (mTLS)mosquitto_sub -t '$SYS/#' -h localhost: Read mosquitto internal stats: connections, message rate, uptime ($SYS tree)mosquitto -c /etc/mosquitto/mosquitto.conf -v: Start the broker in the foreground with verbose loggingmosquitto_pub -t devices/d1/status --will-topic devices/d1/status --will-payload offline --will-retain: Publish and set LWT: on abnormal disconnect the broker posts 'offline'tshark -Y mqtt -i eth0: Wireshark dissector for MQTT: inspect frames and QoS fieldsemqx ctl listeners: In EMQX, list active listeners (TCP, TLS, WS, WSS)