Skip to content

Mqtt Client Disconnect

DodaTech 1 min read

In this tutorial, you'll learn about MQTT Client Disconnects Unexpectedly. We cover key concepts, practical examples, and best practices.

The Problem

MQTT client connection drops unexpectedly with no error message.

Quick Fix

Wrong

client.on('connect', () => {
  // No disconnect handler
})
Connection drops silently — no notification to application.
const client = mqtt.connect('mqtt://broker:1883')

client.on('connect', () => console.log('Connected'))

client.on('disconnect', (packet) => {
  console.log('Disconnected by broker, reason:', packet.reasonCode)
})

client.on('close', () => {
  console.log('Connection closed - reconnecting in 5s')
  setTimeout(() => client.reconnect(), 5000)
})

client.on('offline', () => {
  console.log('Client went offline')
})

client.on('error', (err) => {
  console.error('MQTT error:', err.message)
})
Disconnection detected and reconnection automatically attempted.

Prevention

Common disconnection causes: network failure, keep-alive timeout, duplicate Client ID, broker restart, authentication failure. Always implement auto-reconnect with exponential backoff. Handle all events: close, offline, error, disconnect. MQTT 5.0 disconnect packets include a reason code.

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

FAQ

### What is MQTT reconnect backoff?

Start with 1 second, double each attempt, max 30-60 seconds. Reset on successful connect. Avoid thundering herd after broker restart.

Does reconnect restore subscriptions?

If Clean Session = false, the broker remembers subscriptions and delivers queued messages. Otherwise, re-subscribe.

How to detect broker restart?

Subscribe to $SYS/broker/uptime. If uptime resets, the broker restarted. Reconnect and re-subscribe.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro