MQTT Clean Session: What It Is and How It Works
clean session is a flag that tells the broker whether to keep the client's subscription and messages after it disconnects. If clean session is true, the broker does not save any session data, starting fresh each time the client connects. If false, the broker keeps the session so the client can receive missed messages.How It Works
Think of MQTT clean session like visiting a coffee shop. If you say you want a clean session, it's like starting fresh every time you visit—no saved orders or preferences. The broker forgets your subscriptions and messages when you disconnect.
If you choose not to clean the session, it's like the coffee shop remembering your favorite drink and saving your order history. The broker keeps your subscriptions and any messages sent while you were away, delivering them when you reconnect.
This flag is set during the client's connection request and controls whether the broker stores session state between connections.
Example
This example shows how to connect to an MQTT broker with clean session set to true and false using Python's paho-mqtt client.
import paho.mqtt.client as mqtt # Callback when connected def on_connect(client, userdata, flags, rc): print(f"Connected with result code {rc}") client.subscribe("test/topic") # Create client with clean_session=True client_clean = mqtt.Client(clean_session=True) client_clean.on_connect = on_connect client_clean.connect("test.mosquitto.org", 1883, 60) client_clean.loop_start() # Disconnect after short delay import time time.sleep(2) client_clean.loop_stop() client_clean.disconnect() # Create client with clean_session=False client_persistent = mqtt.Client(clean_session=False) client_persistent.on_connect = on_connect client_persistent.connect("test.mosquitto.org", 1883, 60) client_persistent.loop_start() # Disconnect after short delay time.sleep(2) client_persistent.loop_stop() client_persistent.disconnect()
When to Use
Use clean session = true when you want a fresh start each time your device connects, such as for sensors that send data occasionally and do not need to receive old messages.
Use clean session = false when your device needs to receive messages sent while it was offline, like commands or updates for smart home devices or industrial machines. This ensures no important messages are missed.
Key Points
- Clean session true means no saved subscriptions or messages after disconnect.
- Clean session false keeps session data for message delivery on reconnect.
- Choosing the right setting depends on whether you need message persistence.
- It affects how the broker manages client state and message queues.