Skip to content

Persistent Session messages dropped during connect() due to race condition (Subscribers: 0) #218

@ricardodanielalbano

Description

@ricardodanielalbano

Description:

I encountered a critical issue when using Persistent Sessions (Clean Session = false) with QoS 1.
When the worker connects to the broker, if there are queued offline messages, the broker sends them immediately after the CONNACK. The library reads and processes these PUBLISH packets inside the execution of the $client->connect() method.
Since the standard usage pattern is:
$client->connect(...)
$client->subscribe(...)
The messages are processed at step 1. At this point, the subscription callback (step 2) has not been registered yet. The logger shows Subscribers: 0 and the messages are effectively dropped/lost.

Reproduction Steps:

Connect a client with CleanSession = false and QoS 1.
Disconnect the client.
Publish a message to a topic with QoS 1.
Reconnect the client using the standard flow (connect then subscribe).
Result: The offline message is consumed by the library during the connection handshake but not delivered to the application because the subscription wasn't registered in time.

Expected Behavior:

The library should either:
A. Buffer incoming PUBLISH packets received during the connect() phase and process them only after the connection flow returns control to the user.
B. Or allow registering subscriptions/callbacks before connecting (without needing to manually inject a MemoryRepository).

Current Workaround:

I had to manually instantiate a MemoryRepository, add the Subscription object to it, and inject this repository into the MqttClient constructor. This ensures the callback is present in memory before the socket is read.
While the workaround works, the default usage pattern failing silently for persistent sessions seems like a significant pitfall.

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