SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
  • Long Polling
  • Server-Sent Events (SSE)
  • WebSockets
  • Webhooks
  • WebRTC
  • Short Polling
  • Push Notifications
  • MQTT
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/APIs and Communication/Real-Time Communication

MQTT

A tiny publish-subscribe protocol for IoT devices with weak batteries and weak networks.

โฑ 13 min readIntermediateHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

MQTT is a very small publish/subscribe protocol made for devices with weak batteries and weak networks, such as sensors, meters and smart-home gadgets.

  • Devices do not talk to each other. They all talk to one broker, which passes messages on.
  • A message goes to a topic like home/kitchen/temp. Anyone who subscribed to that topic gets it.
  • You choose how careful delivery is with three levels, QoS 0, 1 and 2: cheap and risky, or safe and costly.

02Concept: What is it?

MQTT (often read as "em-queue-tee-tee") runs on top of a normal TCP connection. A device opens one connection to the broker and keeps it open. Over that single connection it can both publish messages and subscribe to topics. The fixed header of a message can be as small as 2 bytes, which matters when every byte costs battery and mobile data.

The pieces are simple. A publisher sends a message to a topic (a text path with levels split by slashes). A subscriber tells the broker which topics it cares about, using a filter. The broker matches each message against all filters and forwards copies. The publisher and the subscriber never know about each other.

Publish and subscribe through a broker
๐ŸŒก๏ธSensorpublishes
โ†’โ†“home/kitchen/temp
๐Ÿ“ฎBrokermatches filters
โ†’โ†“forward
๐Ÿ“ฑPhone apphome/+/temp
๐Ÿ“ŠDashboardhome/#
The sensor does not know who listens. The broker does the matching.

Topics and wildcards

Topics have levels separated by /. A subscriber can use two wildcards in its filter. + matches exactly one level, and # matches everything below (and it must be the last character). A publisher always uses a full, exact topic with no wildcards.

FilterMatchesDoes not match
home/kitchen/tempOnly that exact topichome/kitchen/light
home/+/temphome/kitchen/temp, home/garage/temphome/kitchen/oven/temp (two levels in the middle)
home/#Everything under home, and home itselffarm/field1/soil
#Every topic on the brokerNothing is left out (careful, this can be a lot)
๐Ÿง MQTT is built for bad networks
Phones go through tunnels and sensors sit behind weak signals. MQTT expects connections to drop. It has keep-alive pings, saved sessions and a last will message so that both sides can recover without losing track of what happened.

03Real-Life Example

๐ŸตThe Notice Board in a Village Hall
A village hall has a big notice board with sections: "Bake sale", "Football", "Music". Anyone can pin a note under a section without knowing who will read it. People who care about football look at the football section. Someone who wants everything checks the whole board. The caretaker (the broker) keeps the board tidy. If you ask the caretaker to "keep a copy of the last football note" (a retained message), a new visitor sees it straight away.
Notice board
MQTT
The notice board and the caretaker
The broker
A section such as Football
A topic
Pinning a note
Publishing a message
Choosing which sections to read
Subscribing with a filter
Reading every section at once
The # wildcard
The last note stays pinned for new visitors
A retained message
A note saying โ€œI went home, the lamp is offโ€
A last will message
What QoS means
QoS 0
๐Ÿ“คPUBLISHand forget

At most once. Can be lost.

QoS 1
๐Ÿ“คPUBLISH
โ†•PUBACK

At least once. Can repeat.

QoS 2
๐Ÿ“คPUBLISH / PUBREC
๐Ÿ”PUBREL / PUBCOMP

Exactly once. Most packets.

Each level adds more steps. More steps means more safety and more cost.

04Why Do We Need It?

