MQTT QoS Levels Compared: QoS 0 vs 1 vs 2, Persistent Sessions, Retained Messages and MQTT 5
Most IoT teams pick QoS 2 for anything important and believe the message is now delivered “exactly once” from sensor to database. It is not. MQTT QoS levels are a per-hop contract between one sender and one receiver, and they only survive a disconnect if a persistent session holds the state. Get the session wrong and QoS 2 delivers nothing after a reconnect; get the broker queue wrong and QoS 1 silently drops the oldest message.
This matters more in 2026 because fleets are now on cellular and satellite links where every extra round trip costs battery, airtime and money. MQTT 5 gave us the tools to fix most of these problems: Session Expiry Interval, Message Expiry Interval, Receive Maximum, retain handling and reason codes on every acknowledgement. Few deployments use them deliberately.
You will leave with the exact packet flows, a comparison table, worked latency and byte maths, runnable paho-mqtt code and a decision matrix.
What this covers: QoS 0, 1 and 2 handshakes, effective QoS downgrade, persistent sessions, retained messages, MQTT 5 expiry and flow control, broker limits, failure modes and a practical selection guide.
Context and Background
MQTT is a publish/subscribe protocol that runs over TCP (or WebSockets and QUIC in some brokers). It was designed for constrained devices and unreliable networks. Two versions matter in production today: MQTT 3.1.1, published by OASIS in October 2014 and later adopted as ISO/IEC 20922:2016, and MQTT 5.0, which became an OASIS Standard on 7 March 2019. Both are free to read: the OASIS MQTT Version 5.0 specification and the OASIS MQTT 3.1.1 specification.
Both versions define the same three MQTT QoS levels. QoS 0 is “at most once”, QoS 1 is “at least once” and QoS 2 is “exactly once”. Those three labels are where most confusion starts. They describe what happens on a single network hop: publisher to broker, or broker to one subscriber. They say nothing about what happens inside the broker, inside your application, or across a bridge to another broker.
The surrounding features decide whether the guarantee actually holds. A persistent session keeps in-flight messages and subscriptions across a disconnect. Retained messages give a new subscriber the last known value on a topic. MQTT 5 adds expiry for messages and sessions, a negotiated in-flight window, and reason codes so a publisher learns when the broker rejected a message. Without these, QoS is a promise with no memory.
The common brokers implement MQTT QoS levels faithfully but differ in defaults. Eclipse Mosquitto, EMQX and HiveMQ all bound per-client in-flight windows and offline queues, and all of them drop messages once those bounds are reached. Those defaults are where most “MQTT lost my data” incidents originate, not in the protocol itself.
If you are still choosing between protocols, start with our overview of how to choose an IoT protocol. If your devices sit behind intermittent links, the companion piece on MQTT store-and-forward at the edge gateway covers disk buffering and bridging. This post stays on the protocol mechanics: what each QoS level costs, what it guarantees, and what state makes the guarantee real.
How MQTT QoS Levels Work: The Per-Hop Delivery Model
MQTT QoS levels define the acknowledgement handshake on one hop. QoS 0 sends a single PUBLISH with no acknowledgement. QoS 1 adds a PUBACK and may deliver duplicates. QoS 2 uses PUBLISH, PUBREC, PUBREL and PUBCOMP so the receiver delivers once per hop. The delivered QoS is the lower of the publish QoS and the subscription QoS.

Figure 1: The three MQTT QoS handshakes on a single hop between a publisher and a broker. The same flows apply, reversed, from broker to subscriber.
The diagram shows one control packet for QoS 0, two for QoS 1 and four for QoS 2. Packet identifiers appear only at QoS 1 and 2. The broker repeats an equivalent exchange independently with every subscriber, which is why QoS is a hop-level property.
QoS 0: one packet, no state
At QoS 0 the sender writes a PUBLISH packet to the TCP socket and forgets it. There is no packet identifier, and the specification requires the DUP flag to be 0. The receiver never replies. If the TCP connection breaks while the packet sits in a kernel buffer, the message is gone and nobody knows.
That sounds worse than it is. TCP already retransmits lost segments while the connection is alive, so QoS 0 loss happens mainly at disconnects, broker restarts and queue overflows. For high-rate telemetry where the next sample supersedes the last one, a few lost samples per reconnect are usually acceptable. The upside is zero per-message state on both sides and the smallest possible airtime.
One subtle point: brokers may queue QoS 0 messages for an offline persistent session, but the specification makes it optional. Mosquitto’s queue_qos0_messages defaults to false, while EMQX’s mqueue_store_qos0 defaults to true. The same QoS 0 subscription can therefore behave differently across brokers after a reconnect.
QoS 1: acknowledgement, retry on reconnect, duplicates by design
At QoS 1 the sender assigns a non-zero 16-bit packet identifier, sends PUBLISH and keeps the message until a PUBACK with that identifier arrives. The receiver must reply with PUBACK and may deliver the message onward immediately. If the sender never sees the PUBACK, it resends the PUBLISH with the DUP flag set to 1 and the same packet identifier.
The key detail is when it resends. MQTT 5 section 4.4 says that when a client reconnects with Clean Start 0 and a session is present, both sides must resend unacknowledged PUBLISH packets (and PUBREL packets) using their original identifiers, and that clients and servers must not resend messages at any other time. MQTT 3.1.1 described reconnect as the only circumstance where redelivery is required. There is no in-session retry timer in the MQTT 5 model; TCP is trusted while the connection lives.
Duplicates arise because the PUBACK can be lost after the receiver has already delivered the message. On reconnect the sender resends, and the receiver delivers it again. The DUP flag does not help much with deduplication. It only tells the receiver this might be a resend; packet identifiers are reused once acknowledged, so a DUP=1 packet is not proof of a duplicate, and DUP=0 is not proof of novelty. The broker also does not propagate the incoming DUP flag to subscribers.
QoS 2: a two-phase handshake for once-per-hop delivery
QoS 2 splits delivery into two acknowledged phases. The sender sends PUBLISH; the receiver stores the packet identifier and replies PUBREC (“received”). The sender then discards the message, keeps only the identifier and sends PUBREL (“release”). The receiver discards its stored identifier and replies PUBCOMP (“complete”), after which the identifier is free.
The receiver’s rule is what makes the guarantee: until it sees PUBREL, it must answer any repeated PUBLISH with the same identifier by sending PUBREC again, without delivering the message onward a second time. The 3.1.1 specification illustrates two valid receiver strategies. In Method A the receiver stores the whole message and delivers it onward when PUBREL arrives. In Method B it stores only the identifier and delivers onward immediately on the first PUBLISH. Method B is faster; Method A delays onward delivery by a further round trip.
QoS 2 therefore costs four packets and two round trips before the sender can reuse the identifier. It protects one hop against duplicates caused by lost acknowledgements during a reconnect. It does not protect against a broker that loses its state, an application that crashes after receiving, or a subscriber whose subscription is only QoS 1.
Effective QoS is the minimum of three numbers
The QoS a subscriber actually receives is not the publisher’s choice. The broker forwards each message at the lower of the publish QoS and the maximum QoS granted on that subscription. A QoS 2 publish to a QoS 0 subscription arrives at QoS 0. The broker can downgrade but never upgrade (Mosquitto has a non-standard upgrade_outgoing_qos option, off by default).
MQTT 5 adds a third ceiling. The broker advertises Maximum QoS in CONNACK; if absent, the client assumes 2. A client must not publish above that level. Some managed cloud brokers support only QoS 0 and 1, so a design that assumes QoS 2 end to end may not even connect cleanly. The practical consequence: effective QoS = min(publish QoS, subscription QoS, broker Maximum QoS), evaluated separately for each hop.
MQTT QoS 0 vs 1 vs 2 comparison table
| Property | QoS 0 | QoS 1 | QoS 2 |
|---|---|---|---|
| Spec name | At most once | At least once | Exactly once (per hop) |
| Control packets per message | 1 (PUBLISH) | 2 (PUBLISH, PUBACK) | 4 (PUBLISH, PUBREC, PUBREL, PUBCOMP) |
| Packet identifier | None | 16-bit, non-zero | 16-bit, non-zero |
| Round trips until sender releases state | 0 | 1 | 2 |
| Duplicates possible on a hop | No | Yes, after reconnect | No, if receiver keeps state |
| Loss possible on a hop | Yes, at disconnect | No, with persistent session | No, with persistent session |
| Counts against Receive Maximum | No | Yes | Yes |
| Queued for offline session | Broker-optional | Yes, up to queue limit | Yes, up to queue limit |
| Typical use | High-rate telemetry, last-value-wins | Events, alarms, commands with idempotent handlers | Rare; non-idempotent actions on one hop |
Sessions, Retained Messages and the MQTT 5 Controls That Make QoS Real
Every one of the MQTT QoS levels above 0 needs memory. The memory lives in the session, and the session’s lifetime is controlled by connection flags. MQTT 5 also added message lifetimes and flow control. Together these decide whether QoS 1 or 2 actually delivers after a disconnect.

Figure 2: How a broker handles a CONNECT under MQTT 5: Clean Start and the Session Expiry timer decide whether in-flight QoS state and queued messages survive.
The flow shows the two decisions that matter at connect time: whether the client asked for a clean start, and whether a stored session still exists. Only the resume path triggers resending of unacknowledged packets and delivery of the offline queue. After a network drop, the expiry timer decides how long that path stays open.
Clean Session in 3.1.1 vs Clean Start plus Session Expiry in MQTT 5
MQTT 3.1.1 has a single CleanSession flag. CleanSession 1 means “start fresh and throw everything away when I disconnect”. CleanSession 0 means “resume my session, and keep it after I disconnect”, with no defined end; brokers invented their own expiry settings. Mosquitto’s persistent_client_expiration, for example, is unset by default, which means persistent clients never expire unless you configure it.
MQTT 5 splits the flag into two independent controls. Clean Start (a CONNECT flag) decides whether an existing session is discarded at connect time. Session Expiry Interval (a four-byte property, in seconds) decides how long the session survives after the network connection closes. If the property is absent or 0, the session ends when the connection closes. If it is 0xFFFFFFFF, the session never expires. Clean Start 1 with Session Expiry 0 reproduces 3.1.1 CleanSession 1.
The client can also lower or raise the expiry in its DISCONNECT packet, which lets a device announce “I am going to sleep for six hours, keep my session” at the moment it leaves. One restriction: if the CONNECT carried an expiry of 0, the client may not set a non-zero value at DISCONNECT. The broker reports whether it found a session through the Session Present flag in CONNACK, and a well-written client checks it.
What a persistent session actually stores
The MQTT 5 specification lists the session state explicitly. On the server side it includes the subscriptions (with their subscription identifiers), QoS 1 and 2 messages sent to the client but not fully acknowledged, QoS 1 and 2 messages pending transmission, optionally QoS 0 messages pending transmission, QoS 2 messages received from the client but not fully acknowledged, the Will Message with its delay, and the session expiry time. On the client side it includes QoS 1 and 2 messages sent to the server but not fully acknowledged, and QoS 2 messages received but not fully acknowledged.
Notice that the client has state too. A device that reboots and loses RAM has lost its half of the session, even if the broker kept its half. If the device reconnects with Clean Start 0 but has no record of the unacknowledged QoS 1 messages it sent before the reboot, those messages are simply gone. Persistent sessions protect against network drops; they protect against device reboots only if the client library persists its in-flight store to flash.
Broker-side, the session is only as durable as the broker’s storage. Mosquitto’s persistence option defaults to false, so session state lives in memory, and when enabled the default autosave_interval is 1,800 seconds. A broker crash with default settings can lose every persistent session, which quietly converts QoS 1 and 2 into best effort. Clustered brokers such as EMQX and HiveMQ replicate session state, but replication mode and durability guarantees vary by version and configuration, so check your own deployment.
Retained messages: last known value, not history
Setting the RETAIN flag on a PUBLISH tells the broker to store that message as the retained message for the topic, replacing any previous one. There is exactly one retained message per topic. A new subscriber whose filter matches the topic receives it immediately, which is how dashboards and digital twins get the current state of a device without waiting for the next update. Publishing a zero-length payload with RETAIN set deletes the retained message.
Retained messages keep their QoS. The broker delivers a retained message at the lower of its stored QoS and the subscription QoS, exactly like a live message. MQTT 5 brokers can declare Retain Available 0 in CONNACK if they do not support retained messages, and a client must then not publish with RETAIN set.
MQTT 5 added two subscription options that control retained delivery. Retain Handling 0 sends retained messages every time the subscription is made; 1 sends them only if the subscription did not already exist; 2 never sends them. Retain Handling 1 is the right choice for a persistent session that re-subscribes on every reconnect, because it stops the client from re-processing the same last value each time. Retain As Published controls the RETAIN flag on forwarded live messages: when 0, the broker clears it, so subscribers can tell “this is the stored value” from “this just happened”; when 1, the broker keeps the flag as published, which bridges between brokers need.
MQTT 5 Message Expiry Interval
Message Expiry Interval is a four-byte PUBLISH property in seconds. When the broker forwards a message, it must send the property with the remaining lifetime: the received value minus the time the message waited in the broker. Once the lifetime runs out, the broker must not forward the message to any subscriber that has not received it yet. This applies to queued messages for offline sessions and to retained messages.
This is the single most useful MQTT 5 feature for QoS 1 command channels. A “open valve 7” command that sits in a queue for three hours and executes when the gateway comes back is a safety problem, not a reliability feature. Set an expiry of a few seconds to minutes on commands, and let telemetry expire after it stops being useful. Mosquitto also has a retain_expiry_interval option to periodically remove expired retained messages.
Receive Maximum: the in-flight window
Receive Maximum is a two-byte property that each side sends at connect time. It caps the number of QoS 1 and QoS 2 publications the sender may have unacknowledged towards that receiver at once. The default is 65,535 if absent, and 0 is a protocol error. QoS 0 is not counted. The 16-bit packet identifier space limits in-flight messages to 65,535 per direction anyway.
Brokers apply their own window too. Mosquitto’s max_inflight_messages defaults to 20. EMQX’s mqtt.max_inflight defaults to 32, and EMQX applies the smaller of this and a v5 client’s Receive Maximum. Messages beyond the window wait in the per-client queue: Mosquitto’s max_queued_messages defaults to 1,000 and EMQX’s max_mqueue_len defaults to 1,000. When EMQX’s queue fills it drops the oldest QoS 0 message first, then the oldest message of any QoS. That is message loss at QoS 1 and 2, by configuration, with no protocol error.
Will Delay, shared subscriptions and reason codes
The Will Message is published by the broker when a client disconnects ungracefully. MQTT 5 adds Will Delay Interval: the broker waits that long before publishing the will, and cancels it if the client reconnects to the session in time. The will is published at the earlier of the delay ending or the session ending. A delay of 30 to 60 seconds stops every cellular blip from raising an “offline” alarm.
Shared subscriptions ($share/<group>/<filter>) distribute messages across a group of consumers. QoS interacts with them in specific ways: for QoS 2, if the connection to the chosen client breaks mid-delivery, the broker must finish delivery to that same client on reconnect and must not reroute it if the session ends. Our deep dive on MQTT 5 shared subscriptions and consumer groups covers load balancing and backpressure in detail.
Finally, MQTT 5 puts a reason code on PUBACK and PUBREC. Reason code 0x10 means “No matching subscribers”; 0x87 means “Not authorized”; 0x97 means “Quota exceeded”. A reason code of 0x80 or above means the message was rejected but counts as acknowledged and must not be resent. Under 3.1.1 a broker could only drop the message silently or close the connection, so a publisher had no reliable way to tell “delivered” from “refused”.
Worked Analysis: MQTT QoS Levels by Latency, Throughput, Airtime and Duplicates
Choosing between MQTT QoS levels is an engineering trade-off with measurable costs. The numbers below are illustrative, derived from packet formats and simple RTT models, not from a benchmark. Use them to reason about your own link, then measure.

