Skip to content

Guide

MQTT Topic Naming Best Practices: Structure, Wildcards and Examples

Design MQTT topic hierarchies that stay readable as IoT projects grow. Learn device naming, telemetry versus commands, wildcard filters, case sensitivity, retained state and topic permission patterns.

  • 10 min read
  • Updated November 14, 2026
MQTT Topic Naming Best Practices: Structure, Wildcards and Examples

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:

Output
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 | OFF

Read top to bottom, it's obvious what each topic carries and who publishes it, and it supports useful subscriptions:

SubscriptionReceives
home/garage/#Everything from the garage
home/+/temperatureEvery room's temperature
home/+/statusAvailability of every device
home/+/+/setEvery 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.

Diagram: an MQTT topic tree from place to device to what, with example payloads and which topics are retained

The Hard Rules

These come from the MQTT specification or cause real bugs:

RuleWhy
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 topicsThey're wildcards, valid only in subscriptions
Topics are case-sensitivehome/Garage and home/garage are different topics: use lowercase everywhere
Avoid spaces and special charactersLegal, but painful in shells, URLs and ACL files. Use - or _
No secrets or personal data in topicsTopic names appear in logs, debug tools and ACL files

Separate Readings, Commands, State and Status

Four kinds of message, four kinds of topic:

KindExamplePublished byRetain?
Reading (telemetry)home/garage/temperatureDeviceUsually yes: newcomers see the current value
Commandhome/garage/door/setDashboard, automationNo: replaying commands is dangerous
Reported statehome/garage/door/stateDevice, after actingYes
Availabilityhome/garage/statusDevice; broker via Last WillYes

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.

Diagram: a dashboard sends a command on the set topic and the device reports the real result on the state topic

One Value per Topic, or JSON?

One value per topicOne JSON topic
Examplehome/garage/temperature → 21.4home/garage/climate → {"temperature":21.4,"humidity":58}
Easy to use in dashboardsYes, connect directlyNeeds a JSON parse step
Wildcard queries (+/temperature)YesNo
Readings stay in syncSeparate messagesOne message, one timestamp
Adding a new fieldNew topicJust 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/+/temperature matches home/garage/temperature but not home/garage/rack/temperature.
  • # matches any number of levels and must be last: home/garage/# matches everything under the garage, including home/garage itself.

Subscribe as narrowly as the consumer needs: a temperature logger subscribed to home/# also receives every command and status message.

Diagram: which published topics match home/+/temperature and home/garage/#

Conventions Used by Popular Tools

If your devices share a broker with these, follow or at least avoid colliding with their topics:

SystemTopic convention
Home Assistant (MQTT discovery)Config under homeassistant/<component>/<object_id>/config; HA's own status on homeassistant/status
Tasmotacmnd/<device>/POWER commands, stat/<device>/POWER state, tele/<device>/SENSOR telemetry, tele/<device>/LWT availability
Zigbee2MQTTzigbee2mqtt/<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

MistakeProblemBetter
/home/garage/tempEmpty first levelhome/garage/temperature
Home/Garage/TempCase mismatches between devicesAll lowercase
esp32-1/dataSays nothing about place or contenthome/garage/climate
home/garage/lamp for both commands and stateDevice and dashboard echo each other in a loop.../lamp/set and .../lamp/state
home/living room/lampSpace breaks shells and ACL fileshome/livingroom/lamp or living_room
Renaming topics in a firmware updateDashboards and automations silently stopKeep 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:

Output
# 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:

  1. Update the firmware to publish both the old and the new topic for a while.
  2. Move each consumer (Node-RED flows, Home Assistant entities, databases) to the new topic.
  3. Watch the old topic with mosquitto_sub -t 'old/topic/#' -v until nothing reads it.
  4. 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

  1. Lowercase, /-separated, no leading /, no spaces.
  2. General to specific: place, device, then what.
  3. Separate .../set commands from .../state reports.
  4. A .../status topic per device with a Last Will.
  5. Retain readings, state and status; never commands.
  6. Same depth for the same kind of data, so wildcards line up.
  7. Units in names or JSON keys (temperature_c).
  8. 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:

Output
site/workshop/esp32-01/status
site/workshop/esp32-01/temperature_c
site/workshop/esp32-01/humidity_pct
site/workshop/esp32-01/config/sample_interval_s

Use 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:

config.json
{
  "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:

terminal
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

Continue learning

Related articles

All articles

Signal In

Built from what makers search for

The lookups piling up in SolderHub's search bar every day shape what we publish next — new component pages, board guides, and firmware notes, sent out as they go live.

By subscribing you agree to our Privacy Policy. Unsubscribe anytime.