Skip to content

WebSocket vs MQTT: Web Apps vs IoT Messaging

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.

FeatureMQTTWebSockets
Protocol ModelPub/Sub messagingPoint-to-point connection
Target EnvironmentIoT devicesWeb browsers & servers
Message RoutingTopic-basedDirect connection
QoS Levels0, 1, 2 (delivery guarantees)Application-defined
Browser SupportVia WebSocket bridgeNative (99%+)
Message Retention✅ Built-inApplication-defined
Will Messages✅ Last Will and Testament❌ Manual implementation
OverheadMinimal (2-byte header)Low (2-14 byte frames)
Binary Efficiency✅ Optimized✅ Supported
Connection StateSession persistenceStateful during connection
Typical UseSensors, IoT devicesWeb apps, real-time UI

MQTT (Message Queuing Telemetry Transport) is a lightweight pub/sub protocol designed for constrained devices:

  1. Broker-Centric: All communication goes through a central broker
  2. Topics: Hierarchical message routing (e.g., home/livingroom/temperature)
  3. QoS Levels: Delivery guarantees from fire-and-forget to exactly-once
  4. Retained Messages: Last known good value for new subscribers
  5. Will Messages: Notification if client disconnects unexpectedly
// MQTT in browser via WebSocket transport
const 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 }
);

WebSockets provide direct, bidirectional communication between client and server:

// WebSocket client for an IoT dashboard
const 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);
};

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

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

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

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

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

The two protocols often work together in IoT platforms:

// Bridge: forward MQTT messages to WebSocket clients
const 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 forward
mqttClient.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);
}
});

Many MQTT brokers support WebSocket transport, enabling browser access:

// MQTT directly in browser via WebSocket transport
const client = mqtt.connect('wss://broker.example.com:8083/mqtt');
// This is still MQTT protocol, just transported over WebSocket
client.subscribe('sensors/+/data');
client.publish('commands/device', 'restart');
import paho.mqtt.client as mqtt
import time
import 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_connect
client.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)

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

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.

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.

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.