MQTT doesn't care what you call your topics, which is exactly why a project with five ESP32s, a Node-RED flow and Home Assistant can turn into a mess of Temp, temperature, /sensor1/t and livingroom_lamp_cmd. A topic scheme is really an API: once devices and dashboards depend on it, renaming is painful. Ten minutes of planning saves that.
Quick answer: use lowercase, /-separated levels from general to specific, for example home/garage/door/state. Start without a leading /, never start with $, and avoid spaces. Give each device separate topics for readings (.../temperature), commands (.../set), reported state (.../state) and availability (.../status). Retain state and status, never commands. Then a single wildcard such as home/+/temperature collects every room's temperature.
A Pattern That Scales
location / device / what works for most home and hobby projects:
home/garage/status online | offline device availability (retained, Last Will)
home/garage/temperature 21.4 reading (retained: current value)
home/garage/humidity 58 reading
home/garage/door/state open | closed what the device reports (retained)
home/garage/door/set open | close a command (NOT retained)
home/livingroom/lamp/state ON | OFF
home/livingroom/lamp/set ON | OFFRead top to bottom, it's obvious what each topic carries and who publishes it, and it supports useful subscriptions:
| Subscription | Receives |
|---|---|
home/garage/# | Everything from the garage |
home/+/temperature | Every room's temperature |
home/+/status | Availability of every device |
home/+/+/set | Every command (useful for logging) |
For more than one building, or a lab and a house sharing one broker, add a level in front: lab/bench1/..., home/.... Keep the same depth for the same kind of thing, or + wildcards stop lining up.
The Hard Rules
These come from the MQTT specification or cause real bugs:
| Rule | Why |
|---|---|
No leading slash (home/..., not /home/...) | A leading / creates an empty first level, so +/garage won't match and tools show an unnamed branch |
Don't start topics with $ | $ is reserved for the broker, e.g. $SYS/... statistics; # subscriptions don't include them |
No + or # in published topics | They're wildcards, valid only in subscriptions |
| Topics are case-sensitive | home/Garage and home/garage are different topics: use lowercase everywhere |
| Avoid spaces and special characters | Legal, but painful in shells, URLs and ACL files. Use - or _ |
| No secrets or personal data in topics | Topic names appear in logs, debug tools and ACL files |
Separate Readings, Commands, State and Status
Four kinds of message, four kinds of topic:
| Kind | Example | Published by | Retain? |
|---|---|---|---|
| Reading (telemetry) | home/garage/temperature | Device | Usually yes: newcomers see the current value |
| Command | home/garage/door/set | Dashboard, automation | No: replaying commands is dangerous |
| Reported state | home/garage/door/state | Device, after acting | Yes |
| Availability | home/garage/status | Device; broker via Last Will | Yes |
Keeping command and state apart is what lets a dashboard switch show what the device really did rather than what someone asked for; the pattern is in Node-RED Dashboard 2.0. Availability with a Last Will is in MQTT retained messages and Last Will.
One Value per Topic, or JSON?
| One value per topic | One JSON topic | |
|---|---|---|
| Example | home/garage/temperature → 21.4 | home/garage/climate → {"temperature":21.4,"humidity":58} |
| Easy to use in dashboards | Yes, connect directly | Needs a JSON parse step |
Wildcard queries (+/temperature) | Yes | No |
| Readings stay in sync | Separate messages | One message, one timestamp |
| Adding a new field | New topic | Just add a key |
Both are fine. A good rule: single values for simple sensors and anything you'll wildcard, JSON for a group of readings taken together (a weather station, a power meter). If you use JSON, put units in the key names (temperature_c, power_w) and keep them consistent across devices.
Wildcards Recap
+matches exactly one level:home/+/temperaturematcheshome/garage/temperaturebut nothome/garage/rack/temperature.#matches any number of levels and must be last:home/garage/#matches everything under the garage, includinghome/garageitself.
Subscribe as narrowly as the consumer needs: a temperature logger subscribed to home/# also receives every command and status message.
Conventions Used by Popular Tools
If your devices share a broker with these, follow or at least avoid colliding with their topics:
| System | Topic convention |
|---|---|
| Home Assistant (MQTT discovery) | Config under homeassistant/<component>/<object_id>/config; HA's own status on homeassistant/status |
| Tasmota | cmnd/<device>/POWER commands, stat/<device>/POWER state, tele/<device>/SENSOR telemetry, tele/<device>/LWT availability |
| Zigbee2MQTT | zigbee2mqtt/<friendly name> state, zigbee2mqtt/<friendly name>/set commands |
| ESPHome (MQTT mode) | <node name>/sensor/<name>/state, <node name>/status |
Notice the common ideas: a separate command topic (set or cmnd), a reported state, and an availability topic using online/offline. Your own scheme can look different, but borrowing these ideas makes it work smoothly alongside them. For Home Assistant discovery, see MQTT with ESP32 and Home Assistant.
Naming Mistakes to Avoid
| Mistake | Problem | Better |
|---|---|---|
/home/garage/temp | Empty first level | home/garage/temperature |
Home/Garage/Temp | Case mismatches between devices | All lowercase |
esp32-1/data | Says nothing about place or content | home/garage/climate |
home/garage/lamp for both commands and state | Device and dashboard echo each other in a loop | .../lamp/set and .../lamp/state |
home/living room/lamp | Space breaks shells and ACL files | home/livingroom/lamp or living_room |
| Renaming topics in a firmware update | Dashboards and automations silently stop | Keep old topics for a while, or update all consumers together |
Retain State, Never Commands
A retained message is replayed to every new subscriber, including the device itself after a reboot. That's perfect for state (lamp/state = ON, status = online, temperature = 21.4) and dangerous for commands (door/set = open, lamp/toggle): the door opens again every time the board reconnects. Retain readings and states; send commands without retain. To delete a retained message, publish an empty retained one: mosquitto_pub -t TOPIC -r -n.
Topics Make Permissions Easy
A clean hierarchy turns broker permissions into a few readable lines. With Mosquitto's ACL file:
# Garage ESP32: publish its own branch, receive only its own commands
user esp32-garage
topic write home/garage/#
topic read home/garage/+/set
# Node-RED: everything under home/
user nodered
topic readwrite home/#A compromised or buggy garage sensor can't switch your living-room lamp. Setup steps are in installing Mosquitto on the Raspberry Pi.
Testing, Multiple Sites and Changing Topics Later
Keep test traffic apart. When you experiment on the same broker as your working system, prefix test topics (test/garage/...) or, better, run a second broker for development, so a half-finished sketch can't switch a real relay. Never copy real passwords into a test setup.
More than one place. If a broker serves a house and a workshop, or two homes over a VPN, the first level names the site: home/..., workshop/.... Each site's devices then get ACL rules on their own branch.
Renaming without breaking things. Topics are a contract between devices and everything that listens to them. When you must change one:
- Update the firmware to publish both the old and the new topic for a while.
- Move each consumer (Node-RED flows, Home Assistant entities, databases) to the new topic.
- Watch the old topic with
mosquitto_sub -t 'old/topic/#' -vuntil nothing reads it. - Remove the old topic from the firmware, and clear any retained messages left on it with
mosquitto_pub -t old/topic -r -n.
If a JSON payload changes shape (a field renamed, a unit changed), add a version key such as "v":2 so consumers can tell the formats apart.
Checklist
- Lowercase,
/-separated, no leading/, no spaces. - General to specific: place, device, then what.
- Separate
.../setcommands from.../statereports. - A
.../statustopic per device with a Last Will. - Retain readings, state and status; never commands.
- Same depth for the same kind of data, so wildcards line up.
- Units in names or JSON keys (
temperature_c). - Write the scheme down in your project's README, and keep old topics alive while you migrate.
Design a topic tree for a real ESP32 installation
A naming scheme becomes easier to maintain when every device has a stable identity and every payload has a documented meaning. For example, a temperature node in a workshop could publish:
site/workshop/esp32-01/status
site/workshop/esp32-01/temperature_c
site/workshop/esp32-01/humidity_pct
site/workshop/esp32-01/config/sample_interval_sUse a stable device identifier when hardware may move between rooms. If location is more important than hardware identity, put the room first and keep a separate device ID in the payload. Avoid mixing both patterns randomly: dashboards and wildcard subscriptions become harder to reason about when one sensor publishes at a different depth from another.
Decide what belongs in the payload
The topic should identify the resource; the payload should carry its value and, when needed, context. A compact JSON telemetry message might be:
{
"device_id": "esp32-01",
"temperature_c": 24.6,
"humidity_pct": 51.3,
"sequence": 1842
}Do not publish Wi-Fi passwords, broker credentials, access tokens, personal information or other secrets in either topics or payloads. MQTT messages can appear in broker logs, retained storage, packet captures and debugging tools. Use broker authentication and topic-level ACLs to control who can publish and subscribe; an obscure topic name is not an access-control mechanism.
Choose QoS for the job
QoS 0 is a best-effort delivery attempt and is often sufficient for frequent temperature updates where the next sample will arrive soon. QoS 1 provides at-least-once delivery, so a subscriber may receive a duplicate and should tolerate it. QoS 2 has a more involved handshake and is rarely necessary for ordinary sensor telemetry. QoS does not make a device's application logic exactly-once: a command handler should still be designed to handle retries safely.
For a command that changes an output, prefer an explicit desired state such as lamp/set = ON over a toggle command. If a client retries a toggle after a timeout, the output can end up in the opposite state. Publish the device's confirmed result separately on lamp/state, and include an acknowledgement or request identifier if the application needs to match a response to a particular command.
Test subscriptions before connecting hardware
Use a terminal to inspect the hierarchy before writing firmware:
mosquitto_sub -h BROKER_HOST -t 'site/#' -v
mosquitto_pub -h BROKER_HOST -t 'site/workshop/test/status' -m 'online'Replace the host with your broker address and add the authentication options required by your setup. Keep test traffic under a dedicated test/ prefix or use a separate development broker. This prevents a trial publish from reaching a real actuator subscription. When a scheme is stable, document topic, direction, payload format, QoS, retain behaviour and access permissions in the project's README.
FAQ
Should MQTT topics start with a slash? No. A leading / creates an empty first level and breaks wildcard patterns.
Are MQTT topics case-sensitive? Yes. Home/Lamp and home/lamp are different topics.
How long can a topic be? Up to 65,535 bytes in the specification, but keep them short: they're sent with every message.
Can I use spaces in MQTT topics? They're allowed, but avoid them: they break shell commands, URLs and ACL files.
Should I put the device ID or the location in the topic? Location usually reads better for dashboards. If devices move often, use a stable device ID and map it to a location in Node-RED or Home Assistant.
Next Steps
- MQTT explained: broker, topics, QoS, retained and LWT
- Test MQTT without hardware: try your scheme with
mosquitto_sub -t '#' -v - ESP32 MQTT auto-reconnect: a complete device using this layout
- MQTT troubleshooting




