← Wiki

Message Expiration in Mule: the expired reservation request does not reserve stock

  • 12 min read
On this page

Code

Checkout asks inventory to reserve the items of an order, but it waits for the reservation only for a while; after that it gives up, and a late reservation holds stock another customer could buy. Message Expiration solves this by stating in the message when it stops being valid, and the consumer ignores one that is past its deadline. In Mule, with Anypoint MQ, the queue has a TTL; the example runs without a broker and does the check in the consumer: each request carries an expiresAt, and a flow started by a Scheduler reserves the valid ones and sets aside the expired ones with the reason.

The problem

The reservation request for order ORD-5301 is for a book. It enters a queue and waits for the inventory service to fetch it. If inventory is behind (a long queue, a maintenance window, a stopped consumer), the request reaches it minutes later. In the meantime checkout has already told the customer the reservation failed, and the customer may have given up or tried again. A consumer that processes everything it finds reserves the book anyway, and the reservation stays held until someone releases it.

The request is not wrong: when it was sent, it made sense. It only got old in the queue. What is missing is a way for the sender to say when the message stops being valid, and for the consumer to respect that.

The pattern in the book

The book starts from a message whose data or request becomes useless if not received by a certain time, and which should therefore be ignored. It asks how the sender indicates when a message should be considered stale and not processed. The solution is to set a Message Expiration on the message, a time limit during which it is viable (Message Expiration).

After that time, a message not yet consumed expires, and consumers treat it as if it had never been sent. The book says most messaging systems redirect expired messages to the Dead Letter Channel, that others simply discard them, and that this may be configurable. And it adds the receiver’s side: if it receives the message but cannot process it before it expires, it should throw it away.

In the book, expiration is a property of the message that the messaging system respects. The sender sets the deadline; the channel or the consumer does the discarding.

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

Checkout sends the stock reservation request, which is valid until T, to the queue. Before T, the request goes from the queue to Inventory. After T, the dashed line takes the request to the Dead Letter Channel.

In Mule

With a broker, the queue expires the message. In Anypoint MQ, a queue’s Message TTL field defines how long unprocessed messages stay in it before being deleted; the maximum is two weeks (Configuring and Using Queues). The glossary describes the TTL as the time the message stays in the queue before Anypoint MQ expires and removes it: each queue has its own (Anypoint MQ Glossary).

There are two differences from the book. The TTL belongs to the queue, not to each message: all messages in that queue have the same deadline. And the documentation describes the expired message as deleted; the dead-letter queue, on the same page, receives messages that were not delivered, and the documentation does not say expired ones go to it.

The example uses no queue: the project runs without a broker and does not simulate one with VM. The queue is an Object Store, and the deadline belongs to the message, in an expiresAt field the sender fills in. The consumer is a Polling Consumer: a flow that starts with a Scheduler, reads what is in the queue and decides each request. Expired requests do not vanish: they go to a results store with status EXPIRED, the time they were consumed and the reason. That record is the role the book gives the Dead Letter Channel.

The POST /eip/stock/expiring-requests endpoint puts the request in the eip-me-queue-store queue. The Scheduler, every 1000 ms, triggers the consumer, which takes the request from the queue. If expiresAt > now, the result is RESERVED. If expiresAt <= now, the result is EXPIRED, with the reason. If there is an error while consuming, the result is FAILED, with the error.

In the MuleSoft documentation

The documentation page Enterprise Integration Patterns Using Mule does not list Message Expiration. What the documentation offers is the Anypoint MQ queue TTL, described in “In Mule”; the expiresAt checked by the consumer is this page’s flow decision, not a component.

The example

The inbound flow refuses a request without orderId, without sku, with an expiresAt that does not read as a date and time, or with a quantity that is not a positive integer; without quantity, the request enters with 1. The check uses DataWeave’s try function, which returns success: false instead of throwing the error (try):

<ee:transform doc:name="Check Request Fields">
	<ee:variables>
		<ee:set-variable variableName="vValid"><![CDATA[%dw 2.0
import try from dw::Runtime
output application/java
---
(payload is Object)
	and (not isEmpty(payload.orderId))
	and (not isEmpty(payload.sku))
	and (try(() -> payload.expiresAt as DateTime).success default false)]]></ee:set-variable>
	</ee:variables>
</ee:transform>
<choice doc:name="Validate Request">
	<when expression="#[not vars.vValid]">
		<raise-error doc:name="Raise BAD_REQUEST Error - Invalid request" type="APP:BAD_REQUEST" description="orderId, sku and an ISO date-time expiresAt are required" />
	</when>
</choice>

In the repository: src/main/mule/eip/message-expiration/message-expiration.xml

The valid request goes to the queue with the time it entered, and the response is 202 QUEUED. The inbound flow does not check whether expiresAt has already passed: the consumer decides, and a request that arrives expired is treated as one that expired while waiting.

The consumer reads the whole queue on each run, in arrival order, and decides each request inside its own Try:

<scheduler doc:name="Scheduler - Consume Expiring Requests" disallowConcurrentExecution="true">
	<scheduling-strategy>
		<fixed-frequency frequency="${eip.messageExpiration.consumerFrequencyMillis}" timeUnit="MILLISECONDS" />
	</scheduling-strategy>
</scheduler>
<os:retrieve-all doc:name="Read Queued Requests" objectStore="eip-me-queue-store" />
<set-variable doc:name="SET vRequests" variableName="vRequests" value="#[output application/java --- (payload pluck $) orderBy $.queuedAt]" />
<foreach doc:name="For Each Queued Request" collection="#[vars.vRequests]">
	<try doc:name="Try Consume One Request">
		<set-variable doc:name="SET vConsumedAt" variableName="vConsumedAt" value="#[now()]" />
		<choice doc:name="Check Expired">
			<when expression="#[(payload.expiresAt as DateTime) &lt;= vars.vConsumedAt]">
				<os:store doc:name="Move To Expired Requests" key="#[payload.orderId]" objectStore="eip-me-outcome-store">
					<os:value><![CDATA[#[output application/java --- { orderId: payload.orderId, status: 'EXPIRED', expiresAt: payload.expiresAt, consumedAt: vars.vConsumedAt as String, reason: 'expired before it was consumed' }]]]></os:value>
				</os:store>
				<logger doc:name="WARN: Log request expired" level="WARN" message="#['Reservation request of order ' ++ payload.orderId ++ ' expired at ' ++ payload.expiresAt ++ ', not processed, correlationId=' ++ correlationId]" />
			</when>
			<otherwise>
				<os:store doc:name="Reserve Stock" key="#[payload.orderId]" objectStore="eip-me-outcome-store">
					<os:value><![CDATA[#[output application/java --- { orderId: payload.orderId, status: 'RESERVED', sku: payload.sku, quantity: payload.quantity, expiresAt: payload.expiresAt, consumedAt: vars.vConsumedAt as String }]]]></os:value>
				</os:store>
			</otherwise>
		</choice>
		<os:remove doc:name="Take Request Off The Queue" key="#[payload.orderId]" objectStore="eip-me-queue-store" />
		<error-handler>
			<on-error-continue doc:name="On Error Continue (this request failed, the run goes on)" type="ANY" logException="false">
				<os:store doc:name="Move To Failed Requests" key="#[payload.orderId]" objectStore="eip-me-outcome-store">
					<os:value><![CDATA[#[output application/java --- { orderId: payload.orderId, status: 'FAILED', expiresAt: payload.expiresAt, reason: 'could not be consumed: ' ++ error.errorType.namespace ++ ':' ++ error.errorType.identifier }]]]></os:value>
				</os:store>
				<os:remove doc:name="Take Failed Request Off The Queue" key="#[payload.orderId]" objectStore="eip-me-queue-store" />
				<logger doc:name="WARN: Log request failed" level="WARN" message="#['Reservation request of order ' ++ payload.orderId ++ ' could not be consumed (' ++ error.errorType.identifier ++ '), moved aside, correlationId=' ++ correlationId]" />
			</on-error-continue>
		</error-handler>
	</try>
</foreach>

The comparison uses the consumption time (vConsumedAt), not the send time. That is what makes the pattern: a request that was valid when it entered the queue expires while it waits, and the consumer finds it expired. The expired one reserves nothing and leaves the queue with the reason expired before it was consumed; the valid one becomes RESERVED. In both cases the request leaves the queue only after the result was stored.

The Try around each request separates one request’s failure from the whole pass. A request the consumer cannot handle (for example, a stored expiresAt that no longer reads as a date) goes to the results as FAILED, with the error type, and the For Each moves on to the next. Without it, the same request would fail on every pass and block the ones behind it (this page’s recommendation).

With disallowConcurrentExecution="true", the Scheduler skips the scheduled run if the previous one is still running (Scheduler Endpoint), and two passes do not pick up the same request at the same time.

The expiresAt carries the time zone (2020-01-01T00:00:00Z, for example). The check compares the sender’s clock with the consumer’s; if the two disagree, the request expires too early or too late (an inference from the code: the deadline is an absolute instant).

Caveats

  • In Anypoint MQ, the expired message is deleted, not kept. The queue documentation describes the TTL as the time unprocessed messages stay before being deleted, and the dead-letter queue as the destination of undelivered messages (Configuring and Using Queues). It does not say the expired one passes through the DLQ. A team that needs to know a request expired, and why, needs an expiresAt checked by the consumer, as in the example (this page’s recommendation).
  • The documentation says two things about changing the TTL. The Message TTL description and the glossary say the new value applies to messages already in the queue; the section on changing the settings of an existing queue says the change affects only new messages (Configuring and Using Queues, Anypoint MQ Glossary). Test the effect on messages already in the queue before relying on it (this page’s recommendation).
  • The message also waits inside the consumer. KB article 005228013 describes a Subscriber that fetches ten messages at once and processes them one by one, with maxConcurrency=1: when the last ones’ turn comes, their lock has already expired, and the ACK fails with LockId provided is expired; the article’s solution includes raising acknowledgementTimeout and fetching fewer messages at a time (Understanding and Resolving Anypoint MQ Error “LockId provided is expired”). KB article 005135154 describes messages processed successfully that still end up in the DLQ, when the time in the prefetch buffer plus the processing exceeds acknowledgementTimeout (Messages Processed Successfully but Still Landing in Dead Letter Queue). Both cases are about the lock, not the TTL, but in both the time runs from when the Subscriber fetches the message, before the flow picks it up. The example’s check is different: it compares expiresAt with the time the consumer picks up the request (vConsumedAt), a choice of the example and not Anypoint MQ behavior (this page’s inference).
  • The scheduled consumer runs on one node only. In a cluster or on CloudHub with several workers, the Scheduler runs only on the primary node (Scheduler Endpoint). If that node falls behind, all requests wait for it, and more requests expire in the queue (an inference from the Scheduler documentation).

When not to use it

When the message is valid forever (an order that must be invoiced, even if late), expiring is losing data: there the pattern is Guaranteed Delivery, which insists until it delivers. When all messages in a queue have the same deadline and nobody needs a record of the expired ones, the Anypoint MQ queue TTL is enough, with no field in the message and no code in the consumer. And when the one waiting is the client itself in a synchronous call, the call’s timeout already plays the role of the deadline (this page’s recommendations).

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 consumer’s frequency (eip.messageExpiration.consumerFrequencyMillis, 1000) is in app.yaml. In the suite, the Scheduler source runs only in the test that turns it on; the others make one pass at a time by calling the flow with flow-ref, and the deadlines are relative to now(), with no fixed clock. The suite message-expiration-test-suite.xml pins the behavior, observed on Mule 4.9.17 with MUnit 3.7.1:

Test What it proves
me-valid-request-is-reserved A request that expires in one minute stays QUEUED until the consumer runs and then becomes RESERVED
me-already-expired-request-is-not-reserved A request with an expiresAt already in the past gets 202, becomes EXPIRED with the reason and reserves nothing
me-request-expires-while-it-waits In the same pass, the request with an expiresAt already in the past becomes EXPIRED and the one with a minute to spare becomes RESERVED
me-scheduler-consumes-on-its-own With the Scheduler source on, the request is consumed without a call to the consumer flow
me-request-without-valid-expiry-is-rejected A request without expiresAt, or with tomorrow in place of the date, gets 400; the one without expiresAt comes back in JSON with the reason and does not enter the queue (404)
me-failing-request-does-not-end-the-run A request stored in the queue with an unreadable expiresAt becomes FAILED, with the reason starting with could not be consumed: , and the next request, in the same pass, becomes RESERVED
me-request-with-invalid-quantity-is-rejected quantity 0, -3, 1.5 or "two" gets 400; the one with quantity 0 comes back in JSON (quantity must be a positive integer) and does not enter the queue (404); without quantity, the request enters with 1

The test of expiry in the queue checks both requests after a single pass:

<munit:validation>
	<munit-tools:assert-that doc:name="Past expiry still queued" expression="#[vars.vShort.status]" is="#[MunitTools::equalTo(202)]" />
	<munit-tools:assert-that doc:name="Short expired" expression="#[vars.vShortAfter.body.status]" is="#[MunitTools::equalTo('EXPIRED')]" />
	<munit-tools:assert-that doc:name="Long reserved" expression="#[vars.vLongAfter.body.status]" is="#[MunitTools::equalTo('RESERVED')]" />
</munit:validation>

In the repository: src/test/munit/eip/message-expiration-test-suite.xml

The test does not wait for the request to expire: the queue does not check expiresAt, only the consumer does, so a request stored already expired is the same case as one that expired while waiting, without depending on the build machine’s speed.

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

### EIP message expiration — set expiresAt a few seconds ahead, or in the past
POST {{base}}/eip/stock/expiring-requests
Content-Type: application/json

{ "orderId": "ORD-5301", "sku": "SKU-BOOK", "quantity": 1, "expiresAt": "2020-01-01T00:00:00Z" }

###
GET {{base}}/eip/stock/expiring-requests/ORD-5301

In the repository: requests.http

With the 2020 expiresAt, the GET shows EXPIRED with the reason after one second; with an expiresAt a few seconds ahead, it shows RESERVED. 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