November 11, 2025

MQTT Protocol Tutorial: Getting Started with Publish-Subscribe Messaging for IoT

Blog Details Image

MQTT (Message Queuing Telemetry Transport) is a lightweight messaging protocol designed for IoT applications where bandwidth and power consumption matter. This tutorial covers MQTT fundamentals and demonstrates how to implement MQTT communication using practical tools.

Understanding MQTT is essential for building efficient IoT systems that connect sensors, devices, and cloud platforms.

Where MQTT Fits in the IoT Connectivity Stack

To understand what MQTT does, it helps to see where it sits in the IoT connectivity stack—an adaptation of the OSI networking model created by the Industrial Internet Consortium.

At the bottom layer are physical connections like Ethernet, WiFi, and cellular networks (2G, 3G, 4G). Above this sits the Internet Protocol (IP) layer, followed by transport protocols like TCP and UDP.

MQTT operates on top of the TCP layer, alongside HTTP. Both protocols transport messages as bytes over TCP connections. MQTT specifically handles the transportation of messages over TCP connections without concerning itself with message structure.

Above the transport layer sits the syntactic interoperability layer, which deals with data structure. MQTT sends messages in raw format without structuring the data for interpretation. This is why protocols like OPC UA (an industrial automation standard) use MQTT for transportation while handling data structuring themselves.

Similarly, web services like REST APIs and SOAP use HTTP for transport while managing their own data structures. Other protocols like OneM2M (a telecommunications standard) also operate at this layer.

The topmost layer handles semantic interoperability—the meaning behind the data. Industries create their own standards here, such as OPC UA information modeling for manufacturing or MQTT Sparkplug for describing machines in factory networks.

MQTT vs HTTP: Request-Response vs Publish-Subscribe

MQTT and HTTP use fundamentally different communication patterns. Understanding this difference clarifies why MQTT works better for many IoT scenarios.

How HTTP Request-Response Works

HTTP uses a request-response pattern with clients and servers. When a client needs information from a server, it sends a request, and the server responds.

Consider a Raspberry Pi collecting garage door status information. Using HTTP, the Raspberry Pi must continuously poll the garage door—asking "what is your status?" every few milliseconds. If the owner doesn't arrive for days or weeks, the system keeps polling unnecessarily.

This continuous polling is expensive in two ways:

Data Usage: Each request and response transfers data over the network, even when nothing has changed

Power Consumption: Devices must stay active and use network resources constantly, draining batteries

Tight Coupling Problems with HTTP

The request-response model creates tightly coupled systems. Each device must know about every other device it communicates with.

If your Raspberry Pi communicates with a garage door and you want to add an alarm system from a different manufacturer, you must write a new protocol specifically for that alarm system. Adding a cloud application requires another custom protocol implementation.

This tight coupling means devices need to know communication details about every other participant. Replacing a garage door with a different manufacturer's model requires reprogramming the Raspberry Pi to learn the new communication method.

Static IP Address Requirements

Request-response systems typically require static IP addresses. Each participant needs to know the exact IP address of every other device it communicates with. Losing an IP address breaks communication with all dependent devices.

This is particularly challenging in industrial automation, where different vendors use proprietary protocols. Device A needs specific protocol drivers to communicate with Application A, and different drivers for other devices. There's no efficient way to collect data without depending on manufacturer-provided protocols.

Bandwidth and Scalability Issues

Request-response patterns don't scale well. If reading sensor information takes 100 milliseconds per device, reading five devices takes 500 milliseconds. In factories with thousands of devices, this time sharing makes the network impractical.

This becomes dangerous in industrial settings where time-critical monitoring matters. If a motor must be monitored continuously for safety, but polling 1,000 other devices takes seconds, dangerous situations can develop before the next poll cycle detects them.

How MQTT Publish-Subscribe Works

MQTT uses a publish-subscribe pattern that solves many request-response problems. Instead of direct client-server communication, both participants become clients that communicate through a third party called a broker.

When garage door status changes, the information is sent to the broker. The Raspberry Pi receives updates from the broker rather than polling the door. This is called "report by exception"—data is only sent when something changes.

The client sending information is the publisher. The client receiving information is the subscriber. The Raspberry Pi only receives notifications when the garage door status actually changes—from open to closed or vice versa.

MQTT Decoupling Benefits

