MQTT · Study deck

MQTT Session Management

Picture a delivery box that sleeps between door events.

Broker Bex is your guide for this deck.

sessions
Broker Bex, the module guide, in a scene from this chapter.
iotclass.org

After studying this chapter

Learning objectives

You will be able to:

  • Configure Session Persistence: Select and configure clean versus persistent sessions for specific device types and use cases
  • Implement Secure MQTT: Apply TLS encryption, certificate-based authentication, and topic-level ACLs for production deployments
  • Distinguish Session Behaviors: Compare clean session and persistent session behaviors and justify the choice for a given scenario
  • Design Reconnection Strategies: Construct exponential backoff with jitter to prevent thundering-herd reconnection storms
• Choose clean or persistent state for a sleeping subscriber.
• Bound expiry and queue memory.
• Separate each quality-of-service leg from application outcome.
• Protect reconnect with TLS, identity, topic rules, and jitter.
iotclass.org

Major section

In 60 Seconds · Start With A Sleeping Device · Key Concepts

When it reconnects, it needs the right waiting messages, but an old event must not appear as a new opening.

  • Telemetry means readings and status sent by a remote device.
  • Message Queuing Telemetry Transport (MQTT) means a lightweight way for devices to exchange messages.

Key terms

Quality of service
Quality of service means the delivery promise chosen for a message; it is called QoS.
Latency
Latency means the delay between an action and its result.
iotclass.org

Major section

For Beginners: MQTT Session Management · The Power Nap Problem

A sleeping client may disconnect for ten minutes.

  • With a persistent session, the broker may retain subscriptions and queue eligible QoS 1 or QoS 2 messages until the client reconnects, subject to session expiry, message expiry and queue limits.
iotclass.org

Major section

Lab Setup · Try It: QoS Delivery Simulator

Hardware (Simulated):: Work through the two parts: the ESP32 sketch makes QoS 0 publish attempts with local skips, and the separate calculator illustrates QoS 0, 1 and 2 under modeled transfer disruptions.

  • Subscriber delivery requires separate measurement.
  • It deliberately skips about 20% of publish attempts at the application layer; that is not network packet loss or a subscriber delivery measurement.

Why it matters

QoS 2 avoids duplicate protocol delivery on a completed MQTT leg; a permanent failure can still prevent delivery.

Try it: Lab Setup · Try It: QoS Delivery Simulator in the chapter

iotclass.org

Major section

Checkpoint: QoS Tradeoffs · Security Considerations

In the chapter's simulator, 20% independently missed MQTT-level transfers over 100 QoS 0 sends gives an expected 80 deliveries and 20 losses; ordinary TCP packet loss would usually be retransmitted.

  • QoS 1 retries can yield duplicates if PUBACK is lost; delivery still depends on a working connection and retained session state.
iotclass.org

Major section

Unencrypted MQTT: A Critical Security Risk · Public MQTT Brokers: Never for Production

Unencrypted MQTT transmits credentials and data in plain text--network sniffers can capture usernames, passwords, and all sensor readings.

  • An attacker on your Wi-Fi network can see every temperature reading, door lock command, and camera feed.
  • The cost is minimal compared to the security risk.
iotclass.org

Major section

Checkpoint: Securing MQTT Sessions · Common Pitfalls

Port 1883 is plaintext; port 8883 adds TLS so credentials, topics, and payloads are not visible to ordinary network observers.

  • Public test brokers are useful for learning only: no authentication, no private topic namespace, and no production control over who can read or publish traffic.
iotclass.org

Major section

Common Pitfall: Misunderstanding MQTT QoS Levels · Try It: QoS Level Selection Advisor

The mistake: MQTT QoS levels (0, 1, 2) are often misunderstood.

  • QoS 0 has no MQTT acknowledgment, QoS 1 transfers a message at least once and can duplicate it, and QoS 2 transfers it exactly once on that MQTT leg.
iotclass.org

Major section

Pitfall: Expecting Clean Session to Queue Messages for Publishers · Pitfall: Using Random Client IDs with Persistent Sessions

The Mistake: Developers configure clean_session=false on publishing devices (sensors), expecting the broker to buffer their outbound messages when the network is down.

  • Neither makes the broker a buffer for publications the offline client has not sent.

Implement local message buffering on the publisher side.

Key terms

Default
Default is infinite, which can consume broker memory if clients use random IDs.

Why it matters

The Mistake: Developers enable persistent sessions (clean_session=false) but use auto-generated or random client IDs like ESP32_ + random() or allow the library to generate one.

iotclass.org

Major section

Checkpoint: Persistent Session Hygiene · Pitfall: QoS Mismatch Between Publisher and Subscriber

Persistent sessions queue messages to offline subscribers; they do not store outbound publications for a sleeping publisher, so publishers still need local buffering.

  • A stable client ID is part of the session contract.
  • They're confused when messages are duplicated or lost at the subscriber despite using QoS 2 for publishing.

Why it matters

During a network glitch, that mismatch can still produce lost or repeated stop events because the subscriber leg has been downgraded.

iotclass.org

Major section

Pitfall: Session Expiry Flooding on Broker Restart · Try It: Exponential Backoff with Jitter Visualizer

The Mistake: Developers deploy hundreds of IoT devices with persistent sessions (clean_session=false) and long keep-alive intervals (300+ seconds).

  • After a broker restart or failover, synchronized client retries can overload recovery with CONNECT packets and queued message delivery.
iotclass.org

Major section

Decision Framework: Clean vs Persistent Session Selection · Interactive Calculators

No session expiry configured (orphaned sessions consume memory forever).

  • Assuming the broker grants the requested subscription QoS, the subscriber leg uses no more than the minimum of publication and granted subscription QoS.
  • The delivery counts below are hypothetical outage outcomes, not predictions from TCP packet loss.

