Skip to content
Guide
13 min read
October 17, 2026

MQTT Troubleshooting: Connection Refused, rc=-2 and rc=5

Diagnose MQTT connection failures systematically. Understand broker listener and port problems, PubSubClient rc=-2 and rc=5, authentication, client IDs, topic mismatches and reconnect logs for ESP32, ESP8266, Mosquitto and Node-RED.

MQTT Troubleshooting: Connection Refused, rc=-2 and rc=5

An MQTT device that will not connect can fail at several layers: the network route may be wrong, the broker may not be listening on the expected address, the TCP connection may be refused, or the broker may reject the client's protocol handshake or credentials. These failures look similar if firmware only prints “MQTT failed.”

This guide focuses on a common Arduino pattern: state values returned by PubSubClient through client.state(). Other MQTT libraries can use different error codes, so confirm which library your sketch uses. Work from the network outward, change one variable at a time, and use broker logs rather than guessing.

Image pending: Image placeholder: diagnostic flowchart moving from Wi-Fi/IP to TCP broker port, MQTT handshake/credentials, subscriptions and message payload.

1. Identify which layer is failing

Before changing code, record the broker host/IP configured in the client, the broker port and whether it is plain MQTT or TLS, whether a command-line subscriber on the same network can connect, and the exact client library and its return code.

A device can join Wi-Fi successfully while MQTT still fails. Wi-Fi status says nothing about whether the broker host is correct, the broker is listening, the firewall permits access, or authentication succeeds.

For Mosquitto on Raspberry Pi, check:

sudo systemctl is-active mosquitto sudo journalctl -u mosquitto -n 80 --no-pager

A service may be active but listening only on loopback. Check listener configuration before assuming the broker is reachable from other devices.

2. What PubSubClient rc=-2 means

For PubSubClient state constants, MQTT_CONNECT_FAILED is -2. It indicates that the client could not complete the connection attempt; the underlying cause may be below the MQTT protocol layer, such as a TCP connection failure. Treat it as a direction for diagnosis, not a definitive statement about a particular wire or password.

Check:

  • Wrong host: localhost or 127.0.0.1 on an ESP32 refers to the ESP32 itself, not the Raspberry Pi.
  • Wrong port: the broker and client must agree. Unencrypted MQTT commonly uses 1883 and TLS commonly uses 8883, but configured ports can differ.
  • No listener / local-only default: Mosquitto 2.0 without configured listeners is loopback-only by default.
  • Routing or firewall: the Pi and board may be on different VLANs, or guest Wi-Fi may block local devices.
  • Broker stopped or port unavailable: verify service and listener before adjusting firmware.

Run a local command-line test first, then repeat from a different machine on the LAN. That isolates broker startup from remote reachability.

Image pending: Image placeholder: terminal comparison showing a local MQTT pub/sub test succeeds while a remote host test fails because the listener is local-only. Do not include credentials.

3. What PubSubClient rc=5 means

In the PubSubClient return-code enum, 5 corresponds to MQTT_CONNECT_UNAUTHORIZED. The broker is rejecting the connection as unauthorized. This differs from a network refusal: the client reached a broker far enough for MQTT connection handling, but access was denied.

Check the username, password, password file, listener-specific authentication settings and broker log. Confirm the service restarted after configuration edits. On newer Mosquitto versions, some legacy listener authentication settings have been deprecated, so use documentation that matches the installed major release.

Do not fix rc=5 by enabling anonymous access on an exposed broker. Use explicit authentication and topic permissions. If setting up a lab, use a test user and rotate credentials pasted into a public sketch or screenshot.

4. Other frequent MQTT problems

Duplicate client IDs: MQTT brokers identify a connection by client ID. If two devices connect with the same ID, one may disconnect the other. Generate a stable unique ID per physical device.

Protocol errors: confirm client and broker support a compatible MQTT protocol version and that a TLS client is not pointed at a plain MQTT port, or vice versa.

