Skip to content

Client Reconnect with Same clientID Causes Stale Connection Timeout and Incorrect Offline Status #483

@ogofly

Description

@ogofly

Issue Scenario:

On a device, an MQTT client connects to the mochi-mqtt/server. Without explicitly disconnecting, the device restarts and the client reconnects to the server using the same clientID. The new connection succeeds, but approximately 10–20 seconds later, the server logs indicate a read timeout for the original (first) connection. From the server’s perspective, the client with that clientID appears offline under its Clients list.

Log:

// Log printed in hook OnSessionEstablished
time=2025-11-17T10:28:49.106+08:00 level=INFO msg="Mqtt OnConnect" clientId=864865084478230 username=864865084478230 ip=39.144.46.220:32546 now=1763346529106978

time=2025-11-17T10:31:31.019+08:00 level=INFO msg="Mqtt OnConnect" clientId=864865084478230 username=864865084478230 ip=39.144.46.97:35605 now=1763346691019882
// After the device restarts, the same clientId connects to the broker again
// Why did "taken over" not occur and the old client was not removed?

// The broker detected that the client from the first connection went offline
time=2025-11-17T10:31:49.107+08:00 level=DEBUG msg="client disconnected" error="read tcp 10.0.3.131:1883->39.144.46.220:32546: i/o timeout" client=864865084478230 remote=39.144.46.220:32546 listener=tio-tcp
time=2025-11-17T10:31:49.108+08:00 level=WARN msg="" listener=tio-tcp error="read tcp 10.0.3.131:1883->39.144.46.220:32546: i/o timeout"

// Received the disconnect event in hook OnDisconnect
// Immediately checked the broker state for this clientId (in Server Clients) and found it's Closed() is False, so the business code ignored this disconnect event
time=2025-11-17T10:31:49.108+08:00 level=INFO msg="Ignore OnDisconnect message cause client is connected, may be concurrent connect and disconnect" clientId=864865084478230 username=864865084478230

// However, when checking the broker client's state later, it as removed from Server Clients
// But this client can still publish messages through the broker

Thank you for your great work on mochi-mqtt! We really appreciate the effort and dedication you’ve put into building and maintaining this project.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions