← Wiki

Correlation Identifier in Mule: linking the provider's callback to the order

  • 15 min read
On this page

Code

After charging an order, the payment consumer requests the payment from a provider that answers later, by callback, and it needs to know which order each answer belongs to. That is the problem the Correlation Identifier solves. Mule 4 has no component for it: the pattern is built with HTTP Request, HTTP Listener and Object Store. The name is confusing because Mule has its own correlationId, which does something else: it follows a request from one application to the next, in the logs.

The problem

The payment provider accepts the request with 202 and, later, calls a callback endpoint to say whether it approved or declined the payment. Other orders were sent in the meantime, and the callbacks can arrive in any order. The consumer needs to work out which order each one belongs to.

The pattern in the book

The book Enterprise Integration Patterns starts from an application that made a request through messages and received a reply, and asks how it knows which request that reply belongs to (Correlation Identifier). The solution is for each reply to carry a correlation identifier, a unique ID that indicates which request it answers. The requestor sends the request with a request ID; the replier handles it and copies that value into the reply’s correlation ID.

The diagram answers how the requestor matches each reply to its request when the replies come back out of order.

The Requestor sends Request 1 (request ID = 1) and Request 2 (request ID = 2) to the Replier. The Reply with correlation ID = 2 arrives first and is matched to request 2, then the one with correlation ID = 1 is matched to request 1.

The requestor keeps the requests that are waiting for a reply and looks up each reply’s correlation ID among them. Arrival order is no clue.

A Requestor, with its list of pending requests, and a Replier: the scene runs twice with the same two requests, in rounds numbered 1 and 2. In each round the Requestor sends ID 1 and ID 2, and each enters the list. In round 1, a reply comes back without an ID and the Requestor matches it by arrival order, to the wrong request. In round 2, each reply carries the correlation ID of its request: the reply with ID 2 arrives first and finds entry 2, then the one with ID 1 finds entry 1.

In Mule

In the example, the pattern is built in correlation-identifier.xml. After the Idempotent Receiver charge, the sf-request-payment-from-provider sub-flow plays the requestor. The replier is the payment-provider-simulator flow, a simulated provider inside the same application. The requestor calls the provider with HTTP Request, the callback arrives on an HTTP Listener, and two object stores hold the pending requests and the status of each order.

The diagram answers where the requestId travels, from the charge to the outcome stored on the order, and what happens to a callback that no request is waiting for.

The Payment sub-flow stores the request by requestId in the Pending requests Object Store (1-hour TTL), sets the order to PAYMENT_REQUESTED in the Status Object Store and sends POST /eip/provider/payments to the Simulated provider, which answers 202 Accepted. Later, in an async scope, the provider sends POST /eip/payments/callback with correlationId = requestId, status and approvedAmount to the Callback flow, which reads and removes the pending request. With no pending request it answers 404 and the order does not change. When the request is found, the order goes to PAID (APPROVED with the requested amount), PAYMENT_DECLINED (DECLINED) or PAYMENT_REVIEW with the reason (another amount or status), and the answer is 200 with result MATCHED and the orderStatus.

Mule’s correlationId is something else

Every Mule event has a correlationId, which ties log lines to one execution. Mule first looks for one at the source (for example, in a JMS message or, on the HTTP Listener, in the X-CORRELATION-ID header) and generates a new one only when none comes in (Correlation ID). HTTP Request has the Send Correlation Id option, with AUTO, ALWAYS and NEVER, and AUTO as the default (HTTP Connector). When an application A calls an application B with the option at its default, B adopts A’s ID, because it is also a Mule application and receives the call on an HTTP Listener, and a search for that ID in the logs brings up the request in both.

The diagram answers where the called application’s correlationId comes from, with the option at its default and with NEVER.

The Client sends a request, with or without X-CORRELATION-ID, to Application A, which adopts the header or generates a correlationId. With Send Correlation Id set to AUTO (default), Application A sends the HTTP Request with X-CORRELATION-ID, Application B adopts the same correlationId and the logs of both show the same ID. With NEVER, the HTTP Request goes without the header and Application B generates a new correlationId.

