Polling Consumer in Mule: stock allocation fetches pending orders at its own pace
- 11 min read
On this page
Code
The orders waiting for stock allocation sit in a list of pending orders, and the stock service decides when to fetch them: every second, it reads what arrived since the last time and allocates. Consuming when the consumer is ready, not when the message arrives, is the problem the Polling Consumer solves. In Mule, it is a flow that starts with a Scheduler and keeps in an Object Store how far it has read.
The problem
The pending list is a source that notifies no one: an order enters it and stays there, as it would in a database table that another system fills. The stock service also does not want to be woken up for every order; it allocates better in batches and at the pace it can sustain. So it asks every so often “what is new?” and processes the answer.
Two questions come up right away. How do you know what is new, if the list is never emptied? And what happens to an order that was being allocated when the read failed? The example answers both with a watermark: a number that marks the last order processed.
The pattern in the book
The book starts from an application that needs to consume messages but wants to control when it consumes each one, and asks how the application can consume a message when it is ready. The solution is for the application to use a Polling Consumer, which makes an explicit call when it wants to receive a message (Polling Consumer). The book also calls it a synchronous receiver, because the receiver’s thread stays blocked until it gets the message: the receiver fetches a message, processes it, then fetches another. How the consumer obtains the message from the messaging system is an implementation detail, and may or may not involve polling; all the application knows is that it receives nothing until it asks.
The opposite is the Event-Driven Consumer, which is invoked when the message arrives. The book relates the two to each other and to Competing Consumers, in which several consumers read the same channel.
The diagram redraws the book’s sketch (CC BY 4.0) in the orders scenario:
In Mule
The Scheduler runs flows at defined intervals or times, with a fixed frequency or a cron expression (Scheduler Endpoint (Trigger)). It is the flow’s source, like the HTTP Listener, but the flow itself decides the time, not the sender of the message. A flow that starts with a Scheduler and reads a source is a Polling Consumer: on each trigger, it asks and processes what came back.
The Scheduler solves the “when”. The “what is new” is left to the flow. The documentation uses “watermark” for the technique of storing and retrieving the point where a periodic synchronization should continue on its next run, and says this is a common use of the Object Store (Set Up Watermarks with an Object Store Example). Mule 4 has no watermark component: the flow reads the value with os:retrieve and writes it with os:store (Object Store Connector Reference).
Some connectors ship the pattern as an operation: the same Anypoint MQ that has the event-driven Subscriber has a Consume operation, which takes a single message when the flow asks (Anypoint MQ Subscriber Source), and the VM Connector has a Consume operation, which pulls a message from the queue and waits up to queueTimeout if there is none (VM Connector Reference). A flow with a Scheduler and Consume is a Polling Consumer over a queue. The example uses no queue: the project runs without a broker and does not simulate one with VM.
In the MuleSoft documentation
The documentation’s Enterprise Integration Patterns Using Mule page maps the Polling Consumer to the Mule SDK’s sources, linking to Creating Message Sources with the Mule SDK, a page about writing a source in Java, not about the Scheduler. The SDK also has Polling Sources, sources that query items periodically and take care of idempotency and the watermark; a flow that uses the Scheduler, as this page does, handles the watermark in the flow.
The example
Each order that enters the list gets an increasing sequence number (sequence). The polling flow reads the watermark, selects the orders above it, allocates each one and only then writes the new watermark:
<flow name="stock-poll-pending-orders" doc:description="Polling consumer: a Scheduler polls the pending orders at a fixed frequency and allocates stock for the ones above the watermark, then moves the watermark.">
<scheduler doc:name="Scheduler - Poll Pending Orders" disallowConcurrentExecution="true">
<scheduling-strategy>
<fixed-frequency frequency="${eip.pollingConsumer.frequencyMillis}" timeUnit="MILLISECONDS" />
</scheduling-strategy>
</scheduler>
<os:retrieve doc:name="Read Watermark" key="watermark" objectStore="eip-polling-watermark-store" target="vWatermark">
<os:default-value><![CDATA[#[0]]]></os:default-value>
</os:retrieve>
<os:retrieve-all doc:name="Read Pending Orders" objectStore="eip-pending-orders-store" />
<ee:transform doc:name="Select Orders Above Watermark">
<ee:variables>
<ee:set-variable variableName="vNewOrders"><![CDATA[%dw 2.0
output application/java
---
(payload pluck $) filter (($ is Object) and ($.sequence > (vars.vWatermark as Number))) orderBy $.sequence]]></ee:set-variable>
</ee:variables>
</ee:transform>
<foreach doc:name="For Each New Order" collection="#[vars.vNewOrders]">
<flow-ref doc:name="Refer to sf-allocate-polled-order" name="sf-allocate-polled-order" />
</foreach>
<choice doc:name="Check Anything Read">
<when expression="#[not isEmpty(vars.vNewOrders)]">
<os:store doc:name="Store Watermark" key="watermark" objectStore="eip-polling-watermark-store">
<os:value><![CDATA[#[max(vars.vNewOrders map $.sequence)]]]></os:value>
</os:store>
</when>
</choice>
<logger doc:name="INFO: Log poll" level="INFO" message="#['Polled pending orders: ' ++ sizeOf(vars.vNewOrders) ++ ' new above watermark ' ++ vars.vWatermark ++ ', correlationId=' ++ correlationId]" />
</flow>
In the repository: src/main/mule/eip/polling-consumer/polling-consumer.xml
The frequency comes from eip.pollingConsumer.frequencyMillis, which is 1000 in app.yaml. An order that arrives between two triggers waits for the next one; with the Event-Driven Consumer, the event has already been processed when the sender gets the response. That wait is the cost of the pattern, and it is what the first test measures.
The order of the two writes is the example’s decision. The watermark is written only after every order in the read has been allocated. If the read fails midway, the watermark does not move, and the next read picks up the same orders again, including those already allocated before the failure. No order is lost, and some may be processed twice: this is at-least-once delivery, not exactly once. The opposite order (writing the watermark before allocating) would trade the repeat for a loss: an order that was read and not allocated would stay below the watermark forever. The timesAllocated count makes the repeat visible in the example.
The flow that adds orders to the list has maxConcurrency="1", so two orders arriving at the same time do not get the same number. The documentation says maxConcurrency sets the maximum number of messages a flow processes at the same time, and that the value 1 makes the flow process one request at a time (Flow and Private Flow Components). That holds for a flow in one runtime; with several workers, each would number its own, and the sequence would need a shared counter, such as a database sequence.
Caveats
- Overlapping runs. By default, the Scheduler does not wait for one run to finish before firing the next at the configured cadence;
disallowConcurrentExecution="true"prevents the trigger while the previous run is still going (Scheduler Endpoint (Trigger)). Without it, two reads can pick up the same orders above the same watermark. KB article 005093840, from 2025, describes a Scheduler app on CloudHub 2.0 with a message count far above what was expected and saysmaxConcurrencycontrols the number of threads and does not prevent overlapping runs withoutdisallowConcurrentExecution(High Message Count Observed for CH2 Mule Scheduler App). In the example,disallowConcurrentExecutionis on the poller;maxConcurrency="1"is on the flow that numbers the orders, for a different reason. - Several replicas, several reads. The Scheduler page says that in a Mule cluster, or in a CloudHub deployment with several workers, the Scheduler runs only on the primary node (Scheduler Endpoint (Trigger)). On CloudHub 2.0 the rule is different: without clustering, schedules run individually on every replica, and the documentation asks that, since they may fire more than once, they be designed to avoid duplicate processing (Managing App Schedules). In a 2025 forum thread, a daily flow in an app with two replicas on CloudHub 2.0 ran twice, milliseconds apart (Scheduler in a multi-worker deployment). The example’s watermark does not protect against that case. This is an inference from the Object Store documentation, which guarantees synchronization between nodes only in cluster mode (Object Store Connector Reference): the non-persistent Object Store stays on each replica, and two replicas would read the same list.
- The watermark depends on the right Object Store. The example uses stores with
persistent="false", kept in memory (inferred from the attribute); after a restart, the watermark goes back to 0 and the whole list is read again. In a real deployment, the watermark lives in a persistent store. On CloudHub with several workers, Object Store v2 can have discrepancies or key conflicts, because distributed locking is not available there (Object Store v2 Overview). - At least once requires a consumer that tolerates the repeat. The example’s allocation counts how many times each order was allocated instead of refusing the repeat. A real consumer needs the second allocation of the same order to do nothing; the Idempotent Receiver shows how to refuse it.
When not to use it
When the source notifies (a webhook, a queue with a listener), polling adds delay and empty queries, and the Event-Driven Consumer processes the message the moment it arrives. It also does not pay off when the source itself already knows what was delivered, like a queue: the Consume operation of Anypoint MQ or VM takes the message out, and the example’s watermark would be extra work. And when a single consumer, even at its own pace, cannot keep up with the volume, the problem becomes that of the Competing Consumers.
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).
In the suite, the Scheduler source runs only in the test that turns it on (poll-scheduler-polls-on-its-own), so most tests do one read at a time by calling the flow with flow-ref. The polling-consumer-test-suite.xml suite pins down the behavior, observed on Mule 4.9.17 with MUnit 3.7.1:
| Test | What it proves |
|---|---|
poll-new-order-waits-for-the-next-poll |
A newly added order is not allocated before the read; after it, it is ALLOCATED, and the watermark is its sequence |
poll-watermark-reads-each-order-once |
Three reads, A and B in read 1, nothing new in 2, C in 3, write three allocations and the watermark twice; each order has timesAllocated 1 |
poll-scheduler-polls-on-its-own |
With the Scheduler on (every 1000 ms), the order is allocated without any call to the polling flow |
poll-pending-order-without-id-returns-400 |
An order without orderId gets 400 and does not enter the list |
poll-failed-poll-is-read-again |
A read that fails on the second of two orders does not move the watermark; the next one allocates the first again (timesAllocated 2) and the second once |
The last test is the one that proves “at least once”. The allocation write fails only for the second order, and the verifications count the attempts and the watermark writes:
<munit-tools:verify-call doc:name="Four allocation attempts over two polls" processor="os:store" times="4">
<munit-tools:with-attributes>
<munit-tools:with-attribute attributeName="doc:name" whereValue="Store Allocation" />
</munit-tools:with-attributes>
</munit-tools:verify-call>
<munit-tools:verify-call doc:name="Watermark stored by the second poll only" processor="os:store" times="1">
<munit-tools:with-attributes>
<munit-tools:with-attribute attributeName="doc:name" whereValue="Store Watermark" />
</munit-tools:with-attributes>
</munit-tools:verify-call>
<munit-tools:assert-that doc:name="Watermark unchanged by the failed poll" expression="#[vars.vAfterFail.body.watermark]" is="#[MunitTools::equalTo(vars.vBefore.body.watermark)]" />
<munit-tools:assert-that doc:name="Order 1 allocated before the failure" expression="#[(vars.vAfterFail.body.orders filter ($.orderId == 'ORD-POLL-FAIL-1'))[0].timesAllocated]" is="#[MunitTools::equalTo(1)]" />
<munit-tools:assert-that doc:name="Order 2 not allocated" expression="#[(vars.vAfterFail.body.orders filter ($.orderId == 'ORD-POLL-FAIL-2'))[0]]" is="#[MunitTools::nullValue()]" />
<munit-tools:assert-that doc:name="Order 1 read again: allocated twice" expression="#[(vars.vAfter.body.orders filter ($.orderId == 'ORD-POLL-FAIL-1'))[0].timesAllocated]" is="#[MunitTools::equalTo(2)]" />
<munit-tools:assert-that doc:name="Order 2 allocated once" expression="#[(vars.vAfter.body.orders filter ($.orderId == 'ORD-POLL-FAIL-2'))[0].timesAllocated]" is="#[MunitTools::equalTo(1)]" />
<munit-tools:assert-that doc:name="Watermark moved to order 2" expression="#[vars.vAfter.body.watermark]" is="#[MunitTools::equalTo(vars.vSecond.body.sequence)]" />
In the repository: src/test/munit/eip/polling-consumer-test-suite.xml
To see the Scheduler work, run the application in Anypoint Studio (port 8081) and use the Polling Consumer entries in requests.http:
### EIP polling consumer — added now, allocated by the next poll (every second)
POST {{base}}/eip/stock/pending-orders
Content-Type: application/json
{ "orderId": "ORD-4401" }
###
GET {{base}}/eip/stock/polled-orders
In the repository: requests.http
Call the GET right after the POST and again a second later: the first time the order may not be there yet, the second time it is allocated and the watermark has advanced. The other patterns are in the catalog of integration patterns in Mule and, by component name, in the index by component.