Blog

How to Test and Debug MQTT: A Practical Guide for IoT Engineers

· Sərvin Əliyev

How to test and debug MQTT: MQTT 360 broker delivering sensor, line state and meter topics

MQTT fails quietly. A device publishes, the broker accepts, and the dashboard shows nothing. There is no error on either side, because in MQTT nobody is waiting for an answer: the publisher does not know whether anyone is subscribed, and the subscriber does not know whether anyone is publishing.

That is what makes MQTT scale so well, and also what makes it hard to debug. This guide shows how to test an MQTT system step by step: how topics, wildcards, QoS and retained messages really behave, how to read connection errors, and how to find out where a message got lost. The examples use MQTT 360, our desktop MQTT workspace with a built-in broker, but the method works with any client and broker.

MQTT in two minutes

MQTT is a publish/subscribe protocol. Clients never talk to each other directly. Every client opens one connection to a broker; publishers send messages to a topic, and the broker delivers each message to every client subscribed to a matching topic.

MQTT publish and subscribe through a broker, with + and # wildcard matching examples

A few facts you will use constantly:

  • The standard ports are 1883 for plain TCP and 8883 for MQTT over TLS. MQTT over WebSocket has no single standard port or path; brokers often use 8083/8084 or 80/443 with a path such as /mqtt.
  • Topics are UTF-8 strings split into levels by /, for example factory/line1/temperature. They are case-sensitive, and factory/line1 is not the same topic as /factory/line1: the leading slash creates an empty first level.
  • MQTT 3.1.1 is still the most widely deployed version. MQTT 5 adds reason codes, user properties, message expiry, shared subscriptions and better session control.

Topics and wildcards

Subscribers can use two wildcards:

WildcardMeaningExampleMatchesDoes not match
+Exactly one levelfactory/+/temperaturefactory/line1/temperaturefactory/line1/oven/temperature
#This level and everything below; must be lastfactory/#factory/line1/pressure, factoryoffice/room1/temperature

Wildcards work only in subscriptions, never in the topic you publish to. Topics that start with $, such as the broker statistics under $SYS/, are not matched by a subscription to #; subscribe to them explicitly.

Subscribing to # is the fastest way to see what is happening on a test broker. On a busy production broker it can flood your client and add load to the broker, so narrow the filter there: site1/# instead of #.

QoS, retained messages and sessions

Most "MQTT lost my message" reports come down to four settings.

QoS: delivery guarantee per hop

MQTT QoS 0, 1 and 2 message flows between client and broker

  • QoS 0, at most once: fire and forget. If the connection drops at the wrong moment, the message is gone.
  • QoS 1, at least once: the sender repeats the message until it receives PUBACK. The receiver may get duplicates, so the application must tolerate them.
  • QoS 2, exactly once: a four-step handshake (PUBLISH, PUBREC, PUBREL, PUBCOMP). The slowest level, used when a duplicate would cause harm, such as counting a payment twice.

QoS applies to each hop separately: publisher to broker, and broker to subscriber. A subscriber receives a message at the lower of the publish QoS and its own subscription QoS. Publishing at QoS 2 does not help if the subscriber subscribed at QoS 0.

Retained messages: the last known value

When a message is published with the retain flag, the broker keeps it and sends it immediately to every new subscriber of that topic. This is how a dashboard that opens at 09:00 shows the temperature published at 08:55.

Retained messages also cause a classic confusion: a value that "keeps coming back" after the device is gone. That is the retained message. To delete it, publish an empty payload with the retain flag to the same topic.

Sessions: what happens while a client is offline

With a clean session (MQTT 3.1.1 cleanSession = true, MQTT 5 cleanStart = true with a session expiry of 0), the broker forgets the client when it disconnects. With a persistent session, the broker keeps the client's subscriptions and queues QoS 1 and QoS 2 messages until the client returns. If messages sent while a device was offline never arrive, check these two things first: the session type and the QoS.

Last will: knowing that a device is gone

A client can register a last will message when it connects. If the connection breaks without a proper disconnect, the broker publishes that message for it. A common pattern is a retained devices/42/status topic: the device publishes online after connecting and sets offline as its last will.

The broker notices a dead connection through the keep alive interval. If it hears nothing from a client for one and a half times that interval, it closes the connection and publishes the last will.

What you need before you start

  1. The broker address, port and transport: TCP, TLS or WebSocket (with its path).
  2. Credentials: username and password, or a client certificate. For TLS, the CA certificate the broker's certificate was issued by.
  3. A client ID that no other client uses. If two clients connect with the same ID, the broker disconnects the older one; two of them will keep kicking each other off.
  4. The topic structure and the payload format (JSON, plain text or binary) the devices use.

Step by step: testing an MQTT system

1. Start with a local broker

Before touching the production broker, test against one you control. It removes the network, the firewall and access rules from the equation. MQTT 360 starts an embedded local broker with one click, so you can point a device or a script at your laptop and see every message, even on a site without internet access.

2. Connect and read the CONNACK

Create a connection profile with the broker address, transport and credentials. MQTT 360 stores profiles with the credentials in secure storage, and you can export and import them to share a setup with your team.

If the connection fails, the broker's answer tells you why:

CONNACK (MQTT 3.1.1)MQTT 5 reason codeMeaningWhat to check
10x84 Unsupported Protocol VersionThe broker does not accept this MQTT versionSwitch between 3.1.1 and 5
20x85 Client Identifier not validThe client ID is rejectedUse a different or shorter client ID
30x88 Server unavailableThe broker cannot serve the connectionBroker status and logs
40x86 Bad User Name or PasswordWrong credentialsUsername, password, typos, expired token
50x87 Not authorizedThe account may not connectBroker access rules for this user or client ID

