MQTT Basics Cheat Sheet

MQTT protocol for IoT: publish/subscribe model, Quality of Service levels, broker setup, retained messages, Last Will and Testament, and common IoT patterns.

Last Updated: May 1, 2025

MQTT Concepts

ItemDescription
BrokerCentral server that routes messages between publishers and subscribers
TopicHierarchical string (e.g., sensors/temperature/bedroom) — subscribers filter by topic
PublishSend a message to a topic on the broker
SubscribeExpress interest in a topic (with optional wildcards)
Client IDUnique identifier for each MQTT client connection
Keep AliveMax idle time (seconds) — client sends PINGREQ to stay connected

Quality of Service (QoS)

ItemDescription
QoS 0: At most onceFire-and-forget — no acknowledgment, no retry. Fast, unreliable.
QoS 1: At least onceMessage acknowledged (PUBACK). Retransmit until ACK received.
QoS 2: Exactly onceFour-way handshake — guaranteed exactly-once delivery. Slow but reliable.
QoS is per-messagePublisher and subscriber can have different QoS levels
Downgrade ruleSubscriber gets min(published QoS, subscribed QoS)

Advanced MQTT Features

ItemDescription
Retained MessagesBroker stores last message on a topic — new subscribers get it immediately
Last Will and TestamentPre-set message sent by broker if client disconnects unexpectedly
Persistent SessionBroker remembers subscriptions and queues messages for offline clients
Clean Session = falseEnable persistent session (messages queued between connections)
Wildcard: +Single-level wildcard: sensors/+/temperature matches any sensor name
Wildcard: #Multi-level wildcard: sensors/# matches everything under sensors/

Mosquitto Broker Quick Start

mosquitto -p 1883
Start broker on default MQTT port
mosquitto_sub -t 'sensors/#' -v
Subscribe to all sensor topics (verbose)
mosquitto_pub -t 'sensors/temp' -m '22.5'
Publish a temperature reading
mosquitto_pub -t 'alerts' -m 'OFFLINE' --will-topic 'alerts' --will-payload 'OFFLINE'
Publish with Last Will
mosquitto_pub -t 'config' -m 'v3' -r
Publish retained message (new subs get it)
mosquitto_sub -t '#' --qos 2
Subscribe with QoS 2 (exactly once)
Pro Tip: MQTT is the standard IoT messaging protocol — lightweight, binary, works over TCP or WebSocket. QoS 0 = fire-and-forget, QoS 1 = at-least-once, QoS 2 = exactly-once (slowest).