MQTT

Protocols & Transport Security Notes Jan 6, 2025 JAVASCRIPT

Definition

You know how sometimes you need to send a text message when you have terrible cell reception? You need something that works even with one bar of signal. MQTT was designed with exactly this mindset - it’s a messaging protocol built from the ground up to work in harsh conditions where bandwidth is precious, connections are unreliable, and devices have limited power and memory.

MQTT stands for Message Queuing Telemetry Transport, but the name doesn’t really capture what makes it special. Think of it as the “whisper network” of the Internet of Things. It’s incredibly lightweight - the smallest MQTT message is just 2 bytes, compared to hundreds of bytes for typical HTTP requests. This efficiency matters enormously when you have thousands of battery-powered sensors that need to communicate regularly without draining their batteries or overwhelming your network.

The protocol follows a publish-subscribe pattern with a central broker. Devices publish messages to “topics” (like channels), and other devices subscribe to the topics they care about. A temperature sensor might publish to “home/living-room/temperature,” and both your thermostat app and your home automation system can subscribe to that topic. Neither the sensor nor the subscribers need to know about each other - the broker handles all the routing. This design is perfect for IoT scenarios where you might have devices going offline, networks cutting out, and resources being extremely limited.

Example

MQTT quietly powers much of the connected world around you. Here’s where it’s working behind the scenes:

Smart Home Devices: When you use Amazon Echo, Google Home, or Apple HomeKit, MQTT often handles the communication. Your smart lights publish their status to topics, and the voice assistant subscribes to know what’s on or off. When you say “turn off the living room lights,” a command publishes to the right topic, and every subscribed light responds instantly.

Connected Cars: Modern vehicles are packed with sensors, and many automakers use MQTT to handle telemetry. Tesla, for example, collects data from thousands of sensors per vehicle - tire pressure, battery status, driving patterns. MQTT’s efficiency means this data can stream continuously without overwhelming cellular connections or draining the car’s systems.

Healthcare Wearables: Your Fitbit or Apple Watch tracking heart rate, steps, and sleep? These devices often use MQTT-like protocols to sync efficiently. When your watch detects an unusual heart rate, it needs to alert your phone immediately, even on a weak Bluetooth connection. MQTT’s quality-of-service guarantees help ensure critical health alerts always get through.

Industrial Manufacturing: Factories use MQTT to monitor thousands of machines in real-time. Each machine publishes metrics - temperature, vibration, output counts - to specific topics. If a machine starts showing signs of failure, the message gets through immediately so maintenance can prevent costly breakdowns.

Agriculture Tech: Smart farms deploy hundreds of soil moisture sensors, weather stations, and irrigation controllers across vast fields. MQTT handles communication efficiently even in rural areas with poor connectivity. When a soil sensor detects low moisture, it publishes to a topic that triggers the irrigation system - all with minimal bandwidth.

Analogy

The Efficient Radio Dispatch System: Imagine a large taxi company before smartphones, using radio dispatch. Drivers tune to specific channels (topics) based on their zones. When a dispatcher receives a pickup request for Zone 5, they broadcast only on the Zone 5 channel - drivers in other zones don’t hear the chatter. The system uses short, standardized codes (“10-4”) instead of long sentences to save airtime. That’s MQTT: efficient channel-based communication designed to work even with static-filled radio connections.

The Classroom Announcement System: Think about a school’s PA system, but smarter. Instead of blasting every announcement to every room, teachers subscribe to the channels they need - “fire-safety,” “grade-5-activities,” “cafeteria-menu.” The office (broker) routes each announcement only to the rooms that subscribed. A temperature sensor in the gym (publisher) can alert just the HVAC system (subscriber) without bothering anyone else.

The Postal Box System in Apartment Buildings: In large apartment complexes, you have your personal mailbox that receives only mail addressed to you. The mailroom (broker) sorts incoming mail (messages) and places it in the right boxes (topics). You don’t have to wait at the door for deliveries - the mail waits in your box until you check it. Multiple services can deliver to your box (multiple publishers), and you receive everything without knowing who sent what.

The Bird Watcher’s Network: Imagine a network of bird watchers spread across a nature reserve. Each watcher has a low-power radio and reports sightings: “spotted eagle at sector 7.” Other watchers can tune their radios to “sector-7” or “eagle-sightings” channels. Even with weak radio signals and brief transmissions, the important information gets through. The central station (broker) relays messages to whoever tuned in to the right channels.

Diagram

flowchart TB
    subgraph Publishers
        P1[Temperature Sensor]
        P2[Motion Sensor]
        P3[Door Sensor]
    end

    subgraph Broker[MQTT Broker]
        T1[home/temp]
        T2[home/motion]
        T3[home/door]
    end

    subgraph Subscribers
        S1[Mobile App]
        S2[Dashboard]
        S3[Automation System]
    end

    P1 -->|publish| T1
    P2 -->|publish| T2
    P3 -->|publish| T3

    T1 -->|subscribe| S1
    T1 -->|subscribe| S2
    T2 -->|subscribe| S2
    T2 -->|subscribe| S3
    T3 -->|subscribe| S1
    T3 -->|subscribe| S3

    subgraph QoS[Quality of Service Levels]
        Q0[QoS 0: At most once
Fire and forget] Q1[QoS 1: At least once
Acknowledged delivery] Q2[QoS 2: Exactly once
Guaranteed single delivery] end

Code Example


// Node.js MQTT client
const mqtt = require('mqtt');

const client = mqtt.connect('mqtt://broker.example.com', {
  clientId: 'sensor_123',
  username: 'device',
  password: 'secret'
});

client.on('connect', () => {
  // Subscribe to topic
  client.subscribe('devices/+/commands');

  // Publish sensor data
  client.publish('sensors/temperature', JSON.stringify({
    value: 22.5,
    unit: 'celsius',
    timestamp: Date.now()
  }), { qos: 1 });
});

Security Notes

SECURITY NOTES

CRITICAL: MQTT is IoT protocol. Security requires authentication, encryption, and authorization.

MQTT Characteristics:

  • Lightweight: Minimal bandwidth for IoT
  • Publish/Subscribe: Topic-based messaging
  • QoS levels: 0 (fire-and-forget), 1 (at least once), 2 (exactly once)
  • Persistent: Can retain messages

Security Features:

  • Username/password: Basic authentication
  • TLS/SSL: Encryption for communication
  • ACLs: Access control by topic
  • Client ID: Unique identifier per client

Best Practices:

  • TLS mandatory: Always use TLS for MQTT
  • Strong credentials: Strong username/password
  • ACL enforcement: Restrict topic access
  • Monitoring: Monitor broker access
  • Rate limiting: Limit publish frequency

Standards & RFCs