Search topics...
Networking ProtocolsMQTT & Application Protocolsintermediate

How do you handle MQTT broker disconnection and message persistence?

0 upvotes
Practice with AISoon

Broker disconnections are inevitable in embedded IoT — networks fail, brokers restart, and wireless links drop. A robust MQTT client must handle disconnections transparently. The MQTT protocol provides two key mechanisms: clean session and persistent session.

With cleanSession = true (MQTT 3.1.1) or sessionExpiryInterval = 0 (MQTT 5.0), the broker discards all session state when the client disconnects — subscriptions are lost, and any QoS 1/2 messages published while the client was offline are dropped. The client must resubscribe after reconnecting. This is simpler but means you lose messages during downtime. With cleanSession = false, the broker retains the session — subscriptions persist, and QoS 1/2 messages published while the client was offline are queued and delivered when it reconnects. This is essential for command delivery to intermittently connected devices.

On the client side, you need local message persistence. When the device publishes a QoS 1/2 message but the connection is down, the message must be stored locally — in a circular buffer in RAM, or in flash/EEPROM for persistence across reboots. The client library retransmits these messages after reconnecting. Paho Embedded C supports pluggable persistence backends for this purpose. Size the buffer appropriately: on a cellular IoT device that transmits sensor data every 30 seconds and may be offline for up to 1 hour, you need buffer space for 120 messages.

Also implement Last Will and Testament (LWT): register a will message (e.g., {"status": "offline"} on topic devices/{id}/status) during CONNECT. If the client disconnects ungracefully (crash, network failure), the broker automatically publishes the LWT, notifying other subscribers. Pair this with a retained message published on connect ({"status": "online"}) so the device's online/offline status is always current. This pattern provides reliable presence detection without polling.

Source: Networking Protocols Q&A