Skip to content

ESP32 MQTT Keep Alive Causes Disconnections

DodaTech Updated 2026-06-26 1 min read

In this tutorial, you'll learn about ESP32 MQTT Keep Alive Causes Disconnections. We cover key concepts, practical examples, and best practices.

The Problem

ESP32 MQTT connections drop after inactivity or the keep-alive timer fires incorrectly.

Quick Fix

Wrong

client.setServer("broker.emqx.io", 1883);
client.connect("esp32");
Client disconnects after 45 seconds of no traffic.
Reconnecting... (loops forever)
client.setServer("broker.emqx.io", 1883);
client.setKeepAlive(120);
client.connect("esp32-ka");
Connection stable. No unexpected disconnections.

Prevention

Set keepAlive between 60-300 seconds for IoT. Call client.loop() at least twice as often as keepAlive. Disable keepalive only with broker support. Add ping mechanism. Monitor client.state() for drops.

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

FAQ

### What happens when keepalive expires?

The broker marks the client as disconnected and publishes the Last Will. The ESP32 must reconnect with a clean or stored session.

How often should I call client.loop()?

At least every 50ms for responsive handling, but minimum every keepAlive/2 seconds to prevent timeout disconnection.

Can I disable MQTT keepalive?

Set keepalive to 0 to disable, but not all brokers support this. Default 15 seconds may cause unnecessary reconnections for low-data devices.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro