Skip to content

ESP32 MQTT Connection Fails to Broker

DodaTech Updated 2026-06-26 1 min read

In this tutorial, you'll learn about ESP32 MQTT Connection Fails to Broker. We cover key concepts, practical examples, and best practices.

The Problem

ESP32 cannot connect to MQTT broker — connection refused, timeout, or unauthorized.

Quick Fix

Wrong

WiFiClient espClient;
PubSubClient client(espClient);
client.setServer("broker.emqx.io", 1883);
client.connect("esp32");
Attempting MQTT connection... failed, rc=-2 try again
WiFiClient espClient;
PubSubClient client(espClient);
client.setKeepAlive(60);
int retries = 0;
while (!client.connected() && retries < 5) {
  if (client.connect("esp32-client", "user", "pass")) {
    Serial.println("Connected");
  } else {
    Serial.printf("Failed rc=%d", client.state());
    retries++; delay(5000);
  }
}
Connected to MQTT broker
rc=0 means success

Prevention

Check return code: 0=success, 1=bad protocol, 2=ID rejected, 3=unavailable, 4=bad credentials, 5=not authorized. Set unique client ID. Add authentication for production. Use setKeepAlive(60).

DodaTech engineers apply these same patterns across Doda Browser, DodaZIP, and Durga Antivirus Pro for production IoT reliability.

FAQ

### What are common MQTT connection return codes?

0=success, 1=protocol mismatch, 2=client ID rejected, 3=server unavailable, 4=wrong credentials, 5=not authorized.

How often should I attempt reconnection?

Use exponential backoff: 1s, 2s, 4s, 8s, 16s max. Limit total attempts to prevent resource exhaustion.

Can ESP32 connect over MQTT over TLS?

Yes. Use WiFiClientSecure instead of WiFiClient. Set the CA certificate with setCACert(). Change port to 8883 for secure MQTT.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro