MQTT vs WebSocket: they’re both realtime communication protocols but each is designed to do a different job. If you’re building software that needs realtime client-server communication, the difference between MQTT and WebSocket might not be clear at first.
On this page, we’ll look at the design choices behind both MQTT and WebSocket, and what that means for the use cases they suit best. And, at the risk of giving away the ending, we’ll see that MQTT and WebSocket aren’t competitors. In fact, they can both serve complementary roles within your application infrastructure.
To better understand why we need protocols such as MQTT and WebSocket, let’s start by briefly defining the problem.
Realtime communication needs the right tools
Realtime communication can take a few different forms. But, generally, realtime means that:
From the perspective of end-users, everything happens instantaneously
Data is exchanged as it happens, rather than batching messages together
There’s another factor to bear in mind, too. Most realtime communication is two-way.
Now, consider HTTP. Its client-initiated request-response model means that it is effectively uni-directional. HTTP long polling gives us a way to achieve a form of two-way communication - but then HTTP’s relatively bulky headers add enough latency that it feels sluggish compared to truly realtime protocols. The good news is that there are a number of dedicated realtime options to choose from. Depending on what you need to do, MQTT and WebSocket have probably already come up on your radar.
MQTT and WebSocket are built for different use cases
Before we look in detail at MQTT and WebSocket, we should set out some of the technical reasons why we even need more than one realtime protocol. As ever, it’s all about the tradeoffs. For example, quality of service guarantees add overhead and overhead adds latency. In some cases, you absolutely must know that a message has reached its destination. In others, speed is more important than quality of service.
Although this list isn’t exhaustive, here are some of the characteristics that separate realtime protocols from one another:
Messages vs streaming: Is it designed to deliver individual messages, such as a temperature reading from an IoT device? Or is it best suited to a constant stream of bits, such as the video feed from a security camera?
Message guarantees: Can you be sure everything you send will arrive at its destination? Is there a risk it will arrive out of order or more than once?
Messaging pattern: For example, publish/subscribe or message queue.
Overhead: Can it work in constrained network conditions? How much of its own latency does it introduce?
Of course, the significance of these characteristics largely hinges on how they influence the use cases supported by the protocol. With that in mind, let’s see how MQTT and WebSocket compare.
MQTT and WebSocket - the TLDR
If all you need is a quick overview of how MQTT and WebSocket compare, here’s a summary of the differences between the two protocols:
MQTT is a publish/subscribe messaging protocol that offers adjustable quality of service guarantees with low overheads. It requires a centralized message broker and it isn’t natively supported by web browsers directly. Although it typically runs over TCP, you can run MQTT on top of WebSocket, making it available in web browsers so long as your front-end code includes a library or client that can establish an MQTT connection over WebSocket.
WebSocket is a protocol for establishing a persistent, full-duplex connection between a client and server, typically between a web browser and a web server. This connection allows both sides to send messages simultaneously, enabling realtime communication. WebSocket does not offer quality of service guarantees by default.
Here’s a side-by-side comparison of the technical characteristics.
Criteria | MQTT | WebSocket |
---|---|---|
Use cases | MQTT is suitable for low-powered devices with limited CPU and memory, and unreliable, low-bandwidth networks. It’s the go-to protocol for IoT use cases. | WebSockets are suitable for web apps and devices unrestricted (or less restricted) by low bandwidth. Suitable for use cases such as as financial tickers, online multiplayer games, chat, geolocation updates, live polls, etc. |
Message distribution | One-to-many | One-to-one |
Architecture | MQTT uses a publish/subscribe messaging pattern. | Bidirectional, socket-like API. Note: many WebSocket frameworks and libraries add pub/sub capabilities on top of WebSockets. |
Messaging QoS | MQTT has three QoS (quality of service) options: 0 (at most once delivery), 1 (at least once delivery), and 2 (exactly-once delivery). | Raw WebSockets don't provide QoS options. |
Underlying protocol | TCP | TCP |
Messaging mode | Asynchronous, event-based | Asynchronous, event-based |
Message size | Maximum of 256 MB | Theoretically 2^63 bytes per frame |
Secure connections | TLS | TLS |
Message overhead | Minimum of 2 bytes | Minimum of 2 bytes for all messages except masked frames, which have a minimum of 6 bytes. |
Message queuing | MQTT brokers queue messages for all disconnected clients subscribed to a topic. | Raw WebSocket doesn't support message queuing. |
To truly make a decision between MQTT and WebSocket, you’ll need more detail. So, let’s explore both protocols, their advantages, their disadvantages, and the use cases they suit best.
What is MQTT?
MQTT is a lightweight, publish/subscribe messaging protocol designed for environments with limited resources and unpredictable networks. That makes it particularly popular for IoT use cases, for example where low-powered devices need to relay sensor data over potentially unreliable cellular networks. In fact, the protocol’s name gives us a clue to the original designers’ intent, as it stands for Message Queue Telemetry Transport.
However, MQTT isn’t only used in IoT. Millions of people have used it indirectly every day, as it was one of the protocols that powered Facebook Messenger at least as recently as 2014. That use case flexibility means that, although MQTT runs on TCP by default, there are implementations to run MQTT on top of intermediary transports including WebSocket or via gateways to exchange data using technologies such as Bluetooth.
To understand what separates MQTT from other realtime communication protocols, we need to look at how its components fit together.
MQTT architecture
If you already know publish/subscribe as a concept, then the components of MQTT’s architecture will be familiar:
Topics: These act as channels that enable the system to route individual messages to the right clients.
Publisher: A client that pushes messages to one or more topics.
Subscriber: A client that receives messages from one or more topics.
Broker: A central hub that handles administrative tasks, such as client authentication, and also coordinates receiving and sending messages. The broker also manages message storage for quality of service requirements, as well as retained messages, which we’ll look at in the next section.
We can illustrate how MQTT works with a simple example. Let’s say we have a smart heating system in a house. There are three types of component in the system:
Thermostats in each room: they report the temperature in that room by emitting a JSON message on a Temperature topic containing the current temperature reading and a unique identifier for that device.
Heaters in each room: they consume a HeaterControl topic, looking out for messages that give either an On or Off message, along with their unique identifier.
Heating controller: a device where the homeowner can set their desired temperature. It also reads the Temperature topic and sends On or Off messages on the HeaterControl topic, along with the appropriate device identifier, depending on the thermostat readings and the desired temperature.
Let’s say the desired temperature is 19 degrees celsius (roughly 66 degrees Fahrenheit). The living thermostat emits the following to the Temperature topic:
{
"deviceId": "thermostat-12345",
"timestamp": "2024-02-01T10:00:00Z",
"temperature": {
"units": "Celsius",
"value": 18.5
},
"location": {
"room": "Living Room"
}
}
That reports the living room temperature at 18.5 degrees, half a degree below the target. In response, the heating controller sends the following on the HeaterControl topic:
{
"deviceId": "heating-controller-67890",
"command": "on",
"targetDeviceId": "heater-living-room-001",
"timestamp": "2024-02-01T10:01:00Z"
}
Every heater would receive that message, as they all subscribe to the HeaterControl topic, but only heater-living-room-001 would act.
What makes MQTT good for IoT?
MQTT makes two assumptions that make it well suited to IoT needs:
Bandwidth and computing resources will be limited.
Failure is likely to happen.
Typical MQTT messages have a fixed header size of just 2 bytes. That saves bandwidth on the network and also reduces the time clients must spend processing those headers. Initial handshake takes place just once per connection, which also offers savings against HTTP, for example.
When it comes to handling unreliable networks, MQTT offers:
Three levels of quality of service:
At most once delivery: Effectively fire and forget, as the publisher sends a message and then moves onto the next with no knowledge of whether the subscriber(s) received the message.
At least once delivery: The publisher keeps a copy of a message until it receives acknowledgement from the subscriber(s). This introduces latency and puts more load on the client devices, as there’s a return trip to process. Application code on the subscriber-side must deal with duplicates, if they occur.
Exactly once delivery: In this mode, there is a four-step handshake between the publisher and subscriber. First, the publisher sends the message. Then, the subscriber acknowledges receipt, prompting the publisher to send a confirmation of this acknowledgment. This step assures the subscriber that no duplicates will be sent. Finally, the subscriber sends a last acknowledgement, confirming the completion of the exchange and allowing the publisher to verify that the message was successfully received.
Last will and testament (LWT): An MQTT client can specify a message that the broker should send on its behalf in the event that the client disconnects unexpectedly. In our home heating example, the controller might set an LWT message telling all heaters to deactivate in order to avoid overheating.
Retained messages: Publishers can mark certain messages as “retained” on a particular topic. When a client subscribes to that topic, they first receive the retained messages. In our heating scenario, the most recent temperature reading from each device could be marked as retained, meaning that the heating controller gets the most recent reading without having to wait for a new update to be sent.
What are the downsides of MQTT?
Although MQTT is well suited to some IoT applications, it does have its downsides, such as:
Not available in web browsers: If you’re building web applications, MQTT’s biggest hurdle is that it isn’t available in web browsers. There are ways around that, though, as we’ll see in a moment.
Brokers add complexity: The need for a separate piece of infrastructure to sit between clients adds to your maintenance burden, as well cloud and other infrastructure fees.
Publish/subscribe isn’t always suitable: If you need point-to-point messaging or more sophisticated routing, pub/sub might not be the right choice.
So, do those disadvantages mean you shouldn’t use MQTT outside of IoT?
The answer is that you need to balance the advantages of MQTT for your project against the potential downsides.
Facebook Messenger is a good example of this. Its launch in 2011 was the same year that the WebSocket protocol was standardized. But it isn’t just the protocol landscape that was different back then. Most cellphones in use had more in common with low-powered IoT devices than the portable supercomputers we have today. That was especially true for emerging markets where Facebook looked to grow its user base.
So, for Facebook in 2011, an MQTT design targeting low-powered devices running on unreliable networks was a good match for low-end feature phones connected to still developing mobile networks. Would the Meta engineering team make the same choice today, though?
With WebSocket available in all browsers and most mobile devices now much more powerful than they were a decade ago, it could be that MQTT is the wrong choice for non-IoT use cases.
What is WebSocket?
WebSocket is a protocol that enables realtime, full duplex communication over a single, long running TCP connection between a client and a server. Possibly the most important thing to know about WebSocket is that it is available in all major web browsers, as well as having client libraries for most languages and frameworks.
That widespread availability makes WebSocket a straightforward choice for realtime communication in web applications. And, once you have server-side support for WebSocket then it takes relatively little effort to apply the protocol to communication with mobile apps, other devices, and even microservices.
But there’s more to WebSocket than its ubiquity.
What makes WebSocket a good fit for realtime communication?
WebSocket grew out of a need to overcome the constraints of HTTP’s client-initiated request-response model. The web applications we use today need the ability to push data from the server to the browser whenever they choose, not only when the client opens a connection. As such, WebSocket makes a good match for the typical one-to-one connection between a web application and a server.
In particular, the benefits of WebSocket are:
Available almost everywhere: It’s worth repeating that WebSocket is available in every modern web browser, meaning you don’t need to ask users to install anything on their side.
Simple: Once you’ve established a connection, sending messages in either direction is straightforward. That makes it easy to build advanced functionality and other messaging patterns, such as publish/subscribe, on top of WebSocket.
Low-latency: WebSocket message headers tend to be 2 bytes long, which avoids waste and improves the sense of realtime communication.
Are there any downsides to WebSocket?
WebSocket gives you the scope to build the solution that’s right for your needs. The flipside of that is it might not offer some of the functionality you need out of the box. For example:
No message guarantees: WebSocket messages should arrive in the order you send them, thanks to the underlying TCP transport. However, if you want to guarantee that messages arrive at least once, at most once, or exactly once then you have a couple of options. The first is to write that logic yourself. The second is to use a library, such as Socket.IO, or a realtime platform as a service, such as Ably, that builds that functionality on top of WebSocket.
No automatic reconnections: If the connection drops between a client and the server, you’ll need to write your own logic to detect and fix that. That’s the same for many protocols, including MQTT, although some MQTT clients do offer automatic reconnection. Similarly, options like Socket.IO and Ably take care of reconnecting.
When should I use MQTT and when should I use WebSocket?
As we’ve seen, there is a lot of crossover between MQTT and WebSocket. They are both low-latency, continuous communication protocols. However, they both lend themselves to particular use cases.
Before we look at specific use cases, here are some broad guidelines on when to use MQTT and when to use WebSocket:
MQTT: Good for situations where you have low-powered devices running on unreliable networks, especially where you have a one-to-many messaging model. If some of your clients are web browsers, then you’ll need to run MQTT on top of WebSockets.
WebSocket: Good for where you need one-to-one, realtime connections between a server and clients. Especially well suited to applications running in web browsers but available in most other contexts, too.
Let’s illustrate that with some examples.
Criteria | MQTT Over TCP (in Bytes) | MQTT Over WebSocket (in Bytes) |
---|---|---|
Subscription request | 291 | 299 |
Establish connection | 512 | 1161 |
Disconnect | 334 | 418 |
QoS 1 message published / 256 byte | 545 | 555 |
MQTT over TCP vs MQTT over WebSocket. Source: https://go.ably.com/b73
Can I use MQTT with WebSocket?
Earlier we touched on MQTT’s ability to replace TCP with WebSocket as an alternative transport. To implement MQTT over WebSocket you’ll need:
A broker that supports MQTT over WebSocket, such as the open source Eclipse Mosquitto broker.
MQTT.js or another JavaScript client library that runs in the browsers and supports MQTT over WebSocket.
But why would you want to?
In most circumstances, you probably don’t need to use WebSocket as a transport for MQTT. In fact, there’s only one scenario where it makes sense and that is if you want to use web browsers to display data from MQTT sources.
Remember our home heating example? A web-based control panel might display the temperature in each room. One way to do that would be to make the web application a subscriber to the relevant MQTT topic. The benefit would be that such a setup adapts when you add or remove topics. The downside is that you’ll add more latency, as you’re combining the protocol overhead of MQTT and WebSocket, which in turn runs on top of TCP.
An alternative approach would be to have some middleware that reads the MQTT topic and then emits each temperature reading as a message over a WebSocket connection. That also gives you the opportunity for further processing, such as formatting or enriching with complementary data. A potential downside of this method is the ongoing need to tweak the middleware to accommodate any changes or additions to topics as your application evolves.
Enhancing MQTT and WebSocket
We’ve seen that MQTT and WebSocket enable low-latency messaging. Although they have some architectural differences, such as MQTT implementing a publish/subscribe model whereas WebSocket offers persistent point to point connections, there’s enough crossover between the two that they can serve similar use cases.
Both protocols have their advantages but they also leave plenty of room where you’ll need to create your own solutions. For example, WebSocket’s lack of automatic reconnections. However, there’s a more fundamental issue that you’ll face whether you choose MQTT, WebSocket, or some combination of both and that’s infrastructure.
One way to overcome the challenges of building and maintaining your own realtime infrastructure is to use a realtime platform as a service (PaaS). At Ably, our realtime (PaaS) gives you global, low-latency infrastructure to build experiences using WebSocket, MQTT, and other protocols. Here are just some of the advantages of building with Ably:
Quality of service guarantees: While WebSocket lacks guarantees, Ably delivers every message in the right order and exactly once.
A global edge network: Wherever your app’s users are in the world, Ably edge locations ensure less than 65 ms latency right across our network. That also helps ensure application resilience by routing around failure, should a cloud region become unavailable.
Multiple protocols: Ably selects the right protocol for your application’s needs and network conditions, choosing from options such as WebSocket, Server Sent Events, and MQTT.
Resilient delivery: Ably guarantees that messages arrive in order and on time.
99.999% uptime: Ably’s network routes around failure to ensure your application keeps on delivering.
Scale to meet demand: As demand grows, Ably scales from thousands to billions of messages.
Great developer experience whatever your tech stack: With SDKs for more than 25 languages and frameworks, integrations with common tooling, and industry leading documentation, Ably gives you the tools to become productive quickly.
Sign up for your free Ably account and start building today.
Recommended Articles
Socket.IO vs SockJS
Compare realtime libraries Socket.IO and SockJS on performance, scalability, developer experience, and features.
Building dependable realtime apps with WebSockets and .NET
Learn how to build dependable realtime apps that scale with WebSockets and .NET, and the challenges associated with this.
SignalR vs. Socket.IO: which should you choose in 2024?
Discover the differences between SignalR and Socket.IO, their pros and cons, and use cases to see which is right for you.