MQTT tutorial

Learn MQTT by following one message end to end

Connect a client, publish telemetry, subscribe to a topic, then make the design production-ready with deliberate QoS, session, retained-message, and security choices.

The model

MQTT in four concepts

MQTT keeps clients small by moving connection management, topic matching, and delivery coordination into the broker.

Broker

Accepts client connections, evaluates subscriptions, and routes each published message to matching consumers.

Client

Any sensor, gateway, service, browser, or application that connects, publishes, subscribes, or does all three.

Topic

A hierarchical route such as factory/line-1/motor-7/temperature that keeps publishers independent from subscribers.

Message

A payload plus delivery settings such as QoS, retain, expiry, and MQTT 5 properties.
First working flow

Publish and receive your first message

Use two terminals so you can see the broker decouple the publishing client from the subscriber.

  1. 01

    Start the subscriber

    Connect with a unique client ID and subscribe before publishing so the first live message is visible.

  2. 02

    Publish telemetry

    Send a small JSON payload to the exact topic using the same broker and compatible credentials.

  3. 03

    Verify delivery

    Confirm topic, payload, QoS, timestamp, and client identity before adding wildcards or retained state.

Terminal 1 · Subscribe
mosquitto_sub \
  -h "$MQTT_HOST" -p 8883 \
  -u "$MQTT_USERNAME" -P "$MQTT_PASSWORD" \
  -i "tutorial-sub-01" \
  -t "factory/line-1/motor-7/telemetry" \
  -q 1 -v
Terminal 2 · Publish
mosquitto_pub \
  -h "$MQTT_HOST" -p 8883 \
  -u "$MQTT_USERNAME" -P "$MQTT_PASSWORD" \
  -i "tutorial-pub-01" \
  -t "factory/line-1/motor-7/telemetry" \
  -q 1 \
  -m '{"temperature":61.8,"vibration":2.1}'
Delivery semantics

Choose QoS from the business consequence

A higher QoS adds handshakes and state. It does not automatically make the application correct.

QoS level
QoS levelDeliveryGood fitTrade-off
QoS 0At most once; no acknowledgmentFrequent telemetry where the next reading replaces the lastLowest overhead, but loss is possible
QoS 1At least once; duplicates are possibleState changes, alerts, and commands with idempotent consumersAcknowledgment and deduplication are required
QoS 2Exactly once at the MQTT protocol layerRare workflows with a measured exactly-once requirementFour-part handshake, more state, and more latency
Topic contract

Design topics for ownership and authorization

A topic tree becomes an API. Keep it stable, document each level, and make permission boundaries obvious.

A predictable topic hierarchy
factory/{site}/{line}/{device}/{channel}

factory/shanghai/line-1/motor-7/telemetry
factory/shanghai/line-1/motor-7/state
factory/shanghai/line-1/motor-7/command

# Subscribe to telemetry from one line
factory/shanghai/line-1/+/telemetry

# Reserve broad multi-level subscriptions for trusted services
factory/shanghai/#
Use stable identifiers; keep display names in the payload.
Separate telemetry, state, and command directions.
Never place secrets or personal data in topic names.
Grant wildcard access only where the device role needs it.
Version breaking contracts deliberately instead of renaming ad hoc.
Document payload schema, units, cadence, QoS, and ownership.
Production check

Move from a successful demo to a reliable system

One identity per device

Unique credentials make revocation, rotation, audit, and incident scope manageable.

Intentional sessions

Choose session expiry, keepalive, reconnect backoff, and offline queues from expected network behavior.

Measured capacity

Load test connections, subscriptions, fan-out, payload size, retained state, and reconnect storms.

Observable operations

Track connection failures, authorization denials, queue depth, delivery latency, and credential changes.

MQTT tutorial FAQ

Does MQTT work without a broker?

The standard MQTT publish-subscribe model uses a broker to accept connections, match topics, and deliver messages. Clients do not discover or route directly to one another.

Which MQTT QoS should I choose first?

Start with QoS 0 for frequent replaceable telemetry and QoS 1 for state changes or commands that must arrive. Use QoS 2 only after measuring the cost and proving an exactly-once requirement.

Is a retained message the same as message history?

No. A retained topic stores only its latest retained value for new subscribers. Use a database or stream store when consumers need history, queries, or replay.

What are ports 1883 and 8883 used for?

Port 1883 commonly carries plain MQTT over TCP. Port 8883 commonly carries MQTT over TLS. Production clients should validate certificates and use encrypted transport.