MQTT QoS Quality of Service Explained Simply
QoS (Quality of Service) defines how messages are delivered between devices, ensuring reliability. It has three levels: 0 (at most once), 1 (at least once), and 2 (exactly once), each balancing speed and delivery guarantee.How It Works
MQTT QoS controls how messages travel from one device to another, like sending a letter with different delivery options. QoS 0 is like dropping a postcard in the mailbox without tracking—it might get lost but is fast. QoS 1 is like sending a letter with a receipt confirmation, so the sender knows it arrived but might get duplicates. QoS 2 is like a registered mail that requires a signature, ensuring the message arrives exactly once without duplicates.
This system helps devices decide how much effort to spend making sure messages get through, balancing speed and reliability depending on the need.
Example
This example shows how to publish a message with different QoS levels using Python and the paho-mqtt library.
import paho.mqtt.client as mqtt client = mqtt.Client() client.connect("test.mosquitto.org", 1883, 60) # Publish with QoS 0 (at most once) client.publish("home/temperature", "22°C", qos=0) # Publish with QoS 1 (at least once) client.publish("home/temperature", "22°C", qos=1) # Publish with QoS 2 (exactly once) client.publish("home/temperature", "22°C", qos=2) client.disconnect()
When to Use
Use QoS 0 when speed is more important than reliability, such as sending frequent sensor data where losing some messages is okay. Use QoS 1 when you need to ensure messages arrive but can handle duplicates, like alerts or commands. Use QoS 2 when message duplication or loss is unacceptable, such as financial transactions or critical control signals.
Choosing the right QoS helps balance network load and device resources with message reliability.
Key Points
- QoS 0: Fast, no guarantee, no retries.
- QoS 1: Guaranteed delivery, possible duplicates.
- QoS 2: Guaranteed single delivery, slowest.
- QoS affects network traffic and device battery life.
- Pick QoS based on message importance and resource limits.