Message passing in a "star" configuration

I have a Tokyo-based project where incoming connections are managed by tasks created using tokio::spawn and everything works as expected. Now, the code that manages a single connection sometimes need to update or retrieve data from a singleton service and I'd like to model that using message passing.

MPSC is perfect for sending messages to the singleton from other tasks but how am I supposed to get the answers back? My idea would be to pass the sending end of another MPSC with the first message, store it in the service and then use it to send back responses: this means some book keeping in the service and always pass a sort of "id" to retrieve the correct channel for the answer. Or I could just pass the sending end of a oneshot channel with every message that requires an answer. Or there is a better way?

1 Like

Oneshot in the message is the way to go. Requires no "bookkeeping" and is a very efficient type of channel. It's also recommended in one of the official Tokio examples.

4 Likes

Thank you. I somehow did miss the example. :confused:

Send a reply channel (such as a oneshot channel) with the request, and have the service use that channel to deliver the response.