← Wiki

Request-Reply in Mule: reserving the order's stock by waiting or by being called back

  • 11 min read
On this page

Code

Before moving on to payment, the order needs the warehouse to reserve the items, and only the warehouse can say whether the reservation worked and under which number. Sending one message and getting another back as the answer is the problem Request-Reply solves. In Mule, the synchronous way is an HTTP Request that waits for the response; the asynchronous way combines an HTTP Request that only delivers the request, an Async scope on the replier’s side and an HTTP Listener that receives the reply later.

The problem

The order service asks to reserve 2 units of SKU-BOOK for order ORD-4101. The warehouse takes a while to reserve (300 ms in the example) and returns a reservationId. There are two ways to wait for it. In the first, the order service stands still until the reply arrives, and the client that called the order service stands still with it. In the second, the order service records that it asked, answers the client right away and receives the reservation when the warehouse finishes; then it needs a place to receive the reply and a way to tell which order it belongs to.

The pattern in the book

The book starts from the fact that messaging goes in one direction only, and asks how an application that sends a message can get a reply from the receiver. The solution is to send a pair of messages, a request and a reply, each on its own channel (Request-Reply). There are two participants: the requestor, which sends the request and waits for the reply, and the replier, which receives the request and responds. The request channel can be point-to-point or publish-subscribe; the reply channel is almost always point-to-point, because it rarely makes sense to broadcast replies that only matter to the one who asked.

The book describes two ways for the requestor to receive the reply. With blocking, it says the requestor acts as a Polling Consumer; the asynchronous callback, where another thread receives the reply, takes the form of an Event-Driven Consumer, a link this page makes, not the book:

  • Synchronous block: one thread sends the request, stays blocked waiting for the reply and then processes it. It is simple, but if the requestor goes down, the blocked thread is hard to re-establish, and waiting on a thread assumes one pending request at a time or a reply channel for that thread alone.
  • Asynchronous callback: one thread sends the request and another listens for replies; when one arrives, the callback re-establishes the context of the one who asked. Several pending requests can share one reply channel, and a requestor that goes down recovers by restarting the reply thread. The cost is the callback itself, which has to re-establish the context.

The diagram redraws the book’s sketch (CC BY 4.0) in the orders scenario:

The Requestor (orders) sends the reservation request to the request channel. The request channel delivers it to the Replier (warehouse). The Replier returns the reservation through the reply channel, and the reply channel delivers the reservation to the Requestor.

In Mule

Synchronous. The HTTP Request operation sends the request, receives the response and passes it to the next component in the flow (Configure HTTP Request Operation). Meanwhile, it blocks the flow’s execution for up to the responseTimeout; without that value, the defaultResponseTimeout of the global configuration applies, 10000 ms (HTTP Connector Reference, Global Configurations). On the warehouse side, the HTTP Listener triggers the flow with the request and returns the HTTP response when the flow ends (Configure HTTP Listener Source). This is the book’s synchronous block, with one difference: in HTTP the request and the reply do not travel on two channels, the response comes back on the same connection.

Asynchronous. The Async scope runs its components at the same time as the main flow, which carries on without waiting; since it is “fire and forget”, the scope’s result does not come back to the main flow (Async Scope). The example’s warehouse uses this to answer 202 right away and send the reservation later, through an HTTP Request to the order service’s reply channel, which is an HTTP Listener. This is the book’s asynchronous callback, with the reply channel fixed in the configuration.

With a broker, the reply channel is a queue. The VM Connector’s Publish Consume operation publishes to a queue and waits for the reply on a temporary reply-to queue that it creates and discards itself (VM Connector Reference). The example does not use it: the project does not simulate a broker with VM queues.

In the synchronous group, the endpoint POST /eip/stock/reservations/sync goes to the http:request, which blocks until the reply; the warehouse answers 201 with the reservation and the endpoint answers 200 with reply and waitedMillis. In the asynchronous group, the endpoint POST /eip/stock/reservations/async writes PENDING to the os:store and the warehouse answers 202. Two paths leave it: the endpoint answers 202 PENDING to the client and, later, asynchronously (dashed line), the warehouse calls POST /eip/stock/reservation-replies, which writes the reservation to the os:store.

The same pair of components serves other patterns. When the request says where the reply should go, instead of the warehouse having a fixed address, the pattern is the Return Address. When the requestor needs to match each reply to its request among several pending ones, the pattern is the Correlation Identifier, which the series already shows with a payment provider’s callback; this page does not repeat that work and matches the reply by orderId, which is enough for one reservation per order.

In the MuleSoft documentation

The documentation page Enterprise Integration Patterns Using Mule maps Request-Reply to the connectors that do request and reply operations, or to the Reliability Patterns, without naming a component. The Reliability Patterns page is about receiving messages safely from a connector without a transaction and says nothing about request and reply; the documentation does not say why it links it to this row. The HTTP Request on this page is one of those operations: the synchronous side is the connector waiting for the response; the asynchronous side, with the reply channel on an HTTP Listener, is a flow decision that the EIP page does not cover.

The example

The synchronous side keeps the request, notes the time and calls the warehouse:

<set-variable doc:name="SET vRequest" variableName="vRequest" value="#[output application/java --- payload]" />
<set-variable doc:name="SET vStartedAt" variableName="vStartedAt" value="#[now()]" />
<http:request doc:name="POST Reservation To Warehouse And Wait" config-ref="eip-self-http-request-config" method="POST" path="/eip/warehouse/reservations">
	<http:body><![CDATA[#[output application/json --- vars.vRequest]]]></http:body>
</http:request>
<ee:transform doc:name="Build Sync Response">
	<ee:message>
		<ee:set-payload><![CDATA[%dw 2.0
output application/json
---
{
	mode: "SYNC",
	orderId: vars.vRequest.orderId,
	reply: payload,
	waitedMillis: (now() - vars.vStartedAt) as Number { unit: "milliseconds" }
}]]></ee:set-payload>
	</ee:message>
</ee:transform>

In the repository: src/main/mule/eip/request-reply/request-reply.xml

waitedMillis shows the wait: the response already carries the reservation, and the client waited at least the warehouse’s 300 ms (eip.requestReply.warehouseDelayMillis, in config/app.yaml).

On the asynchronous side, the warehouse answers 202 and returns the reservation from inside an Async:

<set-variable doc:name="SET vRequest" variableName="vRequest" value="#[output application/java --- payload]" />
<async doc:name="Async Reply Later">
	<flow-ref doc:name="Refer to sf-make-reservation" name="sf-make-reservation" />
	<http:request doc:name="POST Reply To Reply Channel" config-ref="eip-self-http-request-config" method="POST" path="${eip.requestReply.replyChannelPath}">
		<http:body><![CDATA[#[output application/json --- payload]]]></http:body>
	</http:request>
</async>
<set-payload doc:name="Set Accepted Response" value="#[output application/json --- { orderId: vars.vRequest.orderId, status: 'ACCEPTED' }]" />

In the repository: src/main/mule/eip/request-reply/request-reply-warehouse.xml

In request-reply.xml, the reply channel is /eip/stock/reservation-replies (eip.requestReply.replyChannelPath). Before calling the warehouse, the order service saves the request as PENDING in an Object Store, because the reply can arrive before the warehouse’s 202. When the reply arrives, the channel checks that there really was a pending request:

<choice doc:name="Check Request Is Pending">
	<when expression="#[vars.vPending.status == null]">
		<raise-error doc:name="Raise NOT_FOUND Error - No request" type="APP:NOT_FOUND" description="No reservation request for this orderId" />
	</when>
	<when expression="#[vars.vPending.status != 'PENDING']">
		<raise-error doc:name="Raise CONFLICT Error - Already replied" type="APP:CONFLICT" description="A reply for this orderId was already received" />
	</when>
</choice>

A reply with no request gets 404; a second reply for the same order gets 409 and does not overwrite the first. While the reply has not arrived, GET /eip/stock/reservation-replies/{orderId} returns PENDING.

Caveats

  • The default timeout is 10 seconds. In the community forum, in 2022, a question about the difference between the response timeout and the connection idle timeout, on a Mule 4 API that occasionally failed with a timeout on an HTTP call, was answered by pointing at the response timeout, 10 seconds by default (What is the difference between response timeout and connection idle timeout in HTTP request of mule 4). The documentation gives the reason: responseTimeout is the maximum time the HTTP Request blocks the flow waiting for the response, and the inherited default is 10000 ms (HTTP Connector Reference). In the synchronous case, raising the timeout also raises the wait of the requestor’s own client, which has its own timeout.
  • The POST is not retried on its own. When the connection is closed on the other end (Remotely Closed), the HTTP Request tries again, but this built-in mechanism does not repeat non-idempotent methods such as POST unless the mule.http.client.retryOnAllMethods property is turned on (Configure HTTP Request Operation). Turning that property on for a reservation request can reserve twice; anyone who retries needs a replier that recognizes the repeat, such as the Idempotent Receiver.
  • The asynchronous reply can be lost. The Async does not inherit the main flow’s error handling and returns nothing to it; to handle errors inside it, the documentation points to a Try (Async Scope). In the example, if the POST of the reply fails, the requestor is not told and the request stays PENDING forever: the example has no deadline and no retry. This page’s recommendation: a real requestor needs one of the two, a deadline for pending requests or a replier that repeats the reply.
  • The temporary reply queue has a deadline too. Publish Consume waits for the reply up to the queueTimeout (5 seconds by default) and fails with VM:QUEUE_TIMEOUT after that (VM Connector Reference). It is the same blocking as synchronous HTTP, with a queue in place of the connection.

When not to use it

If the sender does not need a reply, as with a notice that the order was created, the pair of messages is extra complexity: a single message, in one direction, is enough. And if the replier takes minutes, the synchronous block holds the flow and the client for all that time; the asynchronous path, with the request recorded and the reply on its own channel, is the design this page recommends, and matching the replies of several pending requests calls for the Correlation Identifier.

Running the example and the tests

git clone https://github.com/brunosouzas/mulesoft-patterns-examples.git
cd mulesoft-patterns-examples
mvn clean test

The project needs Java 17, Maven 3.9+ and the Mule 4.9 runtime. MUnit runs on the Enterprise runtime, so Maven needs access to the MuleSoft Enterprise repository (credentials in ~/.m2/settings.xml).

The request-reply-test-suite.xml suite pins the behavior, observed on Mule 4.9.17 with MUnit 3.7.1:

Test What it proves
rr-sync-requestor-waits-for-the-reply The synchronous response already carries the reservation, after at least the warehouse’s 300 ms
rr-async-requestor-is-called-back-on-the-reply-channel The asynchronous call answers 202 PENDING without the reservation; a GET right after still sees PENDING; the reservation arrives later, sent once to the reply channel
rr-reply-without-a-request-returns-404 A reply to a request nobody made gets 404 and is not stored
rr-invalid-request-returns-400 A request without sku or quantity gets 400 and the warehouse is not called
rr-second-reply-is-rejected-with-409 A second reply for the same order gets 409 and the first stays

The asynchronous test waits for the reply with an Until Successful and checks what the requestor answered before it:

<munit-tools:assert-that doc:name="202" expression="#[vars.vResponse.status]" is="#[MunitTools::equalTo(202)]" />
<munit-tools:assert-that doc:name="JSON" expression="#[vars.vResponse.contentType]" is="#[MunitTools::startsWith('application/json')]" />
<munit-tools:assert-that doc:name="Pending" expression="#[vars.vResponse.body.status]" is="#[MunitTools::equalTo('PENDING')]" />
<munit-tools:assert-that doc:name="No reservation in the response" expression="#[vars.vResponse.body.reservationId]" is="#[MunitTools::nullValue()]" />
<munit-tools:assert-that doc:name="Names the reply channel" expression="#[vars.vResponse.body.replyChannel]" is="#[MunitTools::equalTo('/eip/stock/reservation-replies')]" />
<munit-tools:assert-that doc:name="Still pending right after" expression="#[vars.vRightAway.body.status]" is="#[MunitTools::equalTo('PENDING')]" />
<munit-tools:assert-that doc:name="Reply arrived" expression="#[vars.vReply.body.status]" is="#[MunitTools::equalTo('RESERVED')]" />
<munit-tools:assert-that doc:name="Reservation id" expression="#[vars.vReply.body.reservationId]" is="#[MunitTools::notNullValue()]" />

In the repository: src/test/munit/eip/request-reply-test-suite.xml

To call the endpoints, run the application in Anypoint Studio (port 8081) and use the Request-Reply entries in requests.http:

### EIP request-reply — synchronous: the requestor waits for the warehouse (waitedMillis >= 300)
POST {{base}}/eip/stock/reservations/sync
Content-Type: application/json

{ "orderId": "ORD-4101", "sku": "SKU-BOOK", "quantity": 2 }

### Asynchronous: 202 PENDING now, the warehouse calls the reply channel later
POST {{base}}/eip/stock/reservations/async
Content-Type: application/json

{ "orderId": "ORD-4102", "sku": "SKU-MUG", "quantity": 1 }

###
GET {{base}}/eip/stock/reservation-replies/ORD-4102

In the repository: requests.http

The other patterns are in the catalog of integration patterns in Mule and, by component name, in the index by component.

Code for this page