n this post we talk about persistent sessions and message queueing in MQTT.
Persistent Session
To receive messages from an MQTT broker, a client connects to the broker and creates subscriptions to the topics in which it is interested. If the connection between the client and broker is interrupted during a non-persistent session, these topics are lost and the client needs to subscribe again on reconnect.
Re-subscribing every time the connection is interrupted is a burden for constrained clients with limited resources. To avoid this problem, the client can request a persistent session when it connects to the broker. Persistent sessions save all information that is relevant for the client on the broker. The clientId that the client provides when it establishes connection to the broker identifies the session.
What’s stored in a persistent session?
In a persistent session, the broker stores the following information (even if the client is offline). When the client reconnects the information is available immediately.
- Existence of a session (even if there are no subscriptions).
- All the subscriptions of the client.
- All messages in a Quality of Service (QoS) 1 or 2 flow that the client has not yet confirmed.
- All new QoS 1 or 2 messages that the client missed while offline.
- All QoS 2 messages received from the client that are not yet completely acknowledged.
How do you start or end a persistent session?
When the client connects to the broker, it can request a persistent session. The client uses a cleanSession flag to tell the broker what kind of session it needs:
When the clean session flag is set to true, the client does not want a persistent session. If the client disconnects for any reason, all information and messages that are queued from a previous persistent session are lost.
When the clean session flag is set to false, the broker creates a persistent session for the client. All information and messages are preserved until the next time that the client requests a clean session. If the clean session flag is set to false and the broker already has a session available for the client, it uses the existing session and delivers previously queued messages to the client.
To understand in-depth on how an MQTT client knows if a session is already stored and to know some of the best practices while using persistent sessions, read this article.
Watch this video to visually understand persistent sessions in MQTT.
Get your copy of MQTT Essentials eBook to understand the protocol in detail without you having to read the entire specification.
Top comments (0)