Clean Session

To understand what the clean session feature is about, we have look at the MQTT session initiation. When a device connects to a MQTT broker for the first time it implicitly creates a new MQTT session. One part of that session consists of state stored on the broker, and the other part of the session is state stored on the client.

Session state can be bound to the lifetime of the TCP connection, but it doesn't have to be. The state on the broker and the client can also be persisted.

What is in the Session State? Let's have a look what the MQTT specification says about what should be in the server state and the client state of a session:

The Session state in the Client consists of:

  • Messages which have been received from the broker, but haven't been completely acknowledged.
  • Messages which have been sent to the client, but have not been completely acknowledged.
  • The client’s subscriptions.

In conclusion, one of the benefits of MQTT and its session concept, is that sessions can survive re-connects. When connectivity is very expensive, limited, or rapidly changing a device will not be connected all the time. While offline, the broker still keeps the session around and accumulates all messages that match the device's subscriptions. As soon as the client reconnects all the outstanding messages will be delivered.