Search code examples
mobilewebsocketmqttbandwidthbattery

Why use MQTT over WebSockets instead of WebSockets?


MQTT is a lightweight protocol with low bandwidth and battery drain. In opposition, Websockets have hight battery drain. But if I need to use MQTT over Websockets, woundn't it be better just to use Websockets in the first place?

I'm designing a mobile application which needs live data and I'm concerned with battery drain.


Solution

  • Generally you only need to use MQTT over web-sockets when your app is running in a browser (because the browser security model does not allow direct TCP connections). The web-socket connection provides a tunnel through which MQTT packets can be passed.

    This means your question is pretty much equivalent to "wouldn't it be better to just use TCP/IP because MQTT traffic flows over a TCP/IP connection".

    Consider the description of MQTT from the spec:

    MQTT is a Client Server publish/subscribe messaging transport protocol. It is light weight, open, simple, and designed so as to be easy to implement. These characteristics make it ideal for use in many situations, including constrained environments such as for communication in Machine to Machine (M2M) and Internet of Things (IoT) contexts where a small code footprint is required and/or network bandwidth is at a premium.

    So if you need a pub/sub protocol to communicate with your mobile app then MQTT may well be a good choice. If you just need a point to point link then using web-sockets (or TCP) directly might be a better solution. The best protocol will depend upon your specific requirements; but do bear in mind that designing your own pub/sub protocol can be a fair amount of work!.

    In terms of battery drain because every use-case is different; it is likely that you could come up with a custom protocol that meets your specific needs and draws a little less power (but bear in mind the effort required to implement this). Note that all of this assumes that your device already has a full TCP network stack; protocols like LoRaWAN, sigfox, NB-IoT, Bluetooth etc will consume less energy than a standard cellular connection (but each have different pros/cons).