MQTT Essential Features
Clean Session.

Clean Session

To understand what the clean session feature is about, we have to 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:

  • QoS 1 and QoS 2 messages which have been sent to the Server, but have not been completely acknowledged.
  • QoS 2 messages which have been received from the Server, but have not been completely acknowledged.

The session state in the server consists of:

  • The existence of a Session, even if the rest of the Session state is empty.
  • The Client’s subscriptions.
  • QoS 1 and QoS 2 messages which have been sent to the Client, but have not been completely acknowledged.
  • QoS 1 and QoS 2 messages pending transmission to the Client.
  • QoS 2 messages which have been received from the Client, but have not been completely acknowledged.
  • Optionally, QoS 0 messages pending transmission to the Client.

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.