
Recall first from Brokers and client libraries
- An edge broker can serve local clients during an internet outage if the broker and local network remain available.
- The application must keep MQTT network processing active, whether its API exposes blocking calls, completion callbacks, or both.
- mosquitto_sub -v prints the topic and payload. The packet capture shows the QoS and RETAIN fields.
What each QoS level guarantees
4 min readWith a broker and client running, the next question is what delivery actually promises; this lesson unpacks the three QoS levels and session persistence.
A connection can fail after a broker receives a publication but before the publisher receives its acknowledgment. From the publisher's perspective, an absent acknowledgment is consistent with either outcome. Linux TCP provides a reliable, ordered byte stream while the connection works. A successful local write can precede receipt by the peer, and a TCP acknowledgment concerns bytes received by the peer's TCP stack. MQTT defines what the receiving MQTT endpoint confirms and which exchanges can resume on another connection. tcp(7)
The OASIS MQTT specifications define the three levels for delivery between a sender and a receiver. A publication routed through a broker involves two exchanges. The publisher sends it to the broker, then the broker sends it to each matching subscriber. The broker can acknowledge its incoming exchange while a subscriber is offline. For a single matching subscription, the outgoing delivery QoS is the lower of the publication QoS and the maximum QoS granted for that subscription. A QoS 2 publication delivered through a subscription granted QoS 1 therefore has QoS 1 on the outgoing exchange.
QoS 0 is at most once. The sender sends a PUBLISH with no MQTT acknowledgment and no packet identifier. MQTT does not retry that publication. If the connection fails before the receiver processes it, the receiver can miss it. This suits periodic measurements when the next reading is useful on its own and missing a reading is acceptable.
QoS 1 is at least once. The sender assigns a packet identifier, sends PUBLISH, and keeps the exchange outstanding until it receives PUBACK. If the receiver accepts a message and the connection drops before PUBACK arrives, the sender can resend the outstanding PUBLISH when the session resumes. The receiver may deliver it to its application again. At least once describes the protocol exchange under its delivery conditions. The peers still need to reconnect and retain the state required to finish delivery.
QoS 2 is exactly once. The peers track the publication through a longer exchange so that retransmitted packets do not cause the receiving MQTT endpoint to deliver that publication again. This guarantee applies to that exchange with its state intact. If a publisher submits the same event twice as two new publications, MQTT treats them as two publications. An application that must apply a database update once still needs to account for the timing of its own commit and recovery.
A nonzero value used to match packets belonging to an MQTT exchange is scoped to the sending endpoint's outstanding exchanges with its peer. Each direction manages its own identifiers. The broker assigns an identifier for its own QoS 1 or 2 delivery to a subscriber. Once an exchange finishes, its sender can reuse the identifier. Keeping a permanent list of packet identifiers would eventually cause valid new publications to be discarded.
The DUP flag belongs to the PUBLISH packet. For a retransmitted QoS 1 or 2 PUBLISH, the sender sets DUP and uses the original packet identifier. The receiver might see that retransmission as its first copy because the earlier packet was lost. Conversely, a broker can forward a repeated application event in a new outgoing exchange with DUP clear, because it is sending that outgoing packet for the first time. The broker sets the flag according to its own transmission history.
When repeated processing matters, give the event a stable application identifier and preserve it across retries. For example, a gateway can record an alarm's event ID in the same database transaction that inserts the alarm. A uniqueness constraint lets a later delivery of the same event leave the existing record intact. Include the event's producer in the identity if multiple producers can issue the same ID. This deduplicates the database change even when MQTT handles the deliveries as separate exchanges.
What survives a disconnect
4 min readA TCP connection ends when the client disconnects. An MQTT session can outlive that connection. The broker associates session state with the client identifier. That state can include the client's subscriptions, outgoing QoS 1 and 2 messages waiting for delivery, and unfinished protocol exchanges. The client also has state to preserve, including outgoing QoS 1 and 2 exchanges and incoming QoS 2 state needed to finish an exchange. A network reconnect can leave a client's memory intact. A process restart requires the client to recover any state it needs from storage or another durable source.
In MQTT 3.1.1, connect with Clean Session set to false and use the same client ID to resume an existing session or create one if the broker has none. A connect with Clean Session set to true discards any previous session and starts one that lasts for the connection. In MQTT 5, Clean Start controls whether the broker starts fresh or attempts to resume. Session Expiry Interval controls how long a session remains after disconnect. An interval of zero ends the session at disconnect. To resume a session after an outage, use the same ID, request resumption, and reconnect while the session still exists. MQTT 3.1.1 has no client-supplied session expiry interval. Broker administration can still affect how long disconnected sessions are kept.
Read Session Present in the successful CONNACK when inspecting a reconnect. A set bit tells the client that the broker has existing session state. A clear bit means the client has a new session and must establish the subscriptions it needs. For example, a client that reconnects with a new generated ID will have a different session, even if its topic choices are identical. An expired session also means a fresh subscription can receive future publications, but it cannot recover the expired session's queue.
Offline queuing starts with a subscription that already exists in a persistent session. When a matching publication arrives while that client is offline and the resulting delivery QoS is 1 or 2, the broker queues it for that session, subject to available resources and configured queue limits. MQTT 3.1.1 allows brokers to store QoS 0 messages for offline sessions as an option. For a portable design, assume no offline QoS 0 delivery. Retained publications are stored by topic for matching subscribers, whereas this offline queue is maintained for the existing client session. A subscriber that has never subscribed has no session queue for earlier publications.
On the local broker, these commands illustrate the reconnect sequence. Use a client ID reserved for this test and a topic with no retained message or other publisher. In one terminal, start the subscriber and wait for the subscription acknowledgment. The -d option shows protocol activity, -c disables clean session, and -i fixes the client ID.
mosquitto_sub -h localhost -V mqttv311 -c -i m6-qos-reader \
-t m6/qos/session -q 1 -d
Stop the subscriber with Ctrl+C after SUBACK. While it is offline, publish from another terminal. The -r option is absent, so this command sends a non-retained publication.
mosquitto_pub -h localhost -V mqttv311 \
-t m6/qos/session -q 1 -m 'offline alarm'
Run the subscriber command again with the same ID. In its debug trace, the receive order to look for is CONNACK, then the queued PUBLISH. The subscriber command also sends a SUBSCRIBE on reconnect. Since the publication is non-retained and was sent while the client was offline, receiving it demonstrates delivery from the old session's queue. In a test with Mosquitto 2.0.18 on Ubuntu 24.04 (default listener on port 1883), the second run printed offline alarm; the same steps without -c delivered nothing. The exact wording of the debug lines can differ between versions. To compare with a clean session, first connect with the same ID and omit -c. Wait for SUBACK, stop the subscriber, and publish a different payload while it is offline. Reconnect again without -c and inspect the trace for that payload. The broker had discarded the old session at the clean connect and ended the replacement session at disconnect.
How recovery and performance interact
3 min readA QoS 2 exchange uses PUBLISH, PUBREC, PUBREL, and PUBCOMP with the same packet identifier. The receiver records that it has accepted the PUBLISH before replying with PUBREC. Another PUBLISH for the same outstanding exchange can receive another PUBREC without triggering another delivery. When the sender receives PUBREC, it advances to PUBREL. If the session resumes at this stage, the sender resends PUBREL. The receiver responds with PUBCOMP, and the sender can then release the identifier. A repeated PUBREL can be answered without delivering the message again.
Consider a broker that sends PUBREC and then crashes before it receives PUBREL. The publisher may already have advanced to PUBREL and may no longer retain the original payload. Recovering the exchange requires the broker to restore the incoming QoS 2 state, including the payload if delivery is still pending. If the broker already made the message available for onward delivery, its recovered state must also prevent it from making that same incoming publication available again. Restoring only the subscription list cannot meet either requirement.
Persistence across a socket disconnect can work entirely in memory. Recovery after a broker process crash or power loss depends on what the broker saved, when it saved it, and what the storage guarantees. Periodic snapshots can leave recent acknowledged state missing from the recovered session. Linux exposes fsync() to synchronize file data and metadata with storage. A broker also needs a consistent on-disk record of the protocol stage and associated message to recover correctly. Test a clean reconnect and a broker crash as separate failure cases. The application's commit has its own recovery boundary, such as the database transaction that records an event ID and its effect together. fsync(2)
An limit on the number of sent QoS 1 or 2 publications awaiting completion controls how much work can proceed concurrently. With one slot on a QoS 1 sender, each PUBACK must arrive before the next publication can use the slot. When network round-trip time dominates, throughput is then roughly one completion per round trip. A larger window lets the sender transmit several publications before the first acknowledgment returns. QoS 2 generally keeps a slot occupied longer because it waits for PUBCOMP after the PUBREC and PUBREL exchange. Queued messages waiting to be sent and in-flight messages already sent consume resources at the same time.
Reuse a connection for successive publications when the device is online and sending regularly. This avoids repeating TCP and MQTT connection setup for every message. For intermittent clients, estimate how much the broker may need to hold from the publication rate, expected offline duration, payload size, and number of disconnected subscribers. Durable persistence also costs storage writes. More frequent durable commits can reduce the amount of state lost on a crash while increasing acknowledgment latency. A larger in-flight window can improve throughput on a slow link while increasing memory use and the amount of unfinished work at disconnect. Measure acknowledgment time, queue growth, and how long the queue takes to drain after reconnect. Measure subscriber processing time separately if that is what the product promises.
The next lesson, Topic design, security, and MQTT 5, looks at how subscriptions select the deliveries you just traced, who may publish or receive them, and how MQTT 5 gives clients more control over connection and session behavior.
Key takeaways
- MQTT QoS applies separately to publisher-to-broker and broker-to-subscriber delivery.
- QoS 1 can deliver duplicates, and packet identifiers can be reused after an exchange completes.
- A retained session can preserve subscriptions, queued QoS 1 and 2 messages, and unfinished exchanges across disconnects.
- QoS 2 crash recovery depends on restoring protocol state, and durable application effects require application-level handling.
Reflect
- Explain to a colleague, in two sentences: predict delivery and duplication for QoS 0, 1, and 2 on each MQTT connection.
- Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
- What surprised you when you ran the commands yourself?
On a real board
Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.
References and further reading
- Man pagetcp(7): TCP protocol
- Man pagefsync(2): synchronize a file's in-core state with storage
- SpecificationMQTT Version 3.1.1 (OASIS standard)
Official documentation first. Links checked when the lesson was published.