Search code examples
mqttwildcard

Unexpected behavior with MQTT shared subscriptions using specific topics and wildcards


I'm experiencing unexpected behavior with MQTT shared subscriptions. Here's the scenario:

  1. I have two MQTT subscribers:

    • Subscriber A: subscribes to "$share/group/1234/test/A"
    • Subscriber B: subscribes to "$share/group/1234/#"
  2. When I publish a message to the topic "1234/test/A", both subscribers receive the message.

  3. However, when I change both subscriptions to "$share/group/1234/#", the behavior is as expected: only one subscriber receives each message.

  4. I've tested this behavior on various public MQTT brokers, and the results are consistent across all of them.

This seems to contradict the expected behavior of shared subscriptions, where messages should be distributed among subscribers in a shared group.

  1. Is this behavior intentional or a potential bug?
  2. What could be causing both subscribers to receive messages in the first scenario?
  3. Are there any known issues or limitations with shared subscriptions when mixing specific topics and wildcards?

Any insights or suggestions for resolving this issue would be greatly appreciated.


Solution

  • The MQTT V5 spec states:

    If a Server receives a Topic Filter that is identical to the Topic Filter for a Shared Subscription that already exists on the Server, the Session is added as a subscriber to that Shared Subscription. No retained messages are sent.

    Note that this says the Topic Filter must be identical, not that the Topic Filters overlap. For completeness, the Topic Filter described as:

    A Shared Subscription is identified using a special style of Topic Filter. The format of this filter is:

    $share/{ShareName}/{filter}

    So having an identical ShareName does not mean that the subscriptions are shared, the entire topic filter must be identical. $share/group/1234/test/A and $share/group/1234/# do not have identical topic filters, so are not the same shared subscription (and what you are seeing is to be expected).

    In your step 3, where both clients subscribe to $share/group/1234/# the topic filters are identical, so the second subscriber is added to the shared subscription (and things work as you expect them to).