'Is there a pattern for synchronizing message queue communication to request/response manually?
Let's imagine I have a REST API with an endpoint /api/status
. When this endpoint is accessed, the API sends a message to a message queue requesting the status of some other service.
Then in reply, the service sends a message with its status to a queue on which the REST API listens. So it's single message to request the status and single reply message.
My question is: Is there a design pattern for converting the asynchronous nature of this approach to a synchronous one in the API? In other words: Is there a pattern that the GetStatus(...)
method in the pseudo code below can implement to synchronize the getting of the status with communication over multiple message queues or even pub/sub systems.
var statusRequestMsg = "get_status";
var statusResponseMsg = GetStatus(statusRequestMsg);
I know how to solve this in code but I was curious if there is a design patter that introduces a common approach.
I googled a lot in search for that but the only think that I found was a very technical explanation of an approach to do that in this article: A Communication Model to Integrate the Request-Response and the Publish-Subscribe Paradigms into Ubiquitous Systems
Please note that I understand that this is not the perfect API design and that there are better ways to implement the example. I've created the above example to help me illustrate my question. Also I understand that some AMQP impl. (like RabbitMQ) provide a way to synchronize MQ communication to request/response style.
Thanks in advance.
Solution 1:[1]
Have you considered something like this:
- Request comes in
- Create a correlation id
- Send correlation id to other service as part of message sent via queue
- Begin polling for that id in some data store (say Redis)
Time elapses...
- Send correlation id back to originating service along with result of request in a message sent via queue
- Worker reading queue sets value of correlation id in data store to result of asynchronous request
- Polling discovers result and returns in as response to request
Would that work?
Solution 2:[2]
Microsoft calls it Async Request Reply pattern and uses a solution that polls over HTTP: https://docs.microsoft.com/en-us/azure/architecture/patterns/async-request-reply
I imagine it should be possible to avoid polling by subscribing to updates for a key. For example, it's possible to subscribe to updates to a single key in Redis with keyspace notifications (The page mentions two caveats: that "all the events delivered during the time the client [is] disconnected are lost" and "events' notifications are not broadcasted to all nodes".)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | aridlehoover |
Solution 2 | Alexander Taylor |