The Standard for IoT Messaging

Master the MQTT protocol. Lightweight, efficient, and reliable messaging for the Internet of Things. Built for unstable networks and low-bandwidth environments.

Launch Simulator

What is MQTT?

MQTT (Message Queuing Telemetry Transport) is an OASIS standard messaging protocol for the Internet of Things (IoT). It is designed as an extremely lightweight publish/subscribe messaging transport that is ideal for connecting remote devices with a small code footprint and minimal network bandwidth.

Initially developed by IBM in 1999 to monitor oil pipelines over satellite connections, it has now become the de-facto standard for IoT due to its efficiency and reliability over unstable networks.

Why is it so popular?

  • Lightweight: Smallest packet size is just 2 bytes, reducing network overhead.
  • 🛡️ Reliable: Offers 3 levels of Quality of Service (QoS) to ensure delivery.
  • 🔄 Bi-directional: Allows messaging between device-to-cloud and cloud-to-device.
  • 💾 Persistent: Retained messages allow new devices to immediately get the last known state.

Comparison: MQTT vs HTTP

While HTTP is the web standard, it is heavy and document-centric. MQTT is data-centric.

Feature MQTT HTTP
Design Model Pub/Sub Request/Response
Header Size Min 2 Bytes Large (Text based)
Connection Keep-Alive Open/Close
Battery Usage Very Low High
Distribution 1-to-Many 1-to-1

Architecture & Components

The MQTT protocol decouples the sender (publisher) and the receiver (subscriber) via a central component called the Broker.

The Broker

The heart of the system. It receives all messages, filters them, decides who is interested in them based on subscriptions, and then publishes the message to all subscribed clients. Popular brokers include Mosquitto, HiveMQ, and EMQX.

Publisher

A client that sends data (messages) to the broker on a specific topic. For example, a temperature sensor publishing data to home/livingroom/temp. Publishers do not need to know who subscribers are.

Subscriber

A client that registers interest in a specific topic. When the broker receives a message on that topic, it forwards it to the subscriber. A client can be both a publisher and subscriber.

Understanding Topics

MQTT topics are hierarchical strings used to filter messages. They use a forward slash / as a delimiter. They are case-sensitive.

Topic Structure

A typical topic looks like this:

myhome / groundfloor / kitchen / temp

This hierarchy allows specific addressing of devices.

Topic Wildcards

  • Single Level (+):
    home/+/temp matches home/kitchen/temp but not home/kitchen/fridge/temp.
  • Multi Level (#):
    home/# matches everything starting with home, e.g., home/kitchen/temp and home/garage/light/status. This must be the last character in the topic.

Web MQTT Simulator

Experience how MQTT works right here in your browser. This simulator mimics the behavior of a broker and client locally using JavaScript logic.

Disconnected
Protocol: Virtual MQTT
Broker: mqtt.mqttwebs.com (Simulated)

1. Connection & Subscription


Active Subscriptions:
  • Not connected

2. Publish Message

[System] Simulator initialized. Ready to connect.

Quality of Service (QoS)

MQTT provides three specific qualities of service for message delivery. This allows the designer to choose the right balance between overhead and reliability for specific messages.

0

QoS 0

At most once

Also known as "Fire and forget". The message is sent once. No confirmation is expected. If the connection drops or the server is busy, the message is lost forever.

Use case: Periodic temperature sensor data where missing one reading out of a hundred isn't critical.

1

QoS 1

At least once

Guarantees that a message will be delivered at least once to the receiver. The sender stores the message until it gets a PUBACK packet. Duplicates may occur if the ack is lost.

Use case: Turning on a light switch. You definitely want it to turn on, and doing it twice is acceptable.

2

QoS 2

Exactly once

The safest and slowest level. Guarantees that the message is received exactly once by using a four-step handshake. This prevents duplicates.

Use case: Banking transactions, billing systems, or critical alarms where duplicates cause errors.

Implementation Examples

MQTT has client libraries available for almost every programming language (C, C++, Java, Python, Go, JavaScript, etc.).

Python (Paho-MQTT)

The standard library for Python IoT apps.

import paho.mqtt.client as mqtt

# Callback when connected
def on_connect(client, userdata, flags, rc):
    print(f"Connected with result code {rc}")
    # Subscribing in on_connect ensures 
    # we resubscribe if we lose connection
    client.subscribe("home/sensors/#")

# Callback when message received
def on_message(client, userdata, msg):
    print(f"{msg.topic}: {msg.payload.decode()}")

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("broker.hivemq.com", 1883, 60)
client.loop_forever()

JavaScript (Node.js)

Using the MQTT.js library for async operations.

const mqtt = require('mqtt')
// Connect to a public test broker
const client  = mqtt.connect('mqtt://test.mosquitto.org')

client.on('connect', function () {
  console.log("Connected!")
  
  // Subscribe to presence topic
  client.subscribe('presence', function (err) {
    if (!err) {
      // Publish a message
      client.publish('presence', 'Hello mqtt')
    }
  })
})

client.on('message', function (topic, message) {
  // message is a Buffer
  console.log(message.toString())
  client.end() // Close connection
})

Frequently Asked Questions

By default, MQTT sends data in plain text, which is not secure. However, production implementations typically use TLS/SSL to encrypt the connection (MQTTS), typically on port 8883. Additionally, username/password authentication and Client Certificates can be used to authorize devices at the broker level.

A retained message is a normal MQTT message with the "retained" flag set to true. The broker stores the last retained message for that topic. When a new client subscribes to that topic, it immediately receives the retained message. It's useful for "status" updates (e.g., providing the last known temperature to a device that just woke up).

LWT is a feature where a client specifies a message to be published by the broker automatically if the client disconnects ungracefully (e.g., battery dies, network failure). It allows other clients to know that a device has gone offline unexpectedly.

Standard MQTT uses TCP port 1883. MQTT over SSL/TLS uses port 8883. MQTT over WebSockets usually uses port 80 or 443 (if secure), or custom ports like 9001 depending on the broker configuration.

When a client connects with "Clean Session = false", the broker creates a persistent session. It saves all subscriptions and queues QoS 1 and 2 messages for the client while it is offline. When the client reconnects, it receives all missed messages.