RPC style request with MQTT

Viewed 5743

what is the best way to implement RPC style communication (synchronous request/response) with MQTT? Or would it even make sense to put another interface (e.g. REST api) into use?

Thanks in advance!

4 Answers

There are some packages built on top of mqtt that may do what you want. One such example for node.js is mqtt-json-rpc, which mimics RPC over some other WAMP-style stacks like Crossbar.io.

I've been looking for some standard answers for json-rpc over mqtt and how to handle topics. People tend to reference mqtt-json-rpc, which says this:

Internally, remote methods are assigned to MQTT topics.

but if that's the way you do it - one topic per method - then that would be a concurrency problem unless you took two extra precautions: first, the id would have to be guaranteed to be some kind of per-request GUID, and second, the client would have to compare that GUID against its own and discard responses to any requests made by another client. These things are probably a good idea anyway but the jsonrpc 2.0 spec doesn't speak to this and, in fact, use of the transaction ID is encouraged by optional.

I'm thinking that this is the wrong approach and that I should use a per-client topic. The way this would work is using patterns:

topic:  /rpc/${clientID}/request
response: /rpc/${clientID}/response

or topic: /rpc/${clientID}/methodname/request response: /rpc/${clientID}/methodname/response

The RPC server would listen with a wildcard, match that client id, and send the response down the correct pipe. I'm not sure this is a great idea, either, though. My main concern here is that I'm not convinced MQTT brokers are really intended to have such ephemeral topics. Mosquitto for instance lets you turn persistence on globally, but I'm not sure if you send QoS=0 does that bypass persistence, and I'm even less certain how consistent any behavior around this would be across the many different brokers out there.

Related