MQTT decouples devices in space, time, and synchronization:

Space Decoupling: Publishers and subscribers don't need to know each other's IP addresses or locations. They only need to know the broker address.

Time Decoupling: Publishers and subscribers don't need to be online simultaneously. The broker can store messages for offline subscribers.

Synchronization Decoupling: Publishing and subscribing happen asynchronously. Publishers don't wait for subscriber acknowledgments before continuing operations.

MQTT Topics

MQTT organizes messages using topics—hierarchical strings that categorize information. Topics use forward slashes as separators, like file paths.

For example:

  • factory/line1/temperature
  • factory/line1/pressure
  • factory/line2/temperature

Subscribers can use wildcards to subscribe to multiple related topics:

  • Single-level wildcard +: factory/+/temperature subscribes to temperature from all production lines
  • Multi-level wildcard #: factory/# subscribes to all data from the factory

MQTT Quality of Service Levels

MQTT defines three Quality of Service (QoS) levels that determine message delivery guarantees:

QoS 0 (At most once): Messages are delivered once without confirmation. This is fastest but least reliable—some messages may not arrive.

QoS 1 (At least once): Messages are guaranteed to arrive but may be delivered multiple times. The broker confirms receipt and retransmits if no acknowledgment is received.

QoS 2 (Exactly once): Messages are guaranteed to arrive exactly once through a four-step handshake process. This is most reliable but slowest.

Choose QoS levels based on your application requirements. Temperature monitoring might use QoS 0 for speed, while financial transactions would use QoS 2 for reliability.

Retained Messages

MQTT brokers can retain the last message published to a topic. When new subscribers connect, they immediately receive the last known value rather than waiting for the next update.

This is useful for status information. A new device connecting to monitor garage door status immediately receives the current state instead of waiting for the next change event.

Practical MQTT Implementation with Node-RED

Setting up MQTT communication involves three components: a broker, a publisher, and a subscriber.

Installing an MQTT Broker

The MQTT broker manages message routing between publishers and subscribers. Mosquitto is a popular open-source MQTT broker. Install it on a server or local computer that will act as the central message hub.

After installation, the broker runs as a service listening for connections from MQTT clients.

Creating a Publisher with Node-RED

Node-RED provides a visual programming interface for creating MQTT publishers. In this example, we'll publish temperature sensor data.

Add an inject node configured to trigger every 5 seconds—this simulates regular sensor readings. Connect it to a function node that reads temperature data from a sensor (in this case, a temperature value is generated or read from hardware).

Add an MQTT output node and configure it with:

Server: The IP address of your MQTT brokerPort: 1883 (standard unencrypted MQTT port)Topic: A descriptive topic like demo/temperatureKeep Alive: 60 seconds (maintains connection)

Deploy the flow. Node-RED now publishes temperature readings to the broker every 5 seconds under the specified topic.

Testing with an MQTT Client

Use MQTT.fx or another MQTT client application to verify messages are being published correctly. Connect to the same broker by entering its IP address and port.

Subscribe to the topic demo/temperature. You should see messages arriving every 5 seconds showing the temperature values. Apply heat to the temperature sensor and watch the values increase in real-time in the MQTT client.

This demonstrates the complete MQTT workflow: a publisher sends data to the broker when readings change, and any subscriber interested in that topic receives the updates automatically.

MQTT Use Cases and Applications

MQTT excels in scenarios where:

  • Battery-powered devices need efficient communication
  • Network bandwidth is limited or expensive
  • Devices connect intermittently
  • Multiple applications need access to the same sensor data
  • Scalability to thousands of devices is required
  • Time-critical monitoring doesn't need continuous polling

Common applications include smart home automation, industrial sensor networks, vehicle tracking systems, and mobile push notifications.

Summary

MQTT provides an efficient alternative to HTTP request-response patterns for IoT communication. By using a publish-subscribe model with a central broker, MQTT decouples devices, reduces bandwidth usage, and scales to thousands of endpoints.

Key concepts include topics for organizing messages, Quality of Service levels for delivery guarantees, and retained messages for immediate state information. Setting up MQTT requires a broker like Mosquitto and clients that publish or subscribe to topics of interest.

Understanding these fundamentals enables you to build efficient, scalable IoT systems that communicate reliably while conserving power and bandwidth.