MQTT – Topics

by luca
1 comment

In the first part of this tutorial, I introduced the concept of topics. Every message sent to an MQTT broker must be published to a topic and clients connected to the broker decide which messages to receive subscribing to one or more topics.

Today you’ll learn the format of the topics and different ways to subscribe to them.

A topic is a string (UTF-8 format) and consists of one or more levels, separated by a forward slash.

Here are some examples of topics:


A topic must have at least one character and can contains spaces (even if it’s not recommended).

Note that topics are case sensitive, therefore the following topics are different: Home/Temperature and home/temperature

You’re not required to define/create a topic on the broker to use it: a client sending a message can specify any topics, provided it’s syntactically correct.


A client can subscribe one or more topics. The subscription can be precise, specifying the exact name of the topic to be subscribed. Alternatively, you can use two wildcards, that are special characters used to subscrive a group of topics.

The first wildcard is the character. This subscribes to a single level of topics.

Let’s see an example: if you subscribe to the topic home/+/temperature, you subscribe to all the topics that contain an arbitrary string instead of the wildcard, for example:


  • home/living/temperature
  • home/kitchen/temperature
  • home/terrace/temperature


Here are on the contrary some topics thare are not subscribed:


  • garage/temperature
  • home/living/humidity
  • home/terrace/dx/temperature


The last example explains that the + character is wildcard for a single level (it therefore does not correspond to the two levels, terrace/dx, of the example).

The multilevel wildcard character is #. This must be the last character in the topic and preceded by a forward slash, /.

For example, if you subscribe to the topic home/indoor/# you’ll get the messages of the following topics:


  • home/indoor/temperature
  • home/indoor/kitchen/temperature
  • home/indoor/kitchen/humidity


while you won’t get messages from the following topics:


  • home/outdoor/temperature
  • garage/humidity


If you subscribe to the # topic (without specifying any root string) you’ll receive all the messages sent to the broker

Let’s try!

We can verify what explained above thanks to mosquitto. After having executed the server, let’s subscribe to the topic home/+:

mosquitto_sub.exe -t home/+ -v

(we use the -v option to display, together with the message, also the topic the message was published to).

If now we send messages to different topics, we can verify which of them are received and which not:


We can do a similar test for the wildcard #:


Related Posts

1 comment

Mauro Wednesday April 26th, 2017 - 05:32 PM

Grande Luca!!! Come sempre articoli chiari e ben descritti.
Grazie per il lavoro e la condivisione


Leave a Comment

two × 5 =