Shared subscriptions provide for client load balancing. With normal subscriptions(non shared subscriptions) if,for example, 4 clients subscribe to a topic and a client published a message on that topic then that message is sent to all 4 subscribing clients.
With a shared subscription then the message would only be sent to one of the subscribing clients.
The next message published would be sent to one of the other subscribing clients thus balancing the load on the clients and server.
This is illustrated in the diagram below.
Shared Subscription Topics
Shared subscriptions use a reserved topic root called $share and a share name that is used to group the subscribers.
The full topic name for a shared subscription to the topic test is.
$share +share name +test
The shared name is any valid UTF-8 string (but not + or #or /) and must be at least 1 character. So
is valid with a sharename of movies and a topic of test.
Clients subscribing to $share/movies/test and clients subscribing to just test are subscribing to the same topic.
In fact Clients subscribing to $share/oldmovies/test are also subscribing effectively to test.
A client doesn’t publish to the topic $share/movies/test but to the topic test.
So using the examples above.
If 10 clients subscribe to $share/movies/test and 10 clients subscribe to $share/movies/test and 10 clients subscribe to test.
Then if a client publishes a message to topic test then:
- 1 message is sent to one of the clients subscribing to $share/movies/test
- 1 message is sent to one of the clients subscribing to $share/oldmovies/test
- 10 messages is sent to one of the clients subscribing to test
So a total of 12 messages are sent to clients.
The screen shot below shows the output of a Python script that illustrates the above.
Notes: You can see that the clients 5 and 6 both receive the message whereas clients 1 and 3 receive a message for their shared subscription and clients 2 and 4 don’t receive the message.
Common Questions and Answers
Q- When is a shared subscription created?
A- When a client subscribes to it. However with only one client subscribing it behaves like a normal subscription.
Q- When is a shared subscription removed?
A- When no more clients are subscribing to it?
Q- What happens to retained messages on a shared subscription?
A- Retained messages aren’t sent to clients on a shared subscription.
Shared subscriptions allow for load balancing on the client side and use a reserved topic called $share and a user defined sharename.
The sharename is used for grouping clients.
Python Script used in the tutorial.
Note: the Paho client v 1.5.1 now support MQTT v5 and I will be changing the code to use this client shortly.
- MQTTv5 Topics and Topic Aliases
- Examining MQTTv5 User Properties
- MQTT Client and Mosquitto Broker Message Restrictions With Examples
- MQTTv5 CONNECT and CONNACK Messages -Overview
- Understanding And Using MQTT v5 Request Response
- MQTT v 5.0 New Features Overview