15  MQTT Publish-Subscribe Basics

In 60 Seconds

MQTT’s publish-subscribe pattern decouples message senders (publishers) from receivers (subscribers) through a central broker, eliminating the need for devices to know about each other directly. Publishers send messages to hierarchical topics (e.g., building/floor1/temperature), and subscribers use exact topics or wildcards (+ for single level, # for multi-level) to receive relevant messages – making MQTT far more scalable than polling-based HTTP for millions of IoT devices.

15.1 Learning Objectives

By the end of this chapter, you will be able to:

  • Explain the Publish-Subscribe Pattern: Describe how MQTT decouples message producers from consumers through a central broker
  • Design Topic Hierarchies: Construct efficient, scalable topic naming conventions for IoT deployments
  • Distinguish Wildcard Types: Compare + (single-level) and # (multi-level) wildcards and select the appropriate one for a given subscription requirement
  • Apply Retained Messages and LWT: Implement retained messages and Last Will and Testament to solve real IoT state-management problems
  • Calculate Broker Load: Assess throughput and memory requirements for an MQTT deployment given device count and publish rates
  • MQTT: Message Queuing Telemetry Transport — pub/sub protocol optimized for constrained IoT devices over unreliable networks
  • Broker: Central server routing messages from publishers to all matching subscribers by topic pattern
  • Topic: Hierarchical string (e.g., home/bedroom/temperature) used to route messages to interested subscribers
  • QoS Level: Quality of Service 0/1/2 trading delivery guarantee for message overhead
  • Retained Message: Last message on a topic stored by broker for immediate delivery to new subscribers
  • Last Will and Testament: Pre-configured message published by broker when a client disconnects ungracefully
  • Persistent Session: Broker stores subscriptions and pending messages allowing clients to resume after disconnection

15.2 For Beginners: MQTT Publish-Subscribe

Publish-subscribe is a messaging pattern where senders (publishers) and receivers (subscribers) do not communicate directly. Instead, a broker handles all the routing. Think of it like a bulletin board: anyone can post a notice, and anyone interested can read it, without the poster needing to know who will read it.

15.3 Prerequisites

Before diving into this chapter, you should be familiar with:

The Challenge: Scalable Device Communication

The Problem: Traditional request-response patterns (like HTTP polling) don’t scale for IoT. With millions of devices, each polling a server creates:

  • N devices x M polls/hour = billions of wasted requests - Most polls return “no new data”
  • Servers must track every device connection - Memory and connection limits quickly exceeded
  • Devices waste energy checking for messages that aren’t there - Critical for battery-powered sensors

The Solution: Publish-Subscribe messaging with a central broker. MQTT was designed from the ground up for exactly these IoT constraints, providing lightweight, reliable, and scalable communication.

Key Takeaway

MQTT is the publish-subscribe protocol that lets IoT devices communicate through a central broker instead of directly with each other. By decoupling senders (publishers) from receivers (subscribers), MQTT enables millions of devices to exchange messages efficiently.

Common Pitfalls

Unencrypted MQTT exposes device credentials and sensor data to network eavesdroppers — in a building IoT deployment on shared WiFi, this means any connected device can read all sensor data. Always enable TLS 1.2+ on the broker and generate unique client certificates for each device class.

Without LWT, there is no automatic notification when a device disconnects ungracefully — missed timeout alarms and false-healthy device status are common consequences. Configure LWT on every device connection to publish an offline status message, enabling real-time fleet health monitoring.

A single MQTT connection serializes all publishes through one TCP socket — at 100 messages/second with QoS 1, TCP backpressure creates queuing latency. Use multiple parallel MQTT connections or partition topics across connection pools for throughput above 1,000 messages/second.

15.4 What is MQTT?

What is MQTT? (Simple Explanation)

Analogy: MQTT is like a newspaper subscription service.

Instead of checking websites for updates constantly, you subscribe to topics you care about, and news gets delivered to you automatically.

TRADITIONAL vs MQTT:

HTTP vs MQTT comparison
Figure 15.1: Architecture comparison: HTTP polling versus MQTT publish-subscribe
Definition

MQTT (Message Queue Telemetry Transport) is a lightweight, publish-subscribe messaging protocol designed for constrained devices and low-bandwidth, high-latency networks. It’s the de facto standard for IoT communication.

Key Characteristics:

  • Lightweight: Minimal packet overhead (2 bytes minimum)
  • Publish-Subscribe Pattern: Decouples message producers from consumers
  • Quality of Service: Three levels (QoS 0, 1, 2) for reliability
  • Retained Messages: Latest message stored for new subscribers
  • Last Will and Testament: Notifies when clients disconnect unexpectedly

15.5 The Three Key Players

MQTT has three main components:

Component Role Analogy
Publisher Sends messages Newspaper writer
Broker Routes messages Post office
Subscriber Receives messages Newspaper subscriber

HOW MQTT WORKS:

MQTT message flow
Figure 15.2: Sequence diagram illustrating MQTT communication flow
Key Insight: The Broker Decouples Publishers from Subscribers
Broker routing messages
Figure 15.3: MQTT broker routing sensor messages to multiple consumers

In Plain English: Publishers don’t know (or care) who receives their messages. Subscribers don’t know who sends. The broker handles all the routing. This means you can add new sensors or new consumers without changing any existing code.

Minimum Viable Understanding: Publish-Subscribe Pattern

Core Concept: Publishers send messages to named topics without knowing who receives them; subscribers listen to topics without knowing who sends, with a broker routing all messages in between. Why It Matters: This decoupling enables IoT systems to scale from 10 to 10 million devices without changing code - add new sensors or dashboards anytime without modifying existing components. Key Takeaway: Design your topic hierarchy first (e.g., building/floor/room/sensor_type), then build publishers and subscribers independently - the broker handles all discovery and routing.

15.6 Topics: Organizing Messages

MQTT uses topics to organize messages - like folders for emails:

Topic What It Means Example Message
home/living/temp Living room temperature "25.5"
home/bedroom/light Bedroom light status "on"
factory/machine1/status Machine 1 status "running"

Each topic subscription consumes broker memory for storing the topic string and subscriber list. Topic hierarchy depth affects broker efficiency:

Memory per subscription (typical MQTT broker): $ M_{} = M_{} + M_{} + M_{} $

Where: - \(M_{\text{topic}}\): Topic string storage (~40-100 bytes depending on length) - \(M_{\text{sublist}}\): Subscriber list pointer (~8 bytes per subscriber) - \(M_{\text{routing}}\): Routing index overhead (~20 bytes for tree traversal)

Flat vs hierarchical topics:

  • Flat: buildingA_floor1_room101_temp (29 bytes) → one hash lookup
  • Hierarchical: building/A/floor/1/room/101/temp (32 bytes) → 7 tree levels

Broker scaling example (1M subscriptions): For 1 million active subscriptions to unique topics: $ M_{} = 1,000,000 (60 + 8 + 20) $

Wildcard efficiency: 10,000 subscribers to building/+/floor/+/temp share one topic tree path vs 10,000 unique paths: - Wildcard: 1 × 88 bytes + 10,000 × 8 bytes ≈ 80 KB - Unique topics: 10,000 × 88 bytes ≈ 880 KB (11× more memory)

Hierarchy enables efficient wildcard subscriptions, reducing broker memory by 10-100× for common subscription patterns.

Wildcards make subscribing powerful:

  • home/+/temp = “All room temperatures” (+ = any one level)
  • home/# = “Everything in home” (# = all levels below)
Topic wildcard patterns
Figure 15.4: Hierarchical topic structure showing wildcard matching

15.6.1 Wildcard Reference

Wildcard Meaning Example Matches
+ Single level home/+/temperature home/bedroom/temperature, home/kitchen/temperature
# Multiple levels home/# home/bedroom/temperature, home/bedroom/humidity, home/kitchen/motion/sensor1

Pitfall: Using Leading Slashes in Topic Names

The Mistake: Developers create topics with leading slashes like /home/temperature or mix conventions, using /home/temp in publishers and home/temp in subscribers.

Why It Happens: Leading slashes look natural from filesystem experience (Unix paths start with /). MQTT does not strip or normalize slashes, so /home/temp and home/temp are completely different topics.

The Fix: Never use leading slashes. Adopt a consistent topic naming convention across your organization.

// WRONG - leading slash creates unexpected first level
mqttClient.publish("/home/temperature", "24.5");  // Topic has 3 levels: "", "home", "temperature"
mqttClient.subscribe("home/temperature");         // 2 levels: "home", "temperature"
// Result: Subscriber never receives message!

// CORRECT - consistent naming without leading slash
mqttClient.publish("home/temperature", "24.5");   // 2 levels: "home", "temperature"
mqttClient.subscribe("home/temperature");         // Matches!

15.7 Interactive: MQTT Pub/Sub Simulator

Try this hands-on simulator to see MQTT messaging in action. Publish messages to topics and watch how the broker routes them to matching subscribers.

Publisher

Quick Examples:
home/living/temp
home/bedroom/light

MQTT Broker

Status: Ready
Waiting for messages...

Subscribers

Wildcard Examples:
home/+/temp (all room temps)
home/# (everything in home)

Message Log

How to Use This Simulator:

  1. Add Subscribers (already includes 2 examples):
    • Enter a topic pattern (e.g., home/+/temp for all room temperatures)
    • Click “Add Subscriber”
  2. Publish Messages:
    • Enter a specific topic (e.g., home/living/temp)
    • Enter a message payload (e.g., 24.5)
    • Click “Publish Message”
  3. Watch the Flow: See the broker route messages to matching subscribers

15.8 Retained Messages

Analogy: Retained messages are like leaving the last known value on a whiteboard.

Without retained messages:

10:00 AM - Sensor publishes: "Temperature: 24C"
10:30 AM - Phone app starts up and subscribes
           App sees nothing (missed the 10:00 message!)
10:35 AM - Sensor publishes again: "Temperature: 25C"
           App finally gets first reading

With retained messages:

10:00 AM - Sensor publishes with RETAIN flag: "Temperature: 24C"
           Broker saves this as "latest known value"
10:30 AM - Phone app starts up and subscribes
           Broker immediately sends: "Temperature: 24C" (retained)
           App shows data instantly!

When to use retained messages:

  • Device status (“online” / “offline”)
  • Configuration settings (“mode: heating”)
  • Last known sensor value (“temperature: 24C”)

When NOT to use retained messages:

  • Streaming data (don’t need every single reading)
  • Alerts/events (only care about new ones)

15.9 Last Will and Testament (LWT)

Analogy: LWT is like leaving a sealed letter that only gets opened if you disappear.

The Problem:

Sensor is publishing: "I'm alive! Temperature: 24C"
Network cable gets unplugged...
Sensor is offline, but subscribers don't know!
Dashboard still shows "24C" from 10 minutes ago

The Solution with LWT:

Sensor connects to broker and says:
"If I disconnect unexpectedly, publish this message for me:
  Topic: home/bedroom/status
  Message: OFFLINE"

Normal operation: Sensor publishes normally
Network failure happens...
Broker detects sensor is gone -> publishes LWT automatically
Dashboard receives: "home/bedroom/status: OFFLINE"

Real code:

// ESP32 setting up Last Will and Testament
mqttClient.setWill("home/sensor1/status", "OFFLINE");  // LWT message

mqttClient.connect();  // Connect to broker

// Periodically publish normal status
mqttClient.publish("home/sensor1/status", "ONLINE");

// If ESP32 crashes or loses Wi-Fi, broker automatically publishes:
// Topic: "home/sensor1/status"
// Message: "OFFLINE"

15.10 For Kids: Meet the Sensor Squad!

MQTT is like a magical bulletin board where friends can post notes and everyone who cares about that topic gets a copy automatically!

One day, the Sensor Squad discovered a problem in their smart treehouse. Thermo the temperature sensor wanted to tell everyone when it got too hot, Lumi the light sensor needed to announce when it got dark, Speedy the motion detector wanted to alert everyone about visitors, and Droplet the humidity sensor had to warn about rain coming. But with everyone shouting messages at the same time, nobody could hear anything!

Then wise old Broker Bear arrived with a magical bulletin board. “Instead of shouting,” Broker Bear explained, “you can publish your messages to different sections of my board. Thermo, you post to the ‘temperature’ section. Lumi, you use the ‘light’ section.”

The Sensor Squad loved this idea! Broker Bear continued, “And here’s the magic part - anyone who wants to know about temperature can subscribe to that section. Whenever Thermo posts a new message, my magic board automatically sends a copy to everyone who subscribed!”

15.10.1 Key Words for Kids

Word What It Means
Publish Posting a message to the bulletin board
Subscribe Signing up to receive messages from a topic
Broker The helpful friend who runs the bulletin board
Topic A labeled section on the board

15.10.2 Try This at Home!

Create your own family message board! Get a cork board and divide it into sections like “Kitchen,” “Living Room,” and “Bedrooms.” Family members can post sticky notes to sections, and anyone interested checks for new messages. This is exactly how MQTT works in smart homes!

15.11 Worked Example: Designing a Topic Hierarchy for a Smart Building

Worked Example: MQTT Topic Architecture for a 5-Floor Office Building

Scenario: A facilities management company deploys 200 IoT devices across a 5-floor office building: 100 temperature/humidity sensors, 50 occupancy sensors, 30 smart light controllers, and 20 HVAC actuators. They need to support three subscriber types: a real-time dashboard, a historical database, and an alerting system.

Requirements:

  • Group messages by floor, room, and device type
  • Dashboard needs all sensor data building-wide
  • HVAC controller on each floor only needs that floor’s temperature data
  • Alerting system only needs threshold violations, not routine readings

Step 1: Define the topic hierarchy

building/{building_id}/floor/{floor}/room/{room}/{device_type}/{device_id}/{measurement}

Concrete examples:

Device Topic Sample Payload
Temp sensor, Floor 3, Room 301 building/hq/floor/3/room/301/temp/T301a/reading {"value":22.5,"unit":"C"}
Occupancy sensor, Floor 1, Lobby building/hq/floor/1/room/lobby/occupancy/O1a/count {"count":12}
Light controller, Floor 2, Room 205 building/hq/floor/2/room/205/light/L205a/status {"state":"on","brightness":80}
Alert from any device building/hq/alerts/{severity} {"device":"T301a","msg":"temp>30C"}

Step 2: Map subscribers to wildcard patterns

Subscriber Topic Subscription What They Receive Messages/min
Dashboard building/hq/floor/+/room/+/temp/+/reading All temperature readings ~33
Database building/hq/# Everything ~80
Floor 3 HVAC building/hq/floor/3/room/+/temp/+/reading Only Floor 3 temps ~7
Alert system building/hq/alerts/# Only alerts ~0.5

Step 3: Calculate broker throughput

Metric Value
Total devices 200
Average report interval 3 minutes
Messages per hour ~4,000
Broker fan-out factor 2.8x (each message goes to ~2.8 subscribers)
Broker deliveries per hour ~11,200
Average message size 120 bytes
Broker bandwidth ~1.3 MB/hour

A single Mosquitto broker on modest hardware can manage this with 99.99% headroom. The key design insight is that deeper topic hierarchies enable more precise wildcard filtering, reducing unnecessary message delivery.

Common mistake: Flat topics like temp_floor3_room301 prevent wildcard filtering entirely. Every subscriber must subscribe to every individual topic name.

Connection: MQTT QoS meets LoRaWAN Confirmed Messages

MQTT QoS levels and LoRaWAN confirmed/unconfirmed messages solve the same problem – reliability over unreliable links – at different layers. MQTT QoS 0 (fire-and-forget) mirrors LoRaWAN unconfirmed uplinks: suitable for periodic data where the next reading replaces a lost one. MQTT QoS 1 (at-least-once with PUBACK) mirrors LoRaWAN confirmed uplinks: the receiver acknowledges, and the sender retransmits if no ACK arrives. A sensor using both gets double reliability – LoRa ensures the message reaches the gateway, MQTT ensures the gateway delivers it to subscribers. See MQTT Quality of Service for QoS details.

15.12 Interactive Calculators

15.12.1 MQTT Message Throughput Calculator

Calculate the total message throughput and bandwidth requirements for your MQTT deployment.

15.12.2 Topic Hierarchy Memory Calculator

Compare memory usage between flat topics and hierarchical topics with wildcards.

15.12.3 Broker Load Calculator

Estimate broker message delivery load based on publisher and subscriber counts.

15.12.4 Retained Message Storage Calculator

Estimate storage requirements for retained messages across topics.

15.12.5 Wildcard Subscription Efficiency Calculator

Compare individual topic subscriptions vs wildcard patterns.

15.13 What’s Next

Now that you can explain the publish-subscribe pattern and design topic hierarchies, the chapters below build directly on these foundations:

Chapter Focus Why Read It
MQTT Quality of Service QoS 0, 1, and 2 delivery guarantees Understand how MQTT ensures messages arrive reliably over lossy networks — the direct complement to pub-sub decoupling
MQTT Connection and Sessions CONNECT packet, persistent sessions, clean sessions Learn how the broker tracks subscriptions across disconnections, which affects retained-message and LWT behaviour you studied here
MQTT Labs and Implementation ESP32 and Python MQTT clients Apply topic hierarchy design and wildcard subscriptions in working code with real broker deployments
CoAP Fundamentals REST-style request-response for IoT Compare MQTT’s push-based pub-sub against CoAP’s pull-based model to select the right protocol for each use case
Protocol Integration Patterns Bridging MQTT with HTTP, CoAP, and AMQP Discover how pub-sub systems are integrated into wider enterprise architectures beyond the broker