Connected but no messages arrive: the connection may be healthy but topic, QoS, subscription or payload logic may be wrong. Check the exact topic string and verify subscription is performed after every reconnect.

Messages appear as zero or invalid JSON: inspect the raw payload in a command-line client or Debug node before converting it. A successful MQTT packet is not proof that the application parsed its contents correctly.

Image pending: Image placeholder: error-reference table pairing symptom, likely layer and first useful diagnostic command/log to inspect.

5. Use command-line tools to separate client and broker issues

On the broker host, start a subscriber on a known test topic:

mosquitto_sub -h 127.0.0.1 -t 'solderhub/diagnostic' -v

Publish from another terminal on that same host:

mosquitto_pub -h 127.0.0.1 -t 'solderhub/diagnostic' -m 'test'

If that succeeds, try from another device using the broker's LAN address and intended authentication parameters. Use credentials appropriate to your environment; do not reuse a password that appeared in a terminal log or public example.

This progression separates three questions: is the broker running, can another host reach the listener, and are remote credentials accepted? It avoids debugging ESP32 firmware while the broker setup itself is broken.

Image pending: Image placeholder: command-line MQTT test progression: broker local test → remote LAN test → authenticated test → ESP32 client.

6. Read broker logs and configuration

On a systemd-based Raspberry Pi OS installation, inspect recent Mosquitto logs:

sudo journalctl -u mosquitto -n 100 --no-pager

Look for the connection time and whether the broker reports a listener, authentication failure or client disconnection. Do not paste unredacted logs into public support requests; they may contain private hostnames, usernames or topic names.

Check the active configuration rather than just the file you edited. Mosquitto can include files from a configuration directory, and a syntax error can prevent a restart. Check service status after every change and use the Mosquitto configuration manual for supported options.

7. If Node-RED is the client

Open broker settings configured by the MQTT In or MQTT Out node. Check hostname, port, TLS configuration and credentials in the shared broker configuration. A common mistake is entering 127.0.0.1 when Node-RED and Mosquitto are on different machines or containers. Another is configuring TLS in the client while pointing at a listener that expects plain MQTT.

Connect MQTT In to Debug and inspect the message after connection succeeds. MQTT topic names are case-sensitive, so sensor/room1/temp differs from sensor/Room1/temp. Check node status and broker logs around the time you press Deploy.

8. If an ESP32 or ESP8266 is the client

Print Wi-Fi status, the broker target and the library's state value—never print the password or authentication token. Ensure Wi-Fi is ready before attempting MQTT. Reconnect with a controlled interval and subscribe again after success. Keep the client loop serviced regularly.

For PubSubClient, a failed attempt should not trap firmware in an infinite tight loop or a long blocking delay. See Non-blocking MQTT Auto-Reconnect on ESP32. Use a unique client ID and subscribe to a test topic with simple text before introducing JSON parsing and sensor code.

Image pending: Image placeholder: serial monitor showing Wi-Fi connected, broker host/port without secrets, MQTT attempt and decoded state constant. Include no private SSID or token.

A practical checklist

  • Confirm the library and the meaning of its return code.
  • Confirm the correct broker host from the client's network position.
  • Confirm the broker service is active and a listener exists.
  • Verify local publish/subscribe independently of hardware.
  • Test from another LAN host with intended auth/TLS settings.
  • Inspect broker logs at the failure time.
  • Check credentials, ACLs, client ID and protocol compatibility.
  • Confirm topic names and payload format after connection succeeds.
  • Replace tight or blocking reconnect loops with scheduled retries.

Official reading: Mosquitto documentation, configuration manual and documentation for the MQTT client library used by your firmware.

Signal In

Built from what makers search for

The lookups piling up in SolderHub's search bar every day shape what we publish next — new component pages, board guides, and firmware notes, sent out as they go live.

By subscribing you agree to our Privacy Policy. Unsubscribe anytime.