No CONNACK at all usually means the problem is below MQTT: wrong host or port, a firewall, plain TCP to a TLS port, or a TLS handshake that failed because the CA certificate or the host name does not match.

3. Subscribe wide, then narrow

Subscribe to # on the test broker, or to the device's root topic such as site1/# on a shared one. Watch the topic tree fill up: it shows you the real topic names, which often differ from the documentation by a letter, a case or a slash. MQTT 360 shows the live topic tree with a message inspector that displays the payload as text, JSON or hex, which is what you need when a device sends binary data.

4. Publish a test message

Publish to the exact topic a device listens on, with the QoS and retain flag you expect in production. MQTT 360's publisher keeps reusable templates and a history, so repeating a command on site takes one click. Check that the message arrives in your own subscription first; then check the device.

5. Check retained messages and last will

Reconnect your client and see what arrives immediately: those are retained messages. Unplug a device's network cable and wait for its last will to appear. Both tests take a minute and catch most "stale value" and "device looks online but is not" problems.

6. Record a session

Intermittent problems are the hardest: a value that jumps once an hour, a device that disconnects at night. Recording solves them. MQTT 360 records sessions to a local SQLite database, so you can leave it running, then search and export the messages afterwards and see exactly what was published and when.

7. Build a quick dashboard and alarms

Once the data is correct, a dashboard is the fastest way to show it to the people on site. MQTT 360 builds dashboards from topic-driven widgets: charts, gauges, numeric displays, LEDs, switches and buttons. Switches and buttons publish back to the broker, so the same dashboard is also a control panel. Alarms on values and device availability raise a desktop notification when something drifts.

Common MQTT problems and how to fix them

SymptomMost likely causeWhat to check
Connection refusedWrong credentials, access rules, protocol versionRead the CONNACK or reason code (table above)
Connection times outWrong host or port, firewall, TLS port with plain TCPTest the port; check TLS settings and the CA certificate
Clients disconnect each otherTwo clients share the same client IDGive every client a unique ID
Messages never arriveTopic typo, case difference, leading slash, access rules on the topicSubscribe to # and compare the real topic names
An old value keeps coming backRetained message on the topicPublish an empty retained payload to clear it
Messages lost while a device was offlineQoS 0, or a clean sessionUse QoS 1 and a persistent session
Duplicate messagesQoS 1 redeliveryMake the consumer idempotent, or use QoS 2 where it matters
Disconnects every few minutesKeep alive too long for a NAT or firewall timeoutShorten the keep alive interval
Payload looks like garbageBinary or compressed payload, wrong encodingView it as hex; check the device's payload format
WebSocket connection failsWrong port or pathCheck the broker's WebSocket port and path, such as /mqtt

Testing without the real devices

Devices are often the last thing to arrive, while the backend and dashboards must be ready first. With a local broker and a publisher you can stand in for any device: publish the same topics and payloads it will send, with the same QoS and retain flags, and develop against that.

The same setup works in the other direction. MQTT 360's edge gateway bridges topics between a local broker and a remote one, in both directions, and buffers messages while the remote side is unreachable. That lets you test how your system behaves when a site loses its uplink, before it happens for real.

MQTT and Modbus

MQTT rarely talks to field devices directly. On an industrial site, a gateway or PLC usually reads meters and drives over Modbus and publishes the values to MQTT. When a value is wrong on the dashboard, the problem can be on either side: check the MQTT topic first, and if the payload already arrives wrong, look at the Modbus side. Our guide on how to test a Modbus device covers that half, and Modbus 360 is the companion tool for it.

A short checklist

  • Test against a local broker first, then the real one.
  • Give every client a unique client ID.
  • Read the CONNACK or reason code when a connection fails.
  • Subscribe to # (or the site root) and compare real topic names with the documentation.
  • Check case, leading slashes and access rules when messages do not arrive.
  • Use QoS 1 and persistent sessions for data you cannot lose.
  • Clear stale retained messages with an empty retained payload.
  • Use a last will for device availability.
  • Record the session when the problem is intermittent.

Frequently asked questions

What are the default MQTT ports?

1883 for MQTT over TCP and 8883 for MQTT over TLS. WebSocket ports and paths depend on the broker.

What is the difference between QoS 0, 1 and 2?

QoS 0 delivers at most once with no acknowledgement. QoS 1 delivers at least once and may produce duplicates. QoS 2 delivers exactly once through a four-step handshake. The subscriber gets the lower of the publish and subscription QoS.

How do I delete a retained MQTT message?

Publish an empty (zero-length) payload with the retain flag to the same topic. The broker removes the retained message.

Why do my MQTT clients keep disconnecting?

The most common causes are two clients using the same client ID, a keep alive interval longer than a firewall's idle timeout, and the broker closing connections because of access rules. Check the client ID first.

Can I run an MQTT broker on my own computer for testing?

Yes. MQTT 360 includes an embedded local broker that starts with one click, which is useful for offline development and for test benches on site.

Which platforms does MQTT 360 run on?

MQTT 360 currently runs on Windows x64. It supports MQTT 3.1.1 and MQTT 5 over TCP, TLS and WebSocket.

Try it on your next integration

MQTT problems become simple once you check them in order: connection, topic names, QoS and session, retained messages, payload format. A workspace that shows each of these makes the difference between an afternoon of guessing and ten minutes of checking.

Download MQTT 360 for Windows, or read more on the MQTT 360 product page. If you are building a larger monitoring system on top of MQTT and Modbus devices, see Luna SCADA or contact us.

MQTT 360