๐Ÿ”‹Light on battery
A tiny header and one long-lived connection mean less radio time and less power than repeated HTTP requests.
๐Ÿ“ถWorks on weak links
Keep-alive, saved sessions and QoS levels let devices recover from drops without custom code.
๐Ÿ”€Loose coupling
Publishers and subscribers do not know each other. You can add a new listener without touching the sensor.
๐Ÿ“กPush, not poll
The broker pushes news down the open connection, so devices do not ask again and again.
๐ŸŽš๏ธPick your safety
Cheap QoS 0 for a temperature reading every second. QoS 1 or 2 for a command like โ€œopen the valveโ€.
๐ŸงฉSimple and everywhere
A small standard with libraries for almost every language and many ready-made brokers.
When thousands of small devices must send and receive short messages over poor networks, MQTT is a light, forgiving choice.

05Where Do We Use It?

๐ŸญIoT and sensors
Factory machines, weather stations, smart meters and agriculture sensors send readings to a central broker.
๐Ÿ Smart home
Lights, thermostats and door locks listen to topics and publish their state.
๐Ÿš—Vehicles and fleets
Trucks and cars report position and health over mobile networks that come and go.
๐Ÿ’ฌMobile messaging
Light push-style messages to phones where saving battery and data matters.
โ˜๏ธCloud IoT services
Managed services such as AWS IoT Core speak MQTT, so devices connect without you running a broker.
๐ŸงชTelemetry pipelines
A broker can feed a stream or a database, so device data can be stored and analysed later.

06Types / Parts / How It Works

The three QoS levels

LevelNameHow it worksRiskCost
QoS 0At most onceSend once. No confirmation.A message can be lost1 packet. Cheapest.
QoS 1At least onceSend, wait for PUBACK, repeat if it does not come.A message can arrive twice2 packets (more with retries)
QoS 2Exactly onceA 4-step handshake: PUBLISH, PUBREC, PUBREL, PUBCOMP.No loss, no duplicates4 packets. Slowest.
๐Ÿ“The lower level wins
The publisher chooses a QoS when it sends, and the subscriber chooses a QoS when it subscribes. For the last leg from the broker to the subscriber, MQTT uses the lower of the two. A QoS 2 message sent to a QoS 0 subscriber is delivered at QoS 0.

Features that help on bad networks

FeatureWhat it doesWhy it helps
Retained messageThe broker keeps the last message of a topic and gives it to every new subscriber at once.A new dashboard shows the current state straight away, without waiting for the next reading.
Last Will and TestamentA message the broker publishes for you if your connection dies without a clean goodbye.Others learn that a device went offline (for example โ€œdevice 7: offlineโ€).
Persistent sessionThe broker remembers your subscriptions and queues messages for you while you are away (QoS 1 and 2).A device that reconnects after a gap catches up without resubscribing.
Keep-aliveThe client pings if it has been quiet. If the broker hears nothing, it closes the connection.Dead connections are noticed and cleaned up.
How the QoS 2 handshake keeps it exactly once
๐Ÿ“คSender
โ†’โ†“1 PUBLISH
๐Ÿ“ฅReceiverstores it
โ†2 PUBREC
โ†’โ†“3 PUBREL
โœ…Receiverreleases once
โ†4 PUBCOMP
Sender steps Receiver steps
The receiver holds the message until PUBREL, so a repeated PUBLISH cannot be delivered twice.
VisualizerTopic wildcards and QoS on a lossy linkPick a topic and see which subscribers match. Then switch to the lossy link and compare QoS 0, 1 and 2: lost messages, duplicates and the number of packets used.
Publish to this topic
Quality of service
Network link

QoS 1, at least once: the sender repeats the PUBLISH until it sees a PUBACK. Nothing is lost, but a lost PUBACK causes a duplicate.

Broker: 10 messages are published to home/kitchen/temp. Each row is one subscriber with its filter.
Thermostat apphome/+/tempgot 10/10 ยท 8 duplicate ยท 40 packets
Home dashboardhome/#got 10/10 ยท 9 duplicate ยท 41 packets
Kitchen lamphome/kitchen/lightdoes not match, receives nothing
Farm sensor board+/+/soildoes not match, receives nothing
Audit logger#got 10/10 ยท 5 duplicate ยท 35 packets
Subscribers hit
3
of 5
Delivered
30
of 30 wanted
Duplicates
22
extra copies
Lost
0
never arrived
Packets sent
116
the cost of safety
QoS 1 delivered everything, but 22 message(s) arrived twice (a PUBACK was dropped, so the sender repeated the PUBLISH). Your handler must cope with duplicates.

Wildcards follow the real MQTT rules: + matches exactly one level and # matches everything below (and the parent level itself, so home/# also matches home). The loss pattern is a fixed list, not random, and the message counts are illustrative. In real MQTT the QoS used is the lower of the publisher's and the subscriber's level.

07How to Use It / Steps / Implementation

Using MQTT well

  1. 1
    Design the topic tree first
    Use clear levels from general to specific, such as site/building/room/device/metric. Good names make wildcard filters easy.
  2. 2
    Do not put data in the topic that belongs in the message
    Keep the topic for who and what. Keep the readings in the payload (often JSON or a compact binary format).
  3. 3
    Choose QoS per message type
    QoS 0 for frequent readings where the next one replaces a lost one. QoS 1 for events that must arrive, with an idempotent handler. QoS 2 only when duplicates truly hurt.
  4. 4
    Set a last will and use retained status
    Publish โ€œonlineโ€ as a retained message when you connect, and set the last will to โ€œofflineโ€. New subscribers then always see the current state.
  5. 5
    Use a persistent session for devices that sleep
    Give each device a stable client ID and keep the session, so it gets queued commands when it wakes up.
  6. 6
    Secure the connection
    Use TLS, give each device its own credentials or certificate, and restrict each device to the topics it needs.
  7. 7
    Watch broker health
    Track connected clients, message rates and dropped messages. A broker is a single hub, so plan for clustering or failover.
A tiny example (illustrative, using a common client style)
# subscribe to every temperature in the house
subscribe  filter="home/+/temp"   qos=1

# publish a reading
publish    topic="home/kitchen/temp"  payload={"c":21.5}  qos=0  retain=false

# connect with a last will
connect    clientId="sensor-7"  will.topic="devices/sensor-7/status"  will.payload="offline"  will.retain=true
๐Ÿ’กWildcards are for subscribers only
You can subscribe to home/#, but you cannot publish to it. A publish needs a full topic. Also avoid subscribing to # in production, since you receive everything.

08Key Terms to Know

TermMeaning in easy words
BrokerThe server that receives all messages and forwards them to matching subscribers
PublisherA client that sends messages to a topic
SubscriberA client that asks the broker for messages that match a topic filter
TopicA text path with levels split by slashes, such as home/kitchen/temp
Wildcard+ matches one level and # matches all the levels below
QoSQuality of Service: the delivery guarantee (0, 1 or 2)
Retained messageThe last message on a topic, stored by the broker for new subscribers
Last Will and TestamentA message the broker publishes if a client disconnects without saying goodbye
Persistent sessionSubscriptions and queued messages that the broker keeps while the client is away
Keep-aliveA timer and ping that lets the broker notice a dead connection
Client IDThe name that identifies a client to the broker and ties it to a session

09Pros, Cons and Trade-offs

โœ… Pros
  • Tiny overhead, good for battery and mobile data
  • Handles flaky connections with sessions and keep-alive
  • Simple publish/subscribe with flexible wildcards
  • Three delivery levels to match the need
  • Many brokers and client libraries
โš ๏ธ Cons
  • A central broker is a hub that must be kept alive and scaled
  • Not made for big files or rich request/response calls
  • QoS 2 is slow and chatty
  • Topic design mistakes are hard to undo later
  • No built-in message replay or long history like a log system

Trade-offs

ChoiceWe gainWe lose
QoS 0Fewest packets and lowest powerLost messages go unnoticed
QoS 1No loss, simple to doDuplicates, so handlers must be idempotent
QoS 2No loss and no duplicatesMore packets, more delay, more state on the broker
Persistent sessionDevices catch up after a gapThe broker stores more, and old sessions need cleaning up
Retained messagesNew subscribers see the latest state at onceA stale value can mislead if a device died silently (pair it with a last will)
MQTT vs HTTP pollingPush, small, long-lived connectionNeeds a broker, and some firewalls dislike long-lived connections

