The most common MQTT bug report looks like this:
"My ESP32 connects to the broker, receives one or two messages, disconnects, reconnects, disconnects again. Every few seconds. Wi-Fi is fine."
Nine times out of ten the broker already told you why. You just did not log it. This post shows how to get the reason code out of the three most popular clients, what each code means, and the fix for every cause I have seen in production, including the one that bites almost everyone on public test brokers.
Step 0: get the reason code
MQTT 5 brokers send a reason code in CONNACK (refused connection) and DISCONNECT (broker closed the connection). MQTT 3.1.1 gives you only a handful of generic codes, so switch to MQTT 5 while debugging if your library supports it.
mosquitto clients (add -d for debug output):
mosquitto_sub -d -V mqttv5 -h broker.connectmq.com -p 1883 -i my-device -t 'devto/#' # ... Client my-device received DISCONNECT (142) Python, paho-mqtt 2.x:
import paho.mqtt.client as mqtt def on_connect(client, userdata, flags, reason_code, properties): print("CONNACK:", reason_code) # e.g. "Success" or "Client identifier not valid" def on_disconnect(client, userdata, flags, reason_code, properties): print("DISCONNECT:", reason_code) # e.g. "Session taken over" c = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, client_id="my-device", protocol=mqtt.MQTTv5) c.on_connect, c.on_disconnect = on_connect, on_disconnect c.connect("broker.connectmq.com", 1883) c.loop_forever() Node.js, MQTT.js:
import mqtt from 'mqtt' const c = mqtt.connect('mqtts://broker.connectmq.com:8883', { clientId: 'my-device', protocolVersion: 5 }) c.on('disconnect', (packet) => console.log('DISCONNECT reason', packet.reasonCode)) // broker-initiated c.on('error', (err) => console.log('error', err.code, err.message)) // refused CONNACK c.on('close', () => console.log('socket closed')) If you see a close with no DISCONNECT before it, the broker did not hang up on you: the network did. Jump to the keep-alive section.
The reason codes that explain most disconnect loops
| Code | Dec | Name | Usual cause |
|---|---|---|---|
0x8E | 142 | Session taken over | Another client connected with the same client ID |
0x85 | 133 | Client identifier not valid | The broker has rules for client IDs and yours breaks them |
0x86 | 134 | Bad user name or password | Wrong credentials, often a trailing space from copy-paste |
0x87 | 135 | Not authorized | ACL denies the topic, or the credentials lack publish/subscribe rights |
0x89 | 137 | Server busy | Too many new connections per second (a reconnect storm) |
0x8A | 138 | Banned | Too many failed attempts from your IP or client |
0x97 | 151 | Quota exceeded | Connection, minute, traffic or per-message limit reached |
MQTT 3.1.1 clients see only 2 (identifier rejected), 4 (bad username or password), 5 (not authorized) and 3 (server unavailable).
0x8E Session taken over: the classic loop
MQTT allows exactly one connection per client ID. When a second client connects with an ID that is already online, the broker closes the first one with 0x8E. Both clients have auto-reconnect, so they take turns kicking each other off, forever. From each device it looks like "random disconnects every few seconds".
Where the duplicate comes from:
- The same firmware on several boards with a hard-coded client ID.
- Copy-pasted example code. Arduino and PubSubClient examples use IDs like
ESP8266ClientorarduinoClient. On a public broker, hundreds of strangers run the same example right now, and every one of them disconnects you. - A script opened twice, or a dashboard open in two browser tabs.
- A zombie process on a server you forgot about.
Fix: derive the ID from something unique to the device.
// ESP32 (Arduino): unique client ID from the MAC address String clientId = "myproj-esp32-" + String((uint32_t)ESP.getEfuseMac(), HEX); // Browser: unique per tab const clientId = 'web-' + crypto.randomUUID().slice(0, 8) 0x85 Client identifier not valid
The MQTT spec lets brokers restrict client IDs (length, characters, or a required prefix). Managed brokers use this to tie IDs to credentials so one leaked password cannot impersonate every device.
On ConnectMQ, for example, each credential set has an issued client ID such as connectmq_client_594592. A client must connect with exactly that ID or with that ID plus an underscore and any suffix:
| Client ID sent | Result |
|---|---|
connectmq_client_594592 | accepted |
connectmq_client_594592_esp32-a4cf12e8b1 | accepted |
esp32-a4cf12e8b1 | 0x85 |
That rule also solves 0x8E: same username and password on every device, unique suffix per device. The issued ID is shown next to the host and ports in the console:
Details: client IDs and sessions.
0x97 Quota exceeded
0x97 can arrive in two places, and they mean different things:
- In CONNACK: you hit a connection-level limit, such as concurrent connections or monthly connected minutes. Every open console tab and every gateway counts as a connection.
- In PUBACK/PUBREC (QoS 1/2): one message broke a per-message limit: too large, too many per second, too many topic levels, too many retained topics, or the monthly traffic is used up. The connection stays open; that message is dropped.
QoS 0 publishers are not told when a message is dropped. While debugging, publish with QoS 1 so the broker can report the reason code back to you.
Typical fixes: batch several values into one JSON message, publish on change instead of every 100 ms, keep payloads small (send files to object storage and publish a link), and close idle debug sessions.
0x89 Server busy: the reconnect storm
Your router reboots. 300 devices reconnect in the same second. The broker rate-limits new connections and refuses most of them with 0x89. They all retry after exactly one second. Repeat.
Fix: reconnect with exponential backoff and random jitter.
// MQTT.js: turn off the fixed-interval reconnect and schedule our own const client = mqtt.connect(url, { ...options, reconnectPeriod: 0 }) let attempt = 0 function nextDelay() { const base = Math.min(30_000, 1_000 * 2 ** attempt++) // 1s, 2s, 4s ... max 30s return base / 2 + Math.random() * base / 2 // jitter: spread the herd } client.on('connect', () => { attempt = 0 }) client.on('close', () => setTimeout(() => client.reconnect(), nextDelay())) No reason code at all: keep-alive and NAT timeouts
If the socket just closes with no DISCONNECT, something between you and the broker dropped an idle TCP connection. Home routers, carrier-grade NAT on 4G/LTE and corporate firewalls often forget idle connections after a few minutes.
The keep-alive interval is how long your client may stay silent before its library sends a PINGREQ. If the broker hears nothing for about 1.5 × keep-alive, it closes the connection and publishes your Last Will.
| Client | Keep-alive that works |
|---|---|
| Wi-Fi / Ethernet devices and gateways | 60 s |
| 4G / LTE / NB-IoT | 120–300 s (lower it if you still see silent drops) |
| Back-end services | 30–60 s |
Two more things to check: some brokers cap keep-alive (ConnectMQ caps it at 600 s, and treats 0 as 600), and PubSubClient's default buffer is 256 bytes, so a larger message is silently not sent. Call mqtt.setBufferSize(1024).
TLS problems that look like disconnects
| Symptom | Cause | Fix |
|---|---|---|
certificate verify failed, unknown CA | Device has no CA store | Embed the root CA (Let's Encrypt ISRG Root X1 for ConnectMQ) |
| Works with IP, fails with hostname (or the opposite) | Hostname mismatch | Always connect to the DNS name |
| Fails only after a power cut | Device clock reset to 1970 | Sync time with NTP before TLS |
| Handshake times out on one network | Port 8883 blocked | Try MQTT over WSS on 8084 |
A 60-second triage flow
- Log the reason code (Step 0).
-
0x8E→ duplicate client ID.0x85→ ID format.0x86/0x87→ credentials or ACL. -
0x97→ check usage and message size; publish with QoS 1 to see it. -
0x89→ add backoff with jitter. - No code → keep-alive, NAT, Wi-Fi power saving, TLS clock.
The full table, including MQTT 3.1.1 codes, is in the ConnectMQ troubleshooting guide.
FAQ
Why does my MQTT connection drop every few seconds?
Most often two clients share a client ID and take the session from each other (reason code 0x8E). Give each device a unique ID.
What does MQTT reason code 142 mean?
142 (0x8E) is Session taken over: another client connected with the same client ID.
What does MQTT reason code 151 mean?
151 (0x97) is Quota exceeded: a connection, traffic or per-message limit was reached.
What keep-alive should I use for MQTT on LTE?
Start between 120 and 300 seconds and lower it if the carrier still drops idle connections.
Next in this series: moving an ESP32 from test.mosquitto.org to a private broker over TLS.
If you want reason codes, a connection history and live topic values in one place while debugging, a free ConnectMQ broker takes about five minutes to set up.



