A client subscribing to a topic can ask the broker to retain, or queue, messages for it while it's offline. This is known in MQTT terminology as a durable connection. For durable connections and delivery to work, the subscribing client needs to be configured and subscribe in a certain way, as follows:
- The client must provide a unique client ID to the broker when it connects.
- The client must subscribe with a QoS 1 or 2 (levels 1 and 2 guarantee delivery, but level 0 does not).
- The client is only guaranteed to get messages published with QoS 1 or 2.
The last two points concern an example where knowing QoS on both the publishing and subscribing sides of a topic is very important for IoT application design.
MQTT brokers can—and the default configuration of Mosquitto on the Raspberry Pi does—retain messages for durable connections between broker restarts.
Let's step through an example:
- Start a subscriber, and then immediately...