Correlation Identifier (book) correlationId (Mule)
What it is for Linking a reply to its request Following an execution through the logs, across applications
Who generates it The requestor; the replier only copies it Mule, when the source does not bring one
How it travels In the request and the reply (in the example, in the JSON body) Over HTTP, in the X-CORRELATION-ID header; with other sources, in their own correlation field
Question it answers Which request is this reply for? Where did this request go?

In the MuleSoft documentation

The documentation page Enterprise Integration Patterns Using Mule does not list the Correlation Identifier. The pattern is built in the flow, as in the example, and Mule’s correlationId answers a different question, the one in the table above.

The example

The request carries the requestId, not the orderId

The sub-flow generates a requestId ("PRQ-" ++ uuid()) and sends the provider only requestId and amount: the provider has no reason to know the application’s orders. Before the call, it stores the whole request, with the orderId and the amount, in the pending store, with the requestId as the key, because the callback can arrive before the 202 does.

<!-- Pending requests by requestId. TTL 1 hour: a callback later than that is treated as unknown. -->
<os:object-store name="eip-pending-payment-requests-store" doc:name="Pending Payment Requests Object Store"
	persistent="false" entryTtl="1" entryTtlUnit="HOURS" expirationInterval="5" expirationIntervalUnit="MINUTES" />

In the repository: src/main/mule/eip/correlation-identifier/correlation-identifier.xml

<!-- Stored before the call: the callback can arrive before the provider's 202 does. -->
<os:store doc:name="Remember Pending Request" key="#[vars.vPaymentRequest.requestId]" objectStore="eip-pending-payment-requests-store">
	<os:value><![CDATA[#[vars.vPaymentRequest]]]></os:value>
</os:store>
<os:store doc:name="Record Order Waiting For Payment" key="#[vars.vPaymentRequest.orderId]" objectStore="eip-order-payment-status-store">
	<os:value><![CDATA[#[output application/java --- { orderId: vars.vPaymentRequest.orderId, status: "PAYMENT_REQUESTED", requestId: vars.vPaymentRequest.requestId }]]]></os:value>
</os:store>
<!-- The order is kept aside and put back after the call, so the caller still has it as payload. -->
<set-variable doc:name="SET vChargedOrder" variableName="vChargedOrder" value="#[payload]" />
<http:request doc:name="Send Payment Request To Provider" config-ref="eip-self-http-request-config" method="POST" path="/eip/provider/payments">
	<http:body><![CDATA[#[output application/json --- vars.vProviderRequestBody]]]></http:body>
</http:request>
<set-payload doc:name="Set Order Back As Payload" value="#[vars.vChargedOrder]" />

The simulated provider answers 202 and calls back

The provider answers 202 and, inside an async scope, calls the path configured in eip.provider.callbackPath, the way a real provider calls the webhook registered with it. The main flow does not wait for the async scope to finish (Async), so the 202 does not depend on the callback, which returns the requestId in the correlationId field:

<set-variable doc:name="SET vProviderRequest" variableName="vProviderRequest" value="#[payload]" />
<async doc:name="Approve Payment Later">
	<http:request doc:name="Call Back The Requestor" config-ref="eip-self-http-request-config" method="POST" path="${eip.provider.callbackPath}">
		<http:body><![CDATA[#[output application/json --- {
	correlationId: vars.vProviderRequest.requestId,
	status: "APPROVED",
	approvedAmount: vars.vProviderRequest.amount,
	providerReference: "PRV-" ++ uuid()
}]]]></http:body>
	</http:request>
</async>
<set-payload doc:name="Set Accepted Response" value="#[output application/json --- { requestId: vars.vProviderRequest.requestId, status: 'ACCEPTED' }]" />

The simulated provider always approves the requested amount. The other outcomes appear in the tests that send the callback themselves.

The callback claims the pending request

The payment-confirm-from-provider-callback flow uses only the correlationId in the body. Without a correlationId, it answers 400. With one, it reads the pending request and removes it from the store before touching the order: that is how the callback claims the request. If the key does not exist, os:retrieve or os:remove throws OS:KEY_NOT_FOUND (Object Store reference), and the try scope marks the callback as unmatched; the next Choice throws APP:NOT_FOUND, which becomes a 404. The vPendingRequest variable lets the log distinguish a copy that lost the claim to another copy from a callback with an unknown, expired or already matched ID.

The Payment sub-flow stores the request by requestId in the Pending requests store and sends it to the Provider, which answers 202. Later, the Provider calls the Callback flow with the correlationId, which is the requestId. The Callback flow reads the pending request and removes it from the store, the order goes to PAID and the answer is 200. When the same callback arrives again, the store has nothing to read: the answer is 404 and the order stays PAID.
<set-variable doc:name="SET vCallback" variableName="vCallback" value="#[payload]" />
<set-variable doc:name="SET vUnmatched" variableName="vUnmatched" value="#[false]" />
<!-- Set only by a successful retrieve below; tells a lost claim apart from an unknown correlationId. -->
<remove-variable doc:name="Remove vPendingRequest" variableName="vPendingRequest" />
<try doc:name="Try Match And Claim Pending Request">
	<os:retrieve doc:name="Find Pending Request" key="#[vars.vCallback.correlationId]" objectStore="eip-pending-payment-requests-store" target="vPendingRequest" />
	<os:remove doc:name="Claim Pending Request" key="#[vars.vCallback.correlationId]" objectStore="eip-pending-payment-requests-store" />
	<error-handler>
		<!-- Unknown, expired, already matched, or claimed by another copy in between: all the same 404. -->
		<on-error-continue doc:name="On Error Continue (no pending request)" type="OS:KEY_NOT_FOUND" logException="false">
			<set-variable doc:name="SET vUnmatched" variableName="vUnmatched" value="#[true]" />
		</on-error-continue>
	</error-handler>
</try>
<choice doc:name="Check Callback Matched">
	<when expression="#[(vars.vUnmatched default false) and vars.vPendingRequest != null]">
		<!-- The retrieve found the request but the remove did not: another copy claimed it in between. -->
		<logger doc:name="WARN: Log lost claim" level="WARN" message="#['Provider callback lost the claim (concurrent duplicate), correlationId in body=' ++ vars.vCallback.correlationId ++ ', correlationId=' ++ correlationId]" />
		<raise-error doc:name="Raise NOT_FOUND Error - Claimed by another copy" type="APP:NOT_FOUND" description="No pending payment request for this correlationId" />
	</when>
	<when expression="#[vars.vUnmatched default false]">
		<logger doc:name="WARN: Log unmatched callback" level="WARN" message="#['Unmatched provider callback, correlationId in body=' ++ vars.vCallback.correlationId ++ ', correlationId=' ++ correlationId]" />
		<raise-error doc:name="Raise NOT_FOUND Error - Unknown correlationId" type="APP:NOT_FOUND" description="No pending payment request for this correlationId" />
	</when>
</choice>

With the request in hand, the flow decides the outcome from the callback’s status and the approved amount:

<choice doc:name="Route On Callback Status">
	<when expression="#[vars.vCallback.status == 'APPROVED' and vars.vCallback.approvedAmount == vars.vPendingRequest.amount]">
		<set-variable doc:name="SET vOutcome (PAID)" variableName="vOutcome" value="#[{ status: 'PAID' }]" />
	</when>
	<when expression="#[vars.vCallback.status == 'DECLINED']">
		<set-variable doc:name="SET vOutcome (PAYMENT_DECLINED)" variableName="vOutcome" value="#[{ status: 'PAYMENT_DECLINED' }]" />
	</when>
	<when expression="#[vars.vCallback.status == 'APPROVED']">
		<set-variable doc:name="SET vOutcome (PAYMENT_REVIEW, AMOUNT_MISMATCH)" variableName="vOutcome" value="#[{ status: 'PAYMENT_REVIEW', reviewReason: 'AMOUNT_MISMATCH' }]" />
	</when>
	<otherwise>
		<set-variable doc:name="SET vOutcome (PAYMENT_REVIEW, UNKNOWN_STATUS)" variableName="vOutcome" value="#[{ status: 'PAYMENT_REVIEW', reviewReason: 'UNKNOWN_STATUS' }]" />
	</otherwise>
</choice>

The Choice here is a Content-Based Router: each callback follows a single route, according to its content. The flow writes the outcome to the status store, which is read at GET /eip/payments/{orderId}/status. All three outcomes answer 200: the provider has already given its final answer, and rejecting the callback would only make it send the same answer again.

Mule’s correlationId between two calls

In mule-correlation-id.xml, the called flow returns the header it received and its event’s correlationId:

<flow name="mule-correlation-id-echo" doc:description="Callee of the Mule correlation ID demo: GET /eip/correlation-id/echo reports the X-CORRELATION-ID header it received and its own correlationId.">
	<http:listener doc:name="GET /eip/correlation-id/echo" config-ref="http-listener-config" path="/eip/correlation-id/echo" allowedMethods="GET">
		<http:response statusCode="#[vars.httpStatus default 200]" />
	</http:listener>
	<ee:transform doc:name="Report What Arrived">
		<ee:message>
			<ee:set-payload><![CDATA[%dw 2.0
output application/json
---
{ receivedHeader: attributes.headers["x-correlation-id"], calleeCorrelationId: correlationId }]]></ee:set-payload>
		</ee:message>
	</ee:transform>
</flow>

In the repository: src/main/mule/eip/correlation-identifier/mule-correlation-id.xml

The flows at /eip/correlation-id/call/default and /call/never call it, and the two calls differ only in sendCorrelationId:

<http:request doc:name="Call Echo (default)" config-ref="eip-self-http-request-config" method="GET" path="/eip/correlation-id/echo" />
<http:request doc:name="Call Echo (NEVER)" config-ref="eip-self-http-request-config" method="GET" path="/eip/correlation-id/echo" sendCorrelationId="NEVER" />

The calls in the tests are real HTTP, to localhost, within the same application; between two applications the header is the same. To change the ID for part of a flow, the documentation points to the with-correlation-id scope from the Mule Tracing module (Correlation ID).

Caveats

Mule’s correlationId does not identify a business message. Calls that leave the same execution carry the same ID, and a client that resends without the header arrives with a new ID. That is why it does not work as an idempotency key, and it is exactly the ID the Idempotent Message Validator uses by default; the Idempotent Receiver page shows both errors in tests.

The pending request expires. The pending store has a 1-hour TTL (entryTtl) and checks for expired entries every 5 minutes (expirationInterval). An expired entry leaves at the first check after it expires, not exactly when the hour is up (Object Store reference). After that, the callback gets 404, like an unknown ID, and the order stays in PAYMENT_REQUESTED, because the status store has no TTL. No test covers expiration: this comes from the configuration and the code.

Claiming before updating narrows the race, but does not close it. The tests show that a repeated callback gets 404 and the order keeps the first outcome, and that a copy that loses the request between os:retrieve and os:remove gets 404 and changes nothing. Two limits remain, which come from the code and have no test:

  • os:retrieve and os:remove are two calls, not a lock. Whether the second of two simultaneous copies fails on os:remove depends on the store. With Object Store v2 on CloudHub there is no distributed locking (the Idempotent Receiver page covers the store), and two simultaneous copies on two workers can still update the order; ruling that out takes an atomic claim or a lock outside this flow.
  • If writing to the order fails after the claim, the request has already left the pending store: the provider’s retry gets 404, and the order stays in PAYMENT_REQUESTED until someone checks.

The stores are in memory (persistent="false"), so each run starts clean. A restart wipes the pending requests, and their callbacks get 404; this comes from the code, with no test. With two workers outside a Mule cluster, the callback may reach the worker that did not store the request and get 404; the repository README points to a persistent, shared store, and the Idempotent Receiver page explains the difference between a cluster and replicas.

The example does not check who sent the callback. In a real webhook, also verify the provider’s signature before trusting the body.

When not to use it

The book describes two ways to receive the reply (Request-Reply). With synchronous blocking, the requestor sends and waits, which assumes a single outstanding request or a dedicated reply channel. With an asynchronous callback, several outstanding requests share the reply channel, and that is where the Correlation Identifier comes in.

A synchronous HTTP call falls into the first case: the response comes back on the same connection, already tied to the request, and an ID kept in a store would only add moving parts. The pattern becomes necessary when the reply arrives by another route: a callback, a reply queue, a return file.

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 suite’s 14 tests pass on Mule 4.9.17 with MUnit 3.7.1:

Test What it proves
cid-order-is-paid-by-the-provider-callback End to end: the simulated provider calls back from the async scope, and the test waits in an until-successful until ORD-CID-E2E is PAID
cid-request-carries-its-id-and-not-the-order The body sent to the provider has only requestId and amount, and the pending request keeps the orderId
cid-out-of-order-callbacks-are-matched-to-their-orders With ORD-CID-A (100) and ORD-CID-B (250) and the provider replaced by a mock that never calls back, the test sends B’s callback before A’s; each order ends up PAID with its own amount, and both requests leave the pending store
cid-declined-callback-marks-the-order-payment-declined DECLINED answers 200 and leaves the order in PAYMENT_DECLINED
cid-approved-callback-for-another-amount-goes-to-payment-review APPROVED with 90 instead of 100 leaves the order in PAYMENT_REVIEW, reviewReason: AMOUNT_MISMATCH
cid-callback-with-unknown-status-goes-to-payment-review Another status (CHARGEBACK) leaves the order in PAYMENT_REVIEW, reviewReason: UNKNOWN_STATUS
cid-repeated-callback-returns-404-and-keeps-the-first-outcome A repeat of an already matched callback, or a late DECLINED, gets 404; the order keeps the first outcome
cid-callback-that-loses-the-claim-returns-404-and-changes-nothing A mock makes os:remove throw OS:KEY_NOT_FOUND; the answer is 404 and the order stays in PAYMENT_REQUESTED
cid-unmatched-callback-returns-404 An unknown correlationId gets 404 and changes nothing
cid-callback-without-correlation-id-returns-400 A callback without a correlationId gets 400
cid-provider-rejects-request-without-id The simulated provider answers 400 to a request without a requestId
cid-status-of-unknown-order-returns-404 GET /eip/payments/{orderId}/status answers 404 for an order with no payment request
mule-cid-http-request-sends-the-caller-correlation-id With sendCorrelationId at its default, the called flow receives the caller’s ID in X-CORRELATION-ID and adopts it
mule-cid-send-correlation-id-never-does-not-send-it With NEVER, the header does not arrive and the called flow gets another ID

To call the endpoints, run the application in Anypoint Studio (port 8081) and open requests.http in VS Code’s REST Client or in IntelliJ:

  1. POST /eip/payments/after/charges with { "orderId": "ORD-2001", "amount": 100 } charges the order and requests the payment from the simulated provider.
  2. GET /eip/payments/ORD-2001/status shows the outcome stored by the callback: with the simulated provider, PAID, with the requestId and the providerReference.
  3. POST /eip/payments/callback with correlationId PRQ-UNKNOWN gets 404.
  4. GET /eip/correlation-id/call/default and /call/never return the caller’s ID alongside the header received and the called flow’s ID.

The other patterns in the series, with the Mule component for each one, are in the catalog of integration patterns in Mule; the reverse path, from the component to the patterns, is in the index by component.

Code for this page