Most ESP32 MQTT sketches connect once and assume the link lasts forever. Then the router reboots or the broker restarts, the classic reconnect() function sits in a while loop retrying every 5 seconds, and everything else on the board (buttons, sensors, displays, safety logic) freezes until the network returns.
Quick answer: never reconnect inside a while loop. In loop(), call client.loop() when connected; when not, try one connect() only if a retry timer has expired, and double the wait after each failure (1 s, 2 s, 4 s... up to 30 s). Set client.setSocketTimeout(2) so a failed attempt doesn't block for PubSubClient's default 15 seconds, re-subscribe after every successful connect, give each board a unique client ID, and register a Last Will so the broker reports the device offline when it disappears. The complete sketch below does all of it.
Why the Usual reconnect() Freezes Your Board
This is the pattern in most tutorials, and in PubSubClient's basic example:
void reconnect() {
while (!client.connected()) { // stuck here until the broker is back
if (!client.connect("esp32")) delay(5000);
}
}While the broker is down, nothing else in your sketch runs: a button press is missed, a relay that should switch off stays on, a display stops updating. It also has two hidden costs:
- Each
connect()attempt can block for up to 15 seconds (PubSubClient's default socket timeout) when the broker doesn't answer. - Every board retries at the same moment after a shared outage such as a router reboot, all hammering the broker together.
The fix is a small state machine driven by millis(): check, maybe try once, and get on with the rest of loop(). PubSubClient's own mqtt_reconnect_nonblocking example shows the basic idea; the sketch below adds backoff, jitter, Wi-Fi recovery, a Last Will and re-subscription.
What You Need
- An ESP32 board and the PubSubClient library (Library Manager → PubSubClient by Nick O'Leary).
- An MQTT broker your ESP32 can reach, with a username and password, such as Mosquitto on a Raspberry Pi.
- The broker's LAN IP address.
localhostor127.0.0.1on an ESP32 means the ESP32 itself.
The Complete Sketch
This controls an LED (or a relay module) on GPIO 2 from MQTT, reports the real state back, publishes the board's uptime every 10 seconds, and keeps running its own loop no matter what the network does.
#include <WiFi.h>
#include <PubSubClient.h>
const char* WIFI_SSID = "YOUR_WIFI";
const char* WIFI_PASS = "YOUR_WIFI_PASSWORD";
const char* MQTT_HOST = "192.168.1.20"; // broker LAN IP
const uint16_t MQTT_PORT = 1883;
const char* MQTT_USER = "esp32-livingroom";
const char* MQTT_PASS = "YOUR_MQTT_PASSWORD";
const char* TOPIC_STATUS = "home/livingroom/status"; // online / offline (retained)
const char* TOPIC_CMD = "home/livingroom/lamp/set"; // commands in
const char* TOPIC_STATE = "home/livingroom/lamp/state"; // real state out (retained)
const char* TOPIC_UPTIME = "home/livingroom/uptime";
const int LAMP_PIN = 2;
WiFiClient net;
PubSubClient mqtt(net);
String clientId;
unsigned long nextMqttAttempt = 0;
unsigned long retryMs = 1000;
const unsigned long RETRY_MAX_MS = 30000;
unsigned long lastWifiAttempt = 0;
unsigned long lastPublish = 0;
void publishLampState() {
mqtt.publish(TOPIC_STATE, digitalRead(LAMP_PIN) ? "ON" : "OFF", true);
}
void onMessage(char* topic, byte* payload, unsigned int len) {
String msg;
for (unsigned int i = 0; i < len; i++) msg += (char)payload[i];
if (strcmp(topic, TOPIC_CMD) == 0) {
if (msg == "ON") digitalWrite(LAMP_PIN, HIGH);
if (msg == "OFF") digitalWrite(LAMP_PIN, LOW);
publishLampState(); // report what really happened
}
}
bool connectMqtt() {
// Last Will: if this board vanishes, the broker publishes "offline" (retained) for it
if (!mqtt.connect(clientId.c_str(), MQTT_USER, MQTT_PASS, TOPIC_STATUS, 1, true, "offline")) {
return false;
}
mqtt.publish(TOPIC_STATUS, "online", true);
mqtt.subscribe(TOPIC_CMD); // subscriptions don't survive a reconnect
publishLampState();
return true;
}
void maintainNetwork() {
if (WiFi.status() != WL_CONNECTED) {
if (millis() - lastWifiAttempt > 10000) { // nudge Wi-Fi every 10 s
lastWifiAttempt = millis();
WiFi.reconnect();
}
return;
}
if (mqtt.connected()) {
mqtt.loop();
return;
}
if ((long)(millis() - nextMqttAttempt) < 0) return; // not time to retry yet
if (connectMqtt()) {
Serial.println("MQTT connected");
retryMs = 1000;
} else {
Serial.printf("MQTT failed, rc=%d, next try in %lu ms\n", mqtt.state(), retryMs);
nextMqttAttempt = millis() + retryMs + random(0, 500); // jitter
retryMs = min(retryMs * 2, RETRY_MAX_MS);
}
}
void setup() {
Serial.begin(115200);
pinMode(LAMP_PIN, OUTPUT);
digitalWrite(LAMP_PIN, LOW); // safe state until told otherwise
WiFi.mode(WIFI_STA);
WiFi.begin(WIFI_SSID, WIFI_PASS);
clientId = "esp32-" + WiFi.macAddress(); // unique per board
clientId.replace(":", "");
mqtt.setServer(MQTT_HOST, MQTT_PORT);
mqtt.setCallback(onMessage);
mqtt.setSocketTimeout(2); // give up a failed connect after 2 s, not 15
mqtt.setKeepAlive(15);
randomSeed(esp_random());
}
void loop() {
maintainNetwork();
// Your local work runs every pass, connected or not
if (millis() - lastPublish >= 10000) {
lastPublish = millis();
if (mqtt.connected()) {
char buf[16];
snprintf(buf, sizeof(buf), "%lu", millis() / 1000);
mqtt.publish(TOPIC_UPTIME, buf);
}
}
}Test it: open a terminal on the broker and watch everything with mosquitto_sub -h localhost -t 'home/#' -v -u USER -P PASS. Send mosquitto_pub -t home/livingroom/lamp/set -m ON ... and the LED lights and lamp/state ON appears. Then stop the broker (sudo systemctl stop mosquitto): the Serial Monitor shows retries at growing intervals while the board keeps running. Start it again and within 30 seconds the board reconnects, publishes online, and responds to commands again.
If you power the ESP32 off instead, home/livingroom/status changes to offline about 1.5 times the keep-alive (here around 20–25 seconds) later: that's the Last Will.
How Each Part Works
Backoff. After a failure the wait doubles, 1, 2, 4, 8, 16 then 30 seconds, and resets to 1 second after a success. A broker that's briefly down gets reconnected in seconds; one that's down for an hour isn't flooded.
Jitter. random(0, 500) adds up to half a second to each wait, so ten boards that lost the router together don't all retry in the same instant.
Socket timeout. setSocketTimeout(2) caps how long connect() waits for the broker to answer. One attempt can still take a few seconds if the broker's IP doesn't exist on the network, because opening the TCP connection itself has its own timeout. If even that is too long for your project, run the MQTT code in its own FreeRTOS task, as shown in ESP32 dual core and FreeRTOS.
Wi-Fi first. MQTT attempts only start once Wi-Fi is up; otherwise every attempt fails instantly with rc=-2. The ESP32 also reconnects Wi-Fi by itself, and the 10-second WiFi.reconnect() nudge covers routers that stay silent. For deeper Wi-Fi recovery, see ESP32 Wi-Fi troubleshooting.
millis() comparisons. (long)(millis() - nextMqttAttempt) < 0 stays correct when millis() wraps round after about 49 days.
Re-Subscribing and Retained Commands
PubSubClient connects with a clean session, so the broker forgets your subscriptions whenever the connection drops. That's why subscribe() lives inside connectMqtt(): every successful connect restores them. Forgetting this is the classic "it works until the first Wi-Fi blip, then ignores commands" bug.
Be careful with retained command topics. If something publishes ON to lamp/set with the retain flag, the board receives it again after every reconnect and every reboot. That's sometimes what you want ("the desired state is ON"), and dangerous for one-shot commands such as "open the door". Publish commands without retain, and keep retain for state topics such as lamp/state and status.
Online and Offline Status
The sketch registers a Last Will on home/livingroom/status when it connects: if the board disappears without saying goodbye (power cut, crash, Wi-Fi gone), the broker publishes offline there, retained. On every successful connect the board publishes online to the same topic, retained. Any dashboard, Node-RED flow or Home Assistant entity subscribed to that topic now always knows whether the device is alive.
The Last Will isn't instant: the broker publishes it only after missing keep-alives for about 1.5 times the keep-alive interval. A 15-second keep-alive means roughly 20–25 seconds. The full pattern, including clearing old retained messages, is in ESP32 MQTT retained messages and Last Will.
Test the Failure Cases
| Test | What should happen |
|---|---|
| Boot with the broker stopped | Retries at growing intervals; the board's loop keeps running |
| Start the broker | Connects within the current retry interval (30 s at most), publishes online |
| Stop the broker while connected | connected() goes false, retries begin, local work continues |
| Restart the router | Wi-Fi reconnects, then MQTT, then commands work again |
| Pull the ESP32's power | status changes to offline after about 20–25 s |
| Two boards flashed with the same sketch | Both stay connected: client IDs come from their MACs |
Send ON, then reboot the board | The lamp starts OFF (safe default) and stays OFF unless a retained command exists |
Common Mistakes
| Mistake | Symptom | Fix |
|---|---|---|
reconnect() with a while loop | Board freezes whenever the broker is down | Timer-based single attempt per interval, as above |
No setSocketTimeout() | Each failed attempt stalls the loop for about 15 s | mqtt.setSocketTimeout(2) |
| Same client ID on every board | Boards kick each other off every few seconds | Build the ID from the MAC address |
Subscribing only in setup() | Commands ignored after the first dropout | Subscribe inside the connect function |
Long delay() calls in loop() | Disconnects with rc=-4 (keep-alive missed) | millis() timing; keep mqtt.loop() running |
Publishing before checking connected() | Silent message loss | Check connected(), or queue readings until reconnected |
| Large JSON payloads | publish() returns false | mqtt.setBufferSize(1024) before connecting |
| Output state restored from a retained one-shot command | Door or relay operates again after every reboot | Retain only state topics, never one-shot commands |
Other ESP32 MQTT Libraries
| Library | Reconnects by itself | Blocking | Notes |
|---|---|---|---|
| PubSubClient (this guide) | No: you write the logic | connect() can block | Simplest and most documented; QoS 0/1 subscribe, QoS 0 publish |
| AsyncMqttClient | Via your event handlers | No | Event-driven; QoS 0–2; less actively maintained |
ESP-IDF esp_mqtt (usable from Arduino) | Yes, built in | No, runs in its own task | QoS 0–2, TLS, MQTT 5; more setup code |
256dpi arduino-mqtt (MQTTClient) | No | Short timeouts | Similar API to PubSubClient, larger default buffer |
If you're starting a large project from scratch, esp_mqtt removes the reconnect problem entirely. For most hobby builds, PubSubClient with the pattern above is reliable and easier to follow.
FAQ
Why does my ESP32 freeze when the MQTT broker is down? Its reconnect code waits in a while loop, and each attempt can block for 15 seconds. Use the timer-based pattern above with setSocketTimeout().
How often should it retry? Start at about a second and back off to 30–60 seconds. Constant retries achieve nothing while the broker is down.
Do I need to subscribe again after reconnecting? Yes, with PubSubClient: it uses a clean session, so subscriptions are lost on every disconnect.
What does rc=-2 mean during reconnects? The network connection to the broker failed. See MQTT troubleshooting: rc=-2 and rc=5.
Is there a library that reconnects by itself? Yes: AsyncMqttClient and the ESP-IDF MQTT client (esp_mqtt) both reconnect in the background. PubSubClient stays the most common choice because it's simple and well documented.
Does the same code work on the ESP8266? Yes, with #include <ESP8266WiFi.h> and ESP.getChipId() or the MAC for the client ID.
Next Steps
- ESP32 MQTT retained messages and Last Will: online/offline status in depth
- MQTT topic naming best practices: designing the
home/room/device/...tree - Node-RED Dashboard 2.0: a switch that shows the device's real state
- MQTT troubleshooting: when the connection won't come up at all




