Guaranteed Delivery in Mule: the order is stored before the response and resent until it arrives
- 13 min read
On this page
Code
The orders API tells the client the order was accepted and then passes it to the fulfillment system. If fulfillment is down, or the application crashes between the response and the handoff, the accepted order disappears. Guaranteed Delivery stores the message before it confirms the send and deletes it only after the target has received it. In the book, the messaging system does the storing; in Mule, it is the queue (Anypoint MQ or persistent VM). The example runs without a broker and does the storing with an outbox in a persistent Object Store and a scheduled forwarder.
The problem
Order ORD-5101 arrives over HTTP. The naive version calls fulfillment right away and responds with the result: with fulfillment returning 503, the client gets an error for an outage that is not theirs. A slightly better version responds 202 and calls fulfillment afterward, but keeps the order only in the event’s memory: if the application restarts before the handoff, fulfillment never sees the order.
The pattern in the book
The book asks how the sender makes sure a message will be delivered even if the messaging system fails. The solution is to make the messages persistent, so they are not lost even if the messaging system crashes (Guaranteed Delivery).
The mechanism is store and forward. The messaging system has its own store on each machine where it is installed. The send completes successfully only after the message is stored in the sender’s store, and the message is deleted from one store only after it has been passed on and stored in the next. So the message is on disk on at least one machine until it is delivered to the receiver and acknowledged by it.
In the book, the guarantee belongs to the messaging system, not to the application: the sender sends, and the channel takes care of the rest.
The diagram redraws the book’s sketch (CC BY 4.0) in the order scenario:
In Mule
With a broker, Mule does what the book describes. Anypoint MQ keeps the message in the queue until the consumer acknowledges it; without an acknowledgment within the queue’s time, it comes back (Configuring and Using Queues). Inside an application, the VM queue can be TRANSIENT (the default) or PERSISTENT (VM Connector Reference); the documentation says transient queues are not reliable if the system crashes and that persistent queues, on a single runtime, write the content to disk (VM Connector). The same page warns that persistent queues do not exist on CloudHub 2.0 or Runtime Fabric, and Reliability Patterns says VM’s file persistence does not work in a cluster (Reliability Patterns). MuleSoft’s reliability pattern combines an acquisition flow, which receives from a non-transactional source such as HTTP and hands over to a transactional operation such as VM or JMS, with a logic flow that consumes from there; for HTTP, if the acquisition cannot deliver, it responds with an error so the client tries again.
The example uses no queue: it runs without a broker and does not simulate one with VM. In place of the messaging system’s store, there is an Object Store declared persistent="true", the outbox. The connector reference describes the Persistent field as the choice between a persistent and a transient store (Object Store Connector Reference), and the object stores page says Mule uses them to persist data that will be read later (Store Application Data Using Object Stores). The API writes the order to the outbox and only then responds 202. A flow started by a Scheduler reads the outbox, sends each order to fulfillment and deletes it only after a 2xx.
This is a substitute for the channel, not the book’s pattern to the letter: the store and forward lives in the application code, not in the messaging system.
The quarantine plays the role of the Dead Letter Channel in a broker: it takes the order that will never be delivered out of the way. And the simulated fulfillment is an Idempotent Receiver: it records the processing of each orderId with failIfPresent, and a repeat gets OS:KEY_ALREADY_EXISTS, the same tool as in Competing Consumers. The simulated fulfillment is in guaranteed-delivery-fulfilment.xml.
In the MuleSoft documentation
The documentation page Enterprise Integration Patterns Using Mule maps Guaranteed Delivery to Reliability Patterns, described in “In Mule”. The example has the same split, with the persistent outbox in place of the transactional connector: the inbound flow stores before responding, and the forwarder delivers afterward.
The example
The API flow validates the order, refuses an orderId that was already delivered or is in quarantine, and stores it in the outbox. The 202 comes after the write:
<try doc:name="Try Persist New Order">
<os:store doc:name="Persist Order In Outbox" key="#[vars.vOrderId]" objectStore="eip-gd-outbox-store" failIfPresent="true">
<os:value><![CDATA[#[output application/java --- { orderId: vars.vOrderId, order: payload, attempts: 0, storedAt: now() as String }]]]></os:value>
</os:store>
<error-handler>
<on-error-propagate doc:name="On Error Propagate (orderId already in the outbox)" type="OS:KEY_ALREADY_EXISTS" logException="false">
<raise-error doc:name="Raise CONFLICT Error - Order already stored" type="APP:CONFLICT" description="Order already received" />
</on-error-propagate>
</error-handler>
</try>
<logger doc:name="INFO: Log order stored" level="INFO" message="#['Order ' ++ vars.vOrderId ++ ' persisted in the outbox, correlationId=' ++ correlationId]" />
<set-payload doc:name="Set Stored Response" value="#[output application/json --- { orderId: vars.vOrderId, status: 'STORED' }]" />
In the repository: src/main/mule/eip/guaranteed-delivery/guaranteed-delivery.xml
failIfPresent="true" makes a second write of the same orderId throw OS:KEY_ALREADY_EXISTS without overwriting (Object Store Connector Reference), and the handler returns 409.
The forwarder reads the whole outbox on each run, in write order, and handles each order in a sub-flow:
<scheduler doc:name="Scheduler - Forward Stored Orders" disallowConcurrentExecution="true">
<scheduling-strategy>
<fixed-frequency frequency="${eip.guaranteedDelivery.forwardFrequencyMillis}" timeUnit="MILLISECONDS" />
</scheduling-strategy>
</scheduler>
<os:retrieve-all doc:name="Read Outbox" objectStore="eip-gd-outbox-store" />
<set-variable doc:name="SET vStoredOrders" variableName="vStoredOrders" value="#[output application/java --- (payload pluck $) orderBy $.storedAt]" />
<foreach doc:name="For Each Stored Order" collection="#[vars.vStoredOrders]">
<flow-ref doc:name="Refer to sf-forward-one-stored-order" name="sf-forward-one-stored-order" />
</foreach>
With disallowConcurrentExecution="true", the Scheduler skips the scheduled run if the previous one is still running (Scheduler Endpoint); without it, two passes could send the same order together.
The sub-flow decides each order’s destination:
<try doc:name="Try Forward To Fulfilment">
<http:request doc:name="POST Order To Fulfilment" config-ref="eip-self-http-request-config" method="POST" path="/eip/fulfilment/orders">
<http:body><![CDATA[#[output application/json --- vars.vStored.order]]]></http:body>
</http:request>
<os:store doc:name="Record Delivery" key="#[vars.vStored.orderId]" objectStore="eip-gd-delivered-store">
<os:value><![CDATA[#[output application/java --- { orderId: vars.vStored.orderId, status: 'DELIVERED', attempts: vars.vAttempt, deliveredAt: now() as String }]]]></os:value>
</os:store>
<os:remove doc:name="Remove Order From Outbox" key="#[vars.vStored.orderId]" objectStore="eip-gd-outbox-store" />
<error-handler>
<on-error-continue doc:name="On Error Continue (fulfilment rejected the order, move it aside)" type="HTTP:BAD_REQUEST, HTTP:UNAUTHORIZED, HTTP:FORBIDDEN, HTTP:NOT_FOUND, HTTP:METHOD_NOT_ALLOWED, HTTP:NOT_ACCEPTABLE, HTTP:UNSUPPORTED_MEDIA_TYPE" logException="false">
<set-variable doc:name="SET vReason" variableName="vReason" value="#['rejected by fulfilment: ' ++ error.errorType.namespace ++ ':' ++ error.errorType.identifier]" />
<flow-ref doc:name="Refer to sf-move-order-to-dead-store" name="sf-move-order-to-dead-store" />
</on-error-continue>
<on-error-continue doc:name="On Error Continue (any other failure, keep for redelivery up to the limit)" type="ANY" logException="false">
<set-variable doc:name="SET vLastError" variableName="vLastError" value="#[error.errorType.namespace ++ ':' ++ error.errorType.identifier]" />
<choice doc:name="Check Attempt Limit">
<when expression="#[vars.vAttempt >= (p('eip.guaranteedDelivery.maxAttempts') as Number)]">
<set-variable doc:name="SET vReason" variableName="vReason" value="#['not delivered after ' ++ (vars.vAttempt as String) ++ ' attempts, last error ' ++ vars.vLastError]" />
<flow-ref doc:name="Refer to sf-move-order-to-dead-store" name="sf-move-order-to-dead-store" />
</when>
<otherwise>
<os:store doc:name="Keep Order In Outbox With Attempt" key="#[vars.vStored.orderId]" objectStore="eip-gd-outbox-store">
<os:value><![CDATA[#[output application/java --- vars.vStored ++ { attempts: vars.vAttempt, lastError: vars.vLastError }]]]></os:value>
</os:store>
<logger doc:name="WARN: Log delivery failed" level="WARN" message="#['Order ' ++ vars.vStored.orderId ++ ' not delivered, kept for redelivery: ' ++ vars.vLastError ++ ', correlationId=' ++ correlationId]" />
</otherwise>
</choice>
</on-error-continue>
</error-handler>
</try>
The order inside the Try is what makes the pattern. The order leaves the outbox (Remove Order From Outbox) only after fulfillment responded 2xx and the delivery was recorded. Some 4xx codes (400, 401, 403, 404, 405, 406 and 415) mean fulfillment rejected the order, and trying again would fail the same way: the order goes straight to quarantine with the reason. Any other failure (a 503, a timeout, even a 408, 409 or 429) leaves the order in the outbox with one more attempt and the last error; on the fifth unsuccessful attempt (eip.guaranteedDelivery.maxAttempts, in app.yaml), it also goes to quarantine. Both handlers are on-error-continue, so one order’s failure does not interrupt the pass.
Why not just an Until Successful? The documentation says it runs synchronously and repeats the processors within the same event (Until Successful Scope). The attempts live in the event, in memory, and a restart in the middle of them loses the order (an inference from the documentation). The outbox keeps the order in a persistent store between one attempt and the next.
Delivery is at least once, not exactly once. If the application stops after the 2xx and before the os:remove, the order stays in the outbox and is sent again on the next pass. That is why fulfillment must tolerate repeats: the simulated one records the processing once per orderId and answers DUPLICATE to the repeat.
Caveats
- The outbox can get stuck on a worker. On your own servers, the documentation says Object Store v2 is accessible only through the REST API and that you can use the object store included in Mule (FAQ: Object Store v2). On CloudHub, Object Store v2 limits persistence to 30 days from creation and, with several workers, can cause data discrepancy or key conflicts (Object Store v2). In a Stack Overflow case, the author, on CloudHub with several workers, thought the Object Store value was not shared; the answer says only the store named
_defaultPersistentObjectStoreis shared across workers (Is Objectstore Not Shared Through Cluster Environment?).eip-gd-outbox-storehas its own name, so the outbox of a worker that does not come back can get stuck (this page’s inference). - The Scheduler runs on one node only. In a cluster or on CloudHub with several workers, the Scheduler runs only on the primary node (Scheduler Endpoint). That keeps two forwarders from competing, but it only helps if the outbox is shared; with one outbox per worker, the orders stored on the other workers are not forwarded (this page’s inference).
- Broker redelivery is also at least once. KB article 001119407 describes Anypoint MQ messages processed several times, every two minutes, because the Subscriber in
AUTOmode did not respect the queue’s acknowledgment time; the article’s solution is to setacknowledgementTimeouton the Subscriber (Anypoint MQ Message Getting Processed Twice). Standard queues deliver at least once and sometimes more than once (Configuring and Using Queues), so swapping the outbox for a broker does not remove the need for an idempotent receiver. - A persistent VM queue requires a serializable payload. On a single runtime or in a cluster, the documentation says data sent to persistent queues must be serializable (VM Connector).
When not to use it
When the client needs fulfillment’s result in the response, a 202 with later delivery does not work: the right contract is a synchronous call. When the caller can resend the order, MuleSoft’s reliability pattern already allows responding with an error and letting the client try again. And when a broker is available, the queue does the storing, the redelivery and the dead letter queue with no application code; the example’s outbox is what is left when there is none (this page’s recommendation).
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 requires Java 17, Maven 3.9+ and the Mule 4.9 runtime; MUnit runs on the Enterprise runtime, so Maven needs access to MuleSoft’s Enterprise repository (credentials in ~/.m2/settings.xml).
The forwarder’s frequency (eip.guaranteedDelivery.forwardFrequencyMillis, 1000) and the attempt limit (eip.guaranteedDelivery.maxAttempts, 5) are in app.yaml. The suite guaranteed-delivery-test-suite.xml pins the behavior, observed on Mule 4.9.17 with MUnit 3.7.1:
| Test | What it proves |
|---|---|
gd-order-is-persisted-before-it-is-acknowledged |
The 202 comes back with the order (amount 120) already in the outbox, with zero attempts, and fulfillment has not seen it yet (404) |
gd-forwarder-delivers-and-empties-the-outbox |
One pass delivers the order, deletes it from the outbox and fulfillment receives it once |
gd-failed-delivery-stays-stored-and-is-redelivered |
With fulfillment returning 503, two passes leave the order STORED with two attempts and the last error; with fulfillment back, the third pass delivers |
gd-crash-after-delivery-before-removal-sends-again |
With the outbox removal simulated as a failure, the next pass sends again: fulfillment receives twice and processes once |
gd-scheduler-redelivers-on-its-own |
With the Scheduler source on, the order reaches fulfillment without a call to the forwarder |
gd-rejected-order-is-moved-aside-and-the-pass-goes-on |
A 400 from fulfillment puts order A in quarantine with the reason, and order B, stored later, is delivered in the same pass |
gd-order-past-the-attempt-limit-is-moved-aside |
The fifth unsuccessful attempt puts the order in quarantine, and a later pass does not send it |
gd-repeated-order-id-is-refused |
A second POST of an orderId that is in the outbox or already delivered gets 409, and the stored order does not change |
gd-fulfilment-processes-a-repeat-once |
The simulated fulfillment answers RECEIVED and then DUPLICATE, and processes the order once |
gd-order-without-id-is-rejected-and-not-stored |
An order without orderId gets 400 and nothing is stored |
The redelivery test checks the order stored during the failure and delivered after it:
<munit:validation>
<munit-tools:assert-that doc:name="Acknowledged although fulfilment is down" expression="#[vars.vPosted]" is="#[MunitTools::equalTo(202)]" />
<munit-tools:assert-that doc:name="Still stored" expression="#[vars.vWhileDown.body.status]" is="#[MunitTools::equalTo('STORED')]" />
<munit-tools:assert-that doc:name="Two failed attempts" expression="#[vars.vWhileDown.body.attempts]" is="#[MunitTools::equalTo(2)]" />
<munit-tools:assert-that doc:name="Last error" expression="#[vars.vWhileDown.body.lastError]" is="#[MunitTools::equalTo('HTTP:SERVICE_UNAVAILABLE')]" />
<munit-tools:assert-that doc:name="Fulfilment has nothing" expression="#[vars.vFulfilmentDown]" is="#[MunitTools::equalTo(404)]" />
<munit-tools:assert-that doc:name="Delivered" expression="#[vars.vAfter.body.status]" is="#[MunitTools::equalTo('DELIVERED')]" />
<munit-tools:assert-that doc:name="On the third attempt" expression="#[vars.vAfter.body.attempts]" is="#[MunitTools::equalTo(3)]" />
<munit-tools:assert-that doc:name="Fulfilment received it once" expression="#[vars.vFulfilmentAfter.body.timesReceived]" is="#[MunitTools::equalTo(1)]" />
</munit:validation>
In the repository: src/test/munit/eip/guaranteed-delivery-test-suite.xml
What the tests do not prove is survival of a restart: MUnit does not restart the application. The tests show the order in the store declared persistent before and after the failures; keeping that store across restarts is the connector’s guarantee (Object Store Connector Reference), not something the suite verifies.
To call the endpoints, run the application in Anypoint Studio (port 8081) with the Guaranteed Delivery entries in requests.http:
### EIP guaranteed delivery — stored first, forwarded by the Scheduler (every second)
PUT {{base}}/eip/fulfilment/availability
Content-Type: application/json
{ "available": false }
###
POST {{base}}/eip/orders/guaranteed
Content-Type: application/json
{ "orderId": "ORD-5101", "amount": 120 }
###
GET {{base}}/eip/orders/guaranteed/ORD-5101
###
PUT {{base}}/eip/fulfilment/availability
Content-Type: application/json
{ "available": true }
###
GET {{base}}/eip/fulfilment/orders/ORD-5101
In the repository: requests.http
With fulfillment off, the order’s GET shows STORED and the attempts rising every second. If fulfillment is turned back on before the fifth attempt, the order becomes DELIVERED and fulfillment reports how many times it received it; after the fifth, the order is already in quarantine (DEAD, with the reason), and turning fulfillment back on does not deliver it (gd-order-past-the-attempt-limit-is-moved-aside). The other patterns are in the catalog of integration patterns in Mule and, by component name, in the index by component.