Last updated: Aug. 10, 2024
Introduction
This page lists some best practices to ensure a consistent and extensible MQTT topic tree. This page doesn't dive into the different design practices or common topic patterns but I may create one for another post.
Best Practices
- Avoid empty characters for topic levels, each topic must contain at least one character
- Reason:
- Having empty space levels is hard to debug and prone to confusion
- Example:
- Never start with a forward slash
- Reason:
- Forward slash is a special character in MQTT and introduces a new topic level before and after
- Example:
- Never end with a forward slash
- Reason:
- Similarly to reason above, ending with forward slash introduces a new topic
- Empty space which can lead to confusion
- Example:
- Follow a consistent naming scheme
- Reason:
- Inconsistent naming scheme may lead to repetition and hard to read or interpret definitions
- Example:
- Camel case:
- Some projects use
-
:
some/topic/not-camel-case
- All lower case:
- Never use space character
- Reason:
- Difficult readability for the programmer
- May break APIs since UTF-8 has many different white space types
- Instead try to use naming scheme that replaces white space with upper case or
-
- Example:
- Keep topics short and concise
- Reason:
- Smaller topics reduces payload and helps network traffic
- Better for constrained devices
- Example:
- AWS limits topics to 7 levels
- AWS limits topic length to be 128 characters (256 bytes)
- Never use non-printable characters and non-ASCII characters
- Reason:
- Non-ASCII UTF-8 characters may display incorrectly
- Example:
- Stick to lower case letters, numbers, and dashes
- Include a unique device identifier or the client id
- Reason:
- Enforces message identification and enforce authorization
- Identifies the message sender
- Easier debugging
- Easier to retrieve device phisically
- Example:
- Client with id
client1
can publish using to client1/status
but no to client2/status
- Topics must embrace extensibility
- Reason:
- Facilitates scaling applications
- Example:
- Do
robot123/dt/motor/fan/temperature
instead of robot/motor/temperature
- Be specific
- Reason:
- Promotes clarity
- Easier integration with advance MQTT features such as retained messages
- Example:
hv100/bld1518/basement/hvac719
(goes from general to specific)
- Do
myhome/livingroom/humidity
instead of myhome/livingroom
- Never expose sensible information
- Reason:
- Security vulnerabilities to your application
- Example:
- Avoid starting with the dollar sign
$
- Reason:
- This hierarchy of topics are reserved for broker or internal services statistics
- Example:
- Some brokers may avoid to create topics with
$
Conclusion
There is no right or wrong approach with different naming conventions. The key is to establish a format that prevents confusion, embraces consistency, and is extensible.