WebSocket vs MQTT: Web Apps vs IoT Messaging
Quick Summary
Section titled “Quick Summary”MQTT and WebSockets serve different ecosystems: MQTT excels in IoT environments with its lightweight pub/sub model and Quality of Service guarantees, while WebSockets dominate web-based real-time communication. The two often work together, with MQTT handling device communication and WebSockets bridging to web applications.
At a Glance Comparison
Section titled “At a Glance Comparison”| Feature | MQTT | WebSockets |
|---|---|---|
| Protocol Model | Pub/Sub messaging | Point-to-point connection |
| Target Environment | IoT devices | Web browsers & servers |
| Message Routing | Topic-based | Direct connection |
| QoS Levels | 0, 1, 2 (delivery guarantees) | Application-defined |
| Browser Support | Via WebSocket bridge | Native (99%+) |
| Message Retention | ✅ Built-in | Application-defined |
| Will Messages | ✅ Last Will and Testament | ❌ Manual implementation |
| Overhead | Minimal (2-byte header) | Low (2-14 byte frames) |
| Binary Efficiency | ✅ Optimized | ✅ Supported |
| Connection State | Session persistence | Stateful during connection |
| Typical Use | Sensors, IoT devices | Web apps, real-time UI |
How MQTT Works
Section titled “How MQTT Works”MQTT (Message Queuing Telemetry Transport) is a lightweight pub/sub protocol designed for constrained devices:
Core MQTT Concepts
Section titled “Core MQTT Concepts”- Broker-Centric: All communication goes through a central broker
- Topics: Hierarchical message routing (e.g.,
home/livingroom/temperature) - QoS Levels: Delivery guarantees from fire-and-forget to exactly-once
- Retained Messages: Last known good value for new subscribers
- Will Messages: Notification if client disconnects unexpectedly
MQTT Client Example
Section titled “MQTT Client Example”// MQTT in browser via WebSocket transportconst mqtt = require('mqtt');
const client = mqtt.connect('wss://broker.example.com:8083/mqtt', { clientId: 'web-client-' + Math.random().toString(16).substr(2, 8), clean: true, reconnectPeriod: 1000, // Last Will and Testament will: { topic: 'clients/web-client/status', payload: 'offline', qos: 1, retain: true }});
client.on('connect', () => { console.log('Connected to MQTT broker'); client.subscribe('sensors/+/temperature', { qos: 1 });});
client.on('message', (topic, message) => { console.log(`Topic: ${topic}, Message: ${message.toString()}`);});
client.publish('control/lights/living-room', JSON.stringify({ state: 'on', brightness: 80 }), { qos: 1 });import paho.mqtt.client as mqttimport json
def on_connect(client, userdata, flags, rc): print(f"Connected with result code {rc}")
# Subscribe to topics on connect client.subscribe("sensors/+/temperature", qos=1) client.subscribe("commands/device/#", qos=2)
# Publish online status client.publish("devices/device-1/status", "online", qos=1, retain=True)
def on_message(client, userdata, msg): print(f"Topic: {msg.topic}, Message: {msg.payload.decode()}")
# Process based on topic if msg.topic.startswith("sensors/"): process_sensor_data(msg.topic, msg.payload) elif msg.topic.startswith("commands/"): execute_command(msg.topic, msg.payload)
# Create client with Last Willclient = mqtt.Client("python-device")client.will_set("devices/device-1/status", "offline", qos=1, retain=True)
client.on_connect = on_connectclient.on_message = on_message
# Connect to brokerclient.connect("broker.example.com", 1883, 60)
# Start loopclient.loop_forever()How WebSockets Work
Section titled “How WebSockets Work”WebSockets provide direct, bidirectional communication between client and server:
// WebSocket client for an IoT dashboardconst ws = new WebSocket('wss://api.example.com/dashboard');
ws.onopen = () => { console.log('Dashboard connected'); ws.send(JSON.stringify({ type: 'subscribe', topics: ['sensors/+/temperature'] }));};
ws.onmessage = (event) => { const data = JSON.parse(event.data);
switch (data.type) { case 'sensor-update': document.getElementById(data.deviceId).textContent = `${data.value}°C`; break; case 'alert': showNotification(data.message); break; }};
ws.onclose = () => { console.log('Disconnected, reconnecting...'); setTimeout(connectDashboard, 3000);};Key Differences
Section titled “Key Differences”Architecture Model
Section titled “Architecture Model”MQTT: Broker-centric pub/sub
- Decoupled publishers and subscribers
- Central message routing
- Topic-based filtering
- Many-to-many communication
WebSockets: Point-to-point connections
- Direct client-server communication
- No built-in routing
- Application-level message handling
- One-to-one or server-mediated broadcast
Quality of Service
Section titled “Quality of Service”MQTT: Built-in QoS levels
- QoS 0: At most once (fire and forget)
- QoS 1: At least once (acknowledged)
- QoS 2: Exactly once (4-way handshake)
WebSockets: TCP reliability only
- Messages delivered in order
- No built-in acknowledgment
- Application must implement QoS
Connection Handling
Section titled “Connection Handling”MQTT: Session awareness
- Clean/persistent sessions
- Automatic resubscription
- Queued messages for offline clients
- Last Will and Testament
WebSockets: Simple connection model
- No built-in session persistence
- Manual reconnection handling
- No offline message queuing
- Application-level presence
Use Case Analysis
Section titled “Use Case Analysis”When MQTT is the Clear Winner
Section titled “When MQTT is the Clear Winner”✅ IoT and embedded devices:
- Sensor networks
- Smart home devices
- Industrial IoT
- Agricultural monitoring
- Vehicle telemetry
✅ Constrained environments:
- Low bandwidth networks
- Battery-powered devices
- Unreliable connections
- High-latency links
✅ Message patterns:
- One-to-many broadcasting
- Topic-based routing
- Offline message delivery
- Retained state values
When WebSockets are Superior
Section titled “When WebSockets are Superior”✅ Web applications:
- Browser-based real-time apps
- Chat and messaging
- Live dashboards
- Collaborative tools
- Gaming
✅ Interactive features:
- Bidirectional communication
- Low-latency requirements
- Request-response patterns
- Direct server push
✅ Existing web infrastructure:
- HTTP/HTTPS environments
- Web server integration
- CDN compatibility
- Standard web security
Bridging MQTT and WebSockets
Section titled “Bridging MQTT and WebSockets”The two protocols often work together in IoT platforms:
Common Architecture Pattern
Section titled “Common Architecture Pattern”// Bridge: forward MQTT messages to WebSocket clientsconst mqtt = require('mqtt');const WebSocket = require('ws');
const mqttClient = mqtt.connect('mqtt://broker.example.com');const wss = new WebSocket.Server({ port: 8080 });
const wsClients = new Set();
wss.on('connection', (ws) => { wsClients.add(ws); ws.on('close', () => wsClients.delete(ws));
ws.on('message', (raw) => { const msg = JSON.parse(raw); if (msg.type === 'publish') { mqttClient.publish(msg.topic, msg.payload, { qos: 1 }); } });});
// Subscribe to all sensor topics and forwardmqttClient.subscribe('sensors/#');
mqttClient.on('message', (topic, payload) => { const update = JSON.stringify({ type: 'mqtt-message', topic, payload: payload.toString() }); for (const ws of wsClients) { if (ws.readyState === WebSocket.OPEN) ws.send(update); }});MQTT over WebSockets
Section titled “MQTT over WebSockets”Many MQTT brokers support WebSocket transport, enabling browser access:
// MQTT directly in browser via WebSocket transportconst client = mqtt.connect('wss://broker.example.com:8083/mqtt');
// This is still MQTT protocol, just transported over WebSocketclient.subscribe('sensors/+/data');client.publish('commands/device', 'restart');Implementation Examples
Section titled “Implementation Examples”Hybrid IoT Dashboard
Section titled “Hybrid IoT Dashboard”import paho.mqtt.client as mqttimport timeimport random
client = mqtt.Client("temp-sensor-001")client.will_set("devices/temp-sensor-001/status", "offline", qos=1, retain=True)
def on_connect(client, userdata, flags, rc): print(f"Sensor connected: {rc}") client.publish("devices/temp-sensor-001/status", "online", qos=1, retain=True)
client.on_connect = on_connectclient.connect("broker.example.com", 1883, 60)client.loop_start()
while True: temp = 20 + random.uniform(-5, 5) client.publish("sensors/temp-sensor-001/temperature", f"{temp:.1f}", qos=1, retain=True) time.sleep(10)// Browser dashboard receiving sensor dataconst ws = new WebSocket('wss://api.example.com/dashboard');
ws.onopen = () => { ws.send(JSON.stringify({ action: 'subscribe', topics: ['sensors/+/temperature'] }));};
ws.onmessage = (event) => { const data = JSON.parse(event.data);
if (data.topic && data.topic.includes('temperature')) { const el = document.getElementById(`${data.device}-temp`); el.textContent = `${data.value}°C`;
if (parseFloat(data.value) > 30) { showAlert(`High temp on ${data.device}: ${data.value}°C`); } }};
ws.onclose = () => { console.log('Connection lost, reconnecting...'); setTimeout(connectDashboard, 3000);};Choosing the Right Protocol
Section titled “Choosing the Right Protocol”Decision Factors
Section titled “Decision Factors”Choose MQTT when:
- Building IoT device networks
- Need pub/sub messaging patterns
- Require QoS guarantees
- Working with constrained devices
- Need offline message delivery
Choose WebSockets when:
- Building web applications
- Need browser compatibility
- Require bidirectional communication
- Working with existing web infrastructure
- Need simple point-to-point connections
Use both when:
- Building complete IoT platforms
- Need device-to-web communication
- Require different protocols for different parts
- Want to leverage strengths of each
Frequently Asked Questions
Section titled “Frequently Asked Questions”What is the difference between WebSocket and MQTT?
Section titled “What is the difference between WebSocket and MQTT?”WebSockets provide a generic bidirectional communication channel. MQTT is a pub/sub messaging protocol designed for IoT with features like QoS levels, retained messages, and last will. MQTT can run over WebSockets to reach browsers.
Can MQTT run over WebSockets?
Section titled “Can MQTT run over WebSockets?”Yes. MQTT over WebSockets is common for bridging IoT backends with web dashboards. The browser connects via WebSocket, and the MQTT protocol runs on top. Most MQTT brokers like Mosquitto and HiveMQ support this.
Should I use WebSocket or MQTT for IoT?
Section titled “Should I use WebSocket or MQTT for IoT?”Use MQTT for IoT devices — it handles unreliable networks, has QoS message delivery guarantees, and uses minimal bandwidth. Use WebSockets for the web dashboard or mobile app that displays IoT data. Use MQTT over WebSockets to bridge both.
Related Content
Section titled “Related Content”- WebSocket vs HTTP — the underlying protocol both WebSockets and MQTT can transport over
- WebSocket vs Long Polling — compare polling approaches with persistent connections
- Building a WebSocket Application — hands-on tutorial for real-time web features
- WebSocket Security Guide — securing persistent connections with TLS and authentication
- WebSockets at Scale — architecture patterns for high-volume messaging