Figure 3: One QoS 2 publish fans out at different effective QoS per subscriber, lands in the retained store, and waits in an offline session queue with its expiry counting down.
A single publish produces several independent deliveries. Each subscriber gets the minimum of the publish QoS and its own subscription QoS. Retained storage and offline queues are separate paths with separate rules, and expiry applies to both.
Latency: count the round trips
Let RTT be the network round-trip time between publisher and broker. At QoS 0 the message reaches the broker after about half an RTT, and the publisher has no further obligation. At QoS 1 the publisher learns of success after one RTT. At QoS 2 the broker can deliver onward after half an RTT under Method B, but the publisher holds its packet identifier for two full RTTs until PUBCOMP.
End-to-end, the hops add, and the MQTT QoS levels diverge mainly in confirmation time. With an illustrative 120 ms cellular RTT from device to broker and a 2 ms RTT from broker to a subscriber in the same data centre, the one-way delivery latency is about 61 ms at every QoS level when the broker forwards on first receipt. The difference shows up in the publisher’s confirmation time: about 120 ms for QoS 1 and 240 ms for QoS 2. If the broker uses Method A and delays onward delivery until PUBREL, QoS 2 delivery latency rises to roughly 180 ms.
Throughput: the in-flight window bounds the rate
For QoS 1 and 2, the sender can have at most W messages unacknowledged on a connection. With a steady flow, sustained throughput per connection is bounded by W divided by the time each identifier is held. For QoS 1 that is about one RTT; for QoS 2 about two.
| Illustrative scenario | Window W | RTT | QoS 1 ceiling | QoS 2 ceiling |
|---|---|---|---|---|
| Cellular device, Mosquitto default window | 20 | 120 ms | ~167 msg/s | ~83 msg/s |
| Cellular device, EMQX default window | 32 | 120 ms | ~267 msg/s | ~133 msg/s |
| Satellite link | 20 | 600 ms | ~33 msg/s | ~17 msg/s |
| LAN gateway | 20 | 1 ms | ~20,000 msg/s | ~10,000 msg/s |
These are protocol ceilings, not predictions; CPU, disk persistence and TCP behaviour usually bind first on a LAN. On high-latency links the window binds first, and QoS 2 halves the ceiling. That is why satellite-connected fleets that “randomly” back up are often just running QoS 1 or 2 with a 20-message window. Raising Receive Maximum or batching several readings into one payload fixes it; switching to QoS 2 makes it worse.
Airtime and bytes: what MQTT QoS levels cost on the wire
Take a 100-byte payload on the topic plant/line3/press7/temp (23 bytes) under MQTT 5 with no properties. The PUBLISH packet is a 2-byte fixed header, 2 bytes of topic length, 23 bytes of topic, 1 byte of property length and 100 bytes of payload: 128 bytes at QoS 0. QoS 1 and 2 add a 2-byte packet identifier, giving 130 bytes. A successful PUBACK, PUBREC, PUBREL or PUBCOMP with no properties can be just 4 bytes.
At the MQTT layer the totals are therefore 128 bytes (QoS 0), 134 bytes (QoS 1) and 142 bytes (QoS 2): a modest 5% to 11% difference. The cost appears below MQTT. If each control packet travels in its own TLS 1.3 record (about 22 bytes of record overhead with AES-GCM) and its own TCP/IPv4 segment (40 bytes without options), the illustrative totals become roughly 190, 256 and 388 bytes. QoS 2 costs about twice the bytes of QoS 0 for small messages, because three of its four packets are pure overhead. TCP delayed ACKs and piggybacking can reduce this, so measure on your stack.
Battery cost follows radio state, not bytes. On LTE and NB-IoT, a modem stays in a high-power connected state for an operator-configured inactivity period after the last packet, commonly several seconds. An acknowledgement that arrives late extends that period. For a device that wakes, sends one reading and sleeps, QoS 1 costs one extra receive window and QoS 2 costs one more transmit plus receive. Reducing reports per wake-up saves far more energy than lowering QoS.
Duplicates: plan for them at QoS 1
Among MQTT QoS levels, only QoS 1 produces duplicates by design, and the duplicate rate is a function of reconnects, not message volume. Every reconnect with a persistent session resends every unacknowledged message, so the worst-case duplicates per reconnect equals the in-flight window: 20 on a default Mosquitto connection. A device that reconnects ten times a day with a full window could produce up to 200 duplicates per day; an idle device produces none.
The correct response is an idempotent consumer, not QoS 2. Put a producer-generated identifier in every message (a sequence number per device, or a UUID in an MQTT 5 user property), and make the consumer reject identifiers it has already processed. This also covers duplicates that QoS 2 cannot see, such as a device that reboots and re-sends from its flash buffer, or a bridge that replays after failover.
paho-mqtt: a persistent-session publisher with expiry
The following uses the Eclipse Paho Python client (the 2.x series, which requires an explicit callback API version). It connects with MQTT 5, asks for a one-hour session, advertises a Receive Maximum, and publishes a command with a 30-second expiry.
import json, time, uuid
import paho.mqtt.client as mqtt
from paho.mqtt.enums import CallbackAPIVersion
from paho.mqtt.properties import Properties
from paho.mqtt.packettypes import PacketTypes
BROKER = "broker.example.com"
def on_connect(client, userdata, flags, reason_code, properties):
# flags.session_present tells us whether the broker resumed our session
print("connected:", reason_code, "session_present:", flags.session_present)
def on_publish(client, userdata, mid, reason_code, properties):
# MQTT 5: reason codes >= 0x80 mean the broker refused the message
if reason_code.is_failure:
print("publish", mid, "rejected:", reason_code)
client = mqtt.Client(
CallbackAPIVersion.VERSION2,
client_id="press7-gateway", # stable ID: required for session resume
protocol=mqtt.MQTTv5,
)
client.max_inflight_messages_set(20)
client.tls_set()
client.on_connect = on_connect
client.on_publish = on_publish
connect_props = Properties(PacketTypes.CONNECT)
connect_props.SessionExpiryInterval = 3600 # keep session 1 h after disconnect
connect_props.ReceiveMaximum = 32 # our inbound in-flight window
client.connect(BROKER, 8883, keepalive=60,
clean_start=False, properties=connect_props)
client.loop_start()
pub_props = Properties(PacketTypes.PUBLISH)
pub_props.MessageExpiryInterval = 30 # stale commands must not execute
pub_props.UserProperty = [("msg-id", str(uuid.uuid4()))]
info = client.publish("plant/line3/press7/cmd",
json.dumps({"action": "open_valve", "valve": 7}),
qos=1, retain=False, properties=pub_props)
info.wait_for_publish(timeout=10)
Two details matter. First, the client ID must be stable, because the broker keys the session on it; a random ID per boot creates a new empty session every time. Second, paho’s connect() defaults clean_start to MQTT_CLEAN_START_FIRST_ONLY, which starts clean on the first connect and resumes on automatic reconnects. That default discards any session left over from the previous process run, so set clean_start=False explicitly when you want resume across restarts.
paho-mqtt: an idempotent subscriber with retain handling
The subscriber below requests QoS 1, receives retained values only when the subscription is new, and deduplicates on the msg-id user property using SQLite’s primary-key constraint. It acknowledges manually, after the write commits.
import sqlite3
import paho.mqtt.client as mqtt
from paho.mqtt.enums import CallbackAPIVersion
from paho.mqtt.subscribeoptions import SubscribeOptions
from paho.mqtt.properties import Properties
from paho.mqtt.packettypes import PacketTypes
db = sqlite3.connect("processed.db", check_same_thread=False)
db.execute("CREATE TABLE IF NOT EXISTS seen (msg_id TEXT PRIMARY KEY, topic TEXT, body BLOB)")
def on_connect(client, userdata, flags, reason_code, properties):
opts = SubscribeOptions(qos=1, noLocal=True, retainAsPublished=False,
retainHandling=SubscribeOptions.RETAIN_SEND_IF_NEW_SUB)
client.subscribe(("plant/+/+/cmd", opts))
def on_message(client, userdata, msg):
props = dict(getattr(msg.properties, "UserProperty", []) or [])
msg_id = props.get("msg-id")
try:
with db: # commits or rolls back
db.execute("INSERT INTO seen VALUES (?, ?, ?)", (msg_id, msg.topic, msg.payload))
handle_command(msg.topic, msg.payload) # your side effect
except sqlite3.IntegrityError:
pass # duplicate: already processed, just acknowledge
client.ack(msg.mid, msg.qos) # PUBACK only after durable work
def handle_command(topic, payload):
print("executing", topic, payload)
client = mqtt.Client(CallbackAPIVersion.VERSION2, client_id="cmd-executor-1",
protocol=mqtt.MQTTv5, manual_ack=True)
client.on_connect = on_connect
client.on_message = on_message
props = Properties(PacketTypes.CONNECT)
props.SessionExpiryInterval = 86400
client.connect("broker.example.com", 1883, clean_start=False, properties=props)
client.loop_forever()
The ordering in this sketch is deliberately conservative: record, act, then acknowledge. If the process crashes after the insert but before the side effect, the redelivered message is treated as a duplicate and skipped, so a real system needs either a transactional side effect or an outbox. The point is that delivery semantics are an application property. MQTT QoS levels only decide how often the broker tries.
Decision matrix: MQTT QoS levels for each IoT message type
| Message type | Recommended QoS | Retain | Session | MQTT 5 extras | Why |
|---|---|---|---|---|---|
| High-rate sensor telemetry (≥1 Hz) | 0 | No | Clean or short expiry | Topic Alias | Next sample supersedes loss; minimise airtime |
| Device state / last value (online, firmware version, setpoint) | 1 | Yes | Persistent | Retain Handling 1 on resume | New subscribers need current state immediately |
| Alarms and events | 1 | No | Persistent, hours | Message Expiry, msg-id property | Must arrive; duplicates handled by ID |
| Commands to devices | 1 | No (never retain commands) | Persistent, short expiry | Message Expiry seconds to minutes, Response Topic | Stale commands are dangerous; need confirmation |
| Billing or metering counters | 1 with idempotent consumer | No | Persistent + broker disk persistence | User property sequence number | Cumulative counters tolerate duplicates and loss |
| Non-idempotent single-hop action with no app-level ID | 2 | No | Persistent | Receive Maximum tuned | Only case where QoS 2 adds real value |
| Liveness | Will message QoS 1, retained | Yes | Persistent | Will Delay 30 to 60 s | Avoids alarm storms on brief drops |
A note on metering: send cumulative totals rather than deltas. A cumulative counter makes duplicates harmless and lost messages recoverable, because the next reading carries the full value. That single design choice removes the need for QoS 2 in most billing pipelines.
Trade-offs, Gotchas, and What Goes Wrong
Most MQTT delivery failures blamed on MQTT QoS levels come from state that silently disappears. The protocol behaves exactly as specified; the configuration around it does not match the team’s assumptions.

Figure 4: Where messages are lost or duplicated in practice. Only one branch, QoS 0 on a flaky link, is a direct consequence of the QoS level itself.
The tree groups failure modes by where the state lives. Most branches are configuration and lifecycle problems that no QoS level can fix.
In-flight queue overflow. Every broker bounds the per-client queue. When a slow subscriber or a long offline period fills it, the broker drops messages, usually oldest first, and the publisher still received its PUBACK. Monitor queue depth and dropped-message counters per client, and size the queue against the longest outage you intend to survive: 1,000 messages at one per second is under 17 minutes.
Session state loss. Three things delete a session without warning: the Session Expiry Interval running out, a client connecting with Clean Start 1 (including the paho first-connect default), and a broker restart without disk persistence. Any of these turns QoS 1 and 2 into best effort for that client. Check the Session Present flag on every reconnect and alert when it is unexpectedly 0.
Client ID collisions. The broker allows one connection per client ID and disconnects the older one when a second connects. Two devices flashed with the same ID will fight indefinitely, each taking over the other’s session and its queue. This appears as reconnect storms and duplicates, not as an error.
The QoS 2 end-to-end myth. QoS 2 gives once-per-hop delivery between two parties that keep their state. It does not span publisher to subscriber, because the broker is a separate hop and may downgrade. It does not survive a bridge, because each bridge is another pair of hops. It does not cover the application, because the library acknowledges at the protocol level. Treat “exactly once” as a property you build with idempotent processing, not a flag you set.
Retained message surprises. Retained commands execute again on every new subscription; never retain commands. Retained values persist after a device is decommissioned unless you publish an empty retained message to clear them. With wildcard subscriptions, a new dashboard can receive thousands of retained messages at once, which can briefly saturate a constrained client.
Ordering assumptions. MQTT preserves order per topic only under specific conditions, essentially for messages at the same QoS on one connection. Mixing QoS levels on a topic, using shared subscriptions, or resending after reconnect can all reorder delivery. Put timestamps or sequence numbers in payloads and let consumers order them.
Downgrades nobody noticed. A historian that subscribes at QoS 0 receives every alarm at QoS 0, regardless of the publisher’s choice. Audit subscription QoS, not just publish QoS.
Practical Recommendations
Across the MQTT QoS levels, default to QoS 1 with idempotent consumers for anything that matters, and QoS 0 for high-rate telemetry. Reserve QoS 2 for the rare single-hop action that cannot be made idempotent. Spend the effort you would have spent on QoS 2 on sessions, broker durability and queue sizing instead, because that is where real deployments lose data.
Treat MQTT 5 features as the safety controls that make MQTT QoS levels dependable, not as extras. Message Expiry Interval belongs on every command. Session Expiry Interval should match the longest outage you plan to tolerate, not “forever”. Receive Maximum and broker in-flight limits should be tuned for the link’s RTT. Reason codes should be logged and alerted on.
For gateways that must survive long outages without relying on broker-side queues, buffer to disk locally and replay with your own sequence numbers; our store-and-forward edge gateway guide walks through that design. For industrial payloads, the topic and state conventions in Sparkplug B versus plain MQTT topics handle birth, death and sequence numbering for you. If you are moving data onward to analytics, the MQTT to Kafka bridge tutorial shows how to keep delivery semantics consistent across the hop.
Checklist:
- [ ] Every device has a stable, unique client ID.
- [ ] Clean Start is explicitly false where sessions must survive restarts; Session Present is checked and alerted on.
- [ ] Session Expiry Interval is set to a deliberate value per device class.
- [ ] Broker disk persistence is enabled and its flush interval matches your loss tolerance.
- [ ] Per-client queue limits are sized against the longest planned outage, and drop counters are monitored.
- [ ] Every command carries a Message Expiry Interval and is never retained.
- [ ] Every message carries a producer-generated ID or sequence number; consumers deduplicate.
- [ ] Subscription QoS is audited so critical topics are not silently downgraded.
- [ ] Will messages use a Will Delay Interval to suppress alarm storms.
- [ ] Receive Maximum and the broker in-flight window are tuned for the link RTT.
Frequently Asked Questions
What is the difference between MQTT QoS 0, 1 and 2?
QoS 0 sends a PUBLISH packet once with no acknowledgement, so a message can be lost if the connection drops. QoS 1 requires a PUBACK and resends on reconnect, so the message arrives at least once but may be duplicated. QoS 2 uses a four-packet handshake, PUBLISH, PUBREC, PUBREL and PUBCOMP, so the receiver delivers each message once on that hop. Each level applies to one hop only, between a client and the broker, and depends on a persistent session to survive disconnects.
Does MQTT QoS 2 guarantee exactly-once delivery end to end?
No. QoS 2 guarantees once-per-hop delivery between two parties that keep their session state. The publisher-to-broker hop and the broker-to-subscriber hop are separate, and the broker may downgrade the second hop to the subscriber’s QoS. A broker without disk persistence can lose state on a crash, and an application can crash after the library acknowledges. End-to-end exactly-once processing requires idempotent consumers keyed on a producer-generated message identifier, which also makes QoS 1 sufficient for most systems.
What is an MQTT persistent session?
A persistent session is broker-side and client-side state that survives a network disconnect. The broker keeps the client’s subscriptions, unacknowledged QoS 1 and 2 messages, and messages queued while the client was offline. In MQTT 3.1.1 you request it with CleanSession 0. In MQTT 5 you connect with Clean Start 0 and a non-zero Session Expiry Interval, which sets how many seconds the session survives after disconnect. The client must reuse the same client ID, and the broker signals resume with the Session Present flag.
How do MQTT retained messages work?
When a publisher sets the RETAIN flag, the broker stores that message as the single retained message for the topic, replacing the previous one. Any new subscriber whose filter matches receives it immediately, which gives dashboards and digital twins the last known value. Publishing an empty payload with RETAIN set clears it. In MQTT 5, the Retain Handling subscription option controls whether retained messages are sent on every subscribe, only on new subscriptions, or never, and expired retained messages are not delivered.
What does MQTT 5 Message Expiry Interval do?
Message Expiry Interval is a PUBLISH property giving the message lifetime in seconds. The broker counts down while the message waits, forwards it with the remaining lifetime, and must not deliver it to any subscriber once the lifetime has passed. This applies to offline session queues and retained messages. It is essential for device commands, because it stops a command queued during an outage from executing hours later when the device reconnects. It also keeps stale telemetry from flooding consumers after a long disconnect.
Which MQTT QoS level should I use for IoT telemetry?
Use QoS 0 for high-rate telemetry where the next sample replaces the previous one, because it minimises airtime, battery use and broker state. Use QoS 1 for events, alarms, state changes and commands, combined with a message ID so consumers can drop duplicates. Use QoS 2 only for a non-idempotent action on a single hop when you cannot add an identifier. On high-latency links remember that QoS 1 and 2 throughput is capped by the in-flight window divided by the round-trip time.
Further Reading
- MQTT store-and-forward at the edge gateway: offline buffering, broker bridging and QoS for durable buffering beyond broker queues.
- OPC UA PubSub over MQTT 5: an implementation tutorial for mapping industrial information models onto MQTT 5 transport.
- Sparkplug B vs plain MQTT topics for birth and death certificates, sequence numbers and state management.
- MQTT-SN vs MQTT vs CoAP for constrained sensor networks when TCP itself is too heavy.
- OASIS MQTT Version 5.0 specification, the normative source for every rule in this post.
- Mosquitto configuration reference and EMQX in-flight window and message queue design for broker limits.
By Riju — about