Try it: Decision Framework: Clean vs Persistent Session Selection · Interactive Calculators in the chapter

iotclass.org

Major section

Label the Diagram · Code Challenge · Deep-Dive Note: Session State Boundaries

A persistent session is a broker-side state budget, not a general reliability switch.

  • The useful state is specific: subscriptions, queued QoS 1 or QoS 2 messages for an offline subscriber, and in-flight QoS acknowledgement exchanges that have not finished.

Key terms

QoS 1
QoS 1 is PUBLISH -> PUBACK, so a lost PUBACK can create a duplicate.
QoS 2
QoS 2 is PUBLISH -> PUBREC -> PUBREL -> PUBCOMP, so the broker and client need packet-id state to resume the exchange exactly once after a reconnect.
iotclass.org

Deck summary

Key takeaways

When it reconnects, it needs the right waiting messages, but an old event must not appear as a new opening.

  • A sleeping client may disconnect for ten minutes.
  • Hardware (Simulated):: Work through the two parts: the ESP32 sketch makes QoS 0 publish attempts with local skips, and the separate calculator illustrates QoS 0, 1 and 2 under modeled transfer disruptions.
  • In the chapter's simulator, 20% independently missed MQTT-level transfers over 100 QoS 0 sends gives an expected 80 deliveries and 20 losses; ordinary TCP packet loss would usually be retransmitted.
  • The mistake: MQTT QoS levels (0, 1, 2) are often misunderstood.
iotclass.org

Retrieval practice

Recall check 1 of 5

Broker Bex says: answer from memory, then check your reasoning.

Q1This broker exposes a conventional plaintext MQTT listener on port 1883. Why would using that listener in production be a security risk?

ABecause port 1883 is too slow to carry production MQTT messages.
BBecause port 1883 automatically adds expensive hardware encryption.
CBecause this listener sends MQTT traffic without TLS protection.
DBecause only obsolete brokers support conventional MQTT on 1883.
Show answer

Answer: C Port 1883 transmits data in plain text without encryption, making it vulnerable to eavesdropping and man-in-the-middle attacks.

iotclass.org

Retrieval practice

Recall check 2 of 5

Broker Bex says: answer from memory, then check your reasoning.

Q2What is the purpose of topic-level access control (ACL) in MQTT?

ATo compress MQTT payload bytes before transmission to broker.
BTo limit client publishing or reading by permitted topic pattern.
CTo expire retained messages stored under a matching topic.
DTo encrypt topic names on the wire without a TLS link.
Show answer

Answer: B Topic-level ACLs (Access Control Lists) restrict which clients can publish/subscribe to specific topics.

Q3A publisher uses QoS 2 but the subscriber is granted QoS 0; what is the subscriber-leg QoS?

AQoS remains undefined until TLS starts because transport security determines the subscriber's delivery grant.
BQoS 0 on the subscriber leg because its grant caps delivery.
CQoS 2 on the subscriber leg because the publisher requested it.
DQoS 1 on the subscriber leg as a midpoint of the two settings.
Show answer

Answer: B The broker uses no more than the lower publication and granted subscription QoS.

iotclass.org

Retrieval practice

Recall check 3 of 5

Broker Bex says: answer from memory, then check your reasoning.

Q4A broker has 1,000 offline subscribers, each with 50 queued messages of 140 bytes; about how much payload-plus-overhead memory is queued?

A140,000 bytes, counting only one queued message per client.
B70,000,000 bytes, multiplying the queue count by ten again.
C7,000,000 bytes, about 7 MB for 1,000 × 50 × 140 bytes.
D50,000 bytes, counting queued messages but not their bytes.
Show answer

Answer: C 1,000 × 50 × 140 gives the approximate queue bytes.

iotclass.org

Retrieval practice

Recall check 4 of 5

Broker Bex says: answer from memory, then check your reasoning.

Q5A developer sets clean_session=false on a temperature sensor that publishes QoS 0 data every 30 seconds and never subscribes to any topics. What is the most significant problem with this configuration?

AThe sensor will send duplicate temperature readings
BThe sensor cannot publish at QoS 0 with a persistent session
CThe broker stores unnecessary session state.
DThe sensor will reconnect to the broker more slowly
Show answer

Answer: C Persistent sessions can retain subscriptions, eligible queued messages and in-flight QoS 1/2 exchange state.

iotclass.org

Retrieval practice

Recall check 5 of 5

Broker Bex says: answer from memory, then check your reasoning.

Q6Complete the MQTT v5 client with session expiry and message expiry interval:

Aconnect_props.SessionExpiryInterval = 3600 # 1 hour
Bconnect_props.SessionTimeout = 3600 # 1 hour
Cconnect_props.ExpiryInterval = 3600 # 1 hour
Dconnect_props.session_expiry = 3600 # 1 hour
Show answer

Answer: A MQTT v5 uses SessionExpiryInterval (seconds) to control how long the broker retains session state after disconnect.

iotclass.org

Print reference

Answers 1 of 2

Answer key.

  1. C · Port 1883 transmits data in plain text without encryption, making it vulnerable to eavesdropping and man-in-the-middle attacks.
  2. B · Topic-level ACLs (Access Control Lists) restrict which clients can publish/subscribe to specific topics.
  3. B · The broker uses no more than the lower publication and granted subscription QoS.
  4. C · 1,000 × 50 × 140 gives the approximate queue bytes.
  5. C · Persistent sessions can retain subscriptions, eligible queued messages and in-flight QoS 1/2 exchange state.
iotclass.org

Print reference

Answers 2 of 2

Answer key.

  1. A · MQTT v5 uses SessionExpiryInterval (seconds) to control how long the broker retains session state after disconnect.
iotclass.org