Search code examples
node.jsmqttscalabilitypm2mosquitto

Routing MQTT protocol to PM2


We have some sort of devices connected to a MQTT Broker (mosquitto), publishing some events. We want to capture all these events through a node application. One simple solution is to create a node app as a client which is connected to MQTT Broker and listen for every event and do an specific job for them. But in scalability point of view, if we want to scale our node app, we have to run multiple instance of our node app and use a PM2 as a load balancer. But the problem is when we create more than one instance, all instances receive the same event and for that specific event, all instances do the same job multiple time as the number of instances we have.

How can we route all MQTT events to PM2 load balancer?


Solution

  • You are possibly approaching the problem the wrong way.

    You want to look at something called Shared Subscriptions. This is new in the MQTT v5 specification (though some brokers implemented a propitiatory versions at MQTT v3).

    Shared Subscriptions tells the broker to distribute in coming messages to collection of clients, only delivering each message to 1 of the group.

    Mosquitto added support for Shared Subscriptions at version 1.6 (but you should make sure you are using the latest 1.6.x release)