MQTT compared with its neighbours

MQTTHTTPAMQP (RabbitMQ)
StylePublish/subscribeRequest/responseQueues, exchanges and routing
WeightVery lightHeavier headersRicher, heavier
Best forDevices, telemetryWeb and APIsBusiness messaging between services
Server pushBuilt inNeeds tricks (SSE, WebSockets)Built in

10Common Problems and Mistakes

Common mistakes

  1. Using QoS 2 everywhere. It adds delay and load. Most telemetry does not need it.
  2. Forgetting duplicates with QoS 1. A repeated PUBLISH can cause a double action, such as opening a valve twice.
  3. Reusing a client ID. Two devices with the same ID keep kicking each other off the broker.
  4. Subscribing to # in production. It receives every message, which can overload a client.
  5. No last will. Other systems keep trusting the last reading of a dead device.
  6. Open brokers with no authentication. Anyone on the network can read and send messages.
  7. Huge payloads. MQTT is for small messages. Send a link to big files instead.

Things to watch

๐ŸŒฉ๏ธReconnect storms
After a broker restart every device reconnects at once. Use random delay before reconnecting.
๐ŸงณSession build-up
Persistent sessions for devices that never return fill the broker. Set an expiry.
๐ŸงฑSingle broker
One broker is a single point of failure. Use a cluster or a managed service.
๐Ÿ•ณ๏ธOrder and scale
Ordering is kept per connection, not across a big cluster. Do not assume global order.

11Real-World Examples

๐ŸฆŸMosquitto
A popular open-source broker, often used for small setups and testing.
๐Ÿ•ธ๏ธEMQX and HiveMQ
Brokers built to run in clusters and hold very many device connections.
โ˜๏ธAWS IoT Core
A managed service that accepts MQTT from devices and routes messages to other cloud services.
๐Ÿ Home automation
Many smart-home hubs and open-source home tools use MQTT for sensors and switches.
๐Ÿ›ฐ๏ธIndustrial telemetry
Plants send machine data to a central system, often using MQTT-based formats.
๐Ÿ“ฒMobile apps
Apps use MQTT-style messaging to receive small live updates with low battery cost.
๐Ÿ“Note
The product names are examples. Features and limits differ between brokers and versions, so check the documentation of the one you use.
Mini case: a greenhouse
๐ŸŒฑSoil sensorsQoS 0, every 10 s
โ†’โ†“
๐Ÿ“ฎBrokercluster
โ†’โ†“
๐Ÿง Controllerwatering rule
โ†’โ†“QoS 1 command
๐ŸšฟValveidempotent
Cheap readings use QoS 0. The watering command uses QoS 1 with an idempotent handler.

12Related Topics to Read Next

Pub/Subโ†’

MQTT is a publish/subscribe protocol with a broker in the middle.

Message Brokersโ†’

The broker is the heart of MQTT, like RabbitMQ or Kafka in other systems.

Delivery Semanticsโ†’

QoS 0, 1 and 2 map to at most once, at least once and exactly once.

WebSocketsโ†’

Another long-lived connection for pushing data, often used by browsers.

TCP vs UDPโ†’

MQTT runs on TCP, which gives ordered and reliable bytes.

Idempotencyโ†’

QoS 1 can repeat a message, so handlers should be safe to run twice.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • โœ”What: a tiny publish/subscribe protocol over TCP with a broker in the middle.
  • โœ”Topics: levels split by /. + is one level, # is everything below (subscribers only).
  • โœ”QoS 0: at most once, can be lost. QoS 1: at least once, can duplicate. QoS 2: exactly once, 4 steps.
  • โœ”Retained: the last message is kept for new subscribers.
  • โœ”Last will: the broker announces a device that vanished.
  • โœ”Session: persistent sessions queue messages for devices that sleep.
  • โœ”Watch: reconnect storms, broker as a single hub, open access, # subscriptions.
  • โœ”One line: โ€œA small noticeboard for devices: pin a note to a topic, and whoever follows it gets a copy.โ€
โ† Previous
Push Notifications
Next โ†’
Message Queues