← Wiki

Competing Consumers in Mule: three consumers split the invoices to issue

  • 12 min read
On this page

Code

After payment, each order needs an invoice, and a single issuer cannot keep up with the rate at which orders arrive. The way out is to put several issuers reading the same work, as long as each invoice is issued by one of them and only once. That is the Competing Consumers problem. In the book, the channel guarantees the single delivery; in Mule, with Anypoint MQ or a VM queue, the broker does. The example runs without a broker and makes the guarantee with an atomic claim in the Object Store.

The problem

Orders ORD-4501 through ORD-4506 are waiting for an invoice. Issuing an invoice takes time (in the example, 50 ms simulated), and with a single issuer the queue grows faster than it empties. Three issuers running at the same time would keep up, but they create a problem a single issuer did not have: if all of them look at the same list, two can take the same order, and the customer gets two invoices.

The pattern in the book

The book starts from an application that uses messaging and cannot process messages as fast as they enter the channel, and asks how a messaging client can process several messages at the same time. The solution is to create several Competing Consumers on a single channel, so they process several messages in parallel (Competing Consumers).

The detail that matters is where the guarantee lives. The consumers are created to receive messages from a single Point-to-Point Channel. When the channel delivers a message, any of the consumers could receive it; the messaging system’s implementation decides which one does, and in practice the consumers compete to be the receiver. The consumers agree on nothing among themselves: it is the channel that delivers each message to only one. The book warns that the solution works only with point-to-point channels; several consumers on a Publish-Subscribe Channel just create more copies of each message.

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

Paid orders enter the point-to-point channel of invoices to issue. From the channel, each message goes to only one of the three issuers: Issuer 1, Issuer 2 or Issuer 3.

In Mule

With a queue, Mule does what the book describes: several flows (or several replicas of the same flow) listen to the same queue, and the broker delivers each message to one of them. The Anypoint MQ Subscriber documentation speaks of “competing consumers” when it recommends a smaller buffer so as not to block the queue’s other consumers (Anypoint MQ Subscriber Source). With the VM Connector in a cluster, persistent queues live in the memory grid, and Mule decides whether to process the message on the originating node or send it to the cluster to be processed by another node, which the documentation describes as a way to distribute load (VM Connector Reference). In both cases, the flow needs no claim at all. Each consumer of the queue is an Event-Driven Consumer, called when the message arrives; the example, with no queue, makes the consumers read the list like a Polling Consumer.

The example uses no queue: the project runs without a broker and does not simulate one with VM. In place of the channel, there is a work list in an Object Store, which every consumer reads in full. Since all of them see all the items, something has to play the role of single delivery. That something is an atomic claim: each consumer tries to write the orderId to a second store with failIfPresent="true". The documentation says that, with this parameter set to true, the operation throws OS:KEY_ALREADY_EXISTS instead of overwriting, and that os:store is synchronized at the key level: no other operation accesses the same key in the same store while it runs (Object Store Connector Reference). The first to write owns the item; the others get the error and move on to the next.

The competition happens at the claim, not at the delivery.

The POST /eip/invoice-work/runs endpoint calls the Parallel For Each consumer-1..3, which starts the invoice-work-consumer, with maxConcurrency 3. The consumer reads the work list with os:retrieve-all-keys and tries to claim each item with os:store failIfPresent. If it writes, it issues the invoice. If it fails with OS:KEY_ALREADY_EXISTS, it moves to the next item.

For the consumers to run at the same time, the starting flow calls the three over HTTP from inside a Parallel For Each, which processes the parts of the collection simultaneously on separate routes and aggregates the results in the original order (Parallel For Each Scope). The consumer flow has maxConcurrency equal to the number of consumers, the maximum number of messages a flow processes at the same time (Flow and Private Flow Components).

The question each consumer asks for every item, “has this key been seen?”, is the same one the Idempotent Receiver asks, which in Mule is the Idempotent Message Validator storing IDs in an Object Store. The purpose changes: there, to refuse a repeated message; here, to divide new messages among those competing for them.

In the MuleSoft documentation

The documentation’s Enterprise Integration Patterns Using Mule page does not list Competing Consumers. The closest row is the Point-to-Point Channel’s, which it describes as the default channel inside a flow; this page’s claim in the Object Store has no row in the table, because it is the substitute the example uses in place of the queue.

The example

Each consumer reads the keys of the list, tries to claim each item and issues the invoice only for the ones it claimed:

<os:retrieve-all-keys doc:name="Read Work List" objectStore="eip-invoice-work-store" />
<foreach doc:name="For Each Work Item" collection="#[payload orderBy $]">
	<set-variable doc:name="SET vOrderId" variableName="vOrderId" value="#[payload]" />
	<try doc:name="Try Claim Work Item">
		<os:store doc:name="Claim Work Item" key="#[vars.vOrderId]" objectStore="eip-invoice-work-claims-store" failIfPresent="true">
			<os:value><![CDATA[#[output application/java --- { orderId: vars.vOrderId, consumer: vars.vConsumerId, claimedAt: now() as String }]]]></os:value>
		</os:store>
		<flow-ref doc:name="Refer to sf-issue-claimed-invoice" name="sf-issue-claimed-invoice" />
		<set-variable doc:name="SET vProcessed" variableName="vProcessed" value="#[output application/java --- vars.vProcessed ++ [vars.vOrderId]]" />
		<error-handler>
			<on-error-continue doc:name="On Error Continue (claimed by another consumer)" type="OS:KEY_ALREADY_EXISTS" logException="false">
				<set-variable doc:name="SET vAlreadyClaimed" variableName="vAlreadyClaimed" value="#[vars.vAlreadyClaimed + 1]" />
			</on-error-continue>
			<on-error-propagate doc:name="On Error Propagate (invoicing failed, release the claim)">
				<os:remove doc:name="Release Claim" key="#[vars.vOrderId]" objectStore="eip-invoice-work-claims-store" />
				<logger doc:name="WARN: Log claim released" level="WARN" message="#['Consumer ' ++ vars.vConsumerId ++ ' released ' ++ vars.vOrderId ++ ' after ' ++ error.errorType.namespace ++ ':' ++ error.errorType.identifier ++ ', correlationId=' ++ correlationId]" />
			</on-error-propagate>
		</error-handler>
	</try>
</foreach>

In the repository: src/main/mule/eip/competing-consumers/competing-consumers.xml

The two handlers separate the two outcomes of the attempt. OS:KEY_ALREADY_EXISTS is not a failure: it means another consumer got there first, and the on-error-continue only counts the item as already claimed and moves on to the next. Any other error falls into the on-error-propagate, which has no type: it is almost always the invoice issuing, after the claim, but it can be a failure of the store itself at the claim, and the example does not tell the two cases apart. There the consumer deletes its own claim (os:remove) and the on-error-propagate ends its run with an error. The item is free again, and the next run of any consumer claims it and issues the invoice.

The release happens only in the error handler. A consumer that stops between the claim and the issuing (the application restarts, the worker dies) leaves the claim written, and nothing in the example releases it: the item stays stuck. With a queue, the broker would redeliver the message that was not acknowledged. A real replacement for the channel would need a deadline for the claim, for example a timestamped claim (claimedAt is already written) and a rule to take over the old ones.

Caveats

  • The claim is atomic only on one worker, or in a cluster. The same page that guarantees key-level synchronization says that, in cluster mode, the guarantee also holds across nodes, and that running the application with store operations on several nodes without clustering can lead to inconsistent results for lack of coordinated locking (Object Store Connector Reference). On CloudHub with several workers, Object Store v2 can have discrepancies or key conflicts, because distributed locking is not available there, and the documentation suggests a distributed key-value store as a lock (Object Store v2 Overview). In a Stack Overflow case, a counter incremented by a Scheduler in an Object Store was not shared across nodes, and the answer points out that CloudHub’s Object Store does not lock across workers (Is Objectstore Not Shared Through Cluster Environment?). This is the strongest reason to use a queue when there is more than one replica (this page’s recommendation).
  • With a queue, redelivery can give the same message to another consumer. KB article 001119407 describes Anypoint MQ messages processed two or more times, every two minutes: with AUTO acknowledgment, the Subscriber does not respect the acknowledgment timeout set on the queue, and a message whose processing takes longer than two minutes goes back to the queue and is delivered again. The article’s fix is to set acknowledgementTimeout on the Subscriber itself (Anypoint MQ Message Getting Processed Twice). This page’s reading, which the article does not state: with several consumers, the second delivery can land on another consumer while the first is still working, because the channel’s single delivery holds per delivery, not per processing; the consumer has to be idempotent all the same.
  • A topic is not a queue. In a 2023 Stack Overflow case, the question was whether several workers reading a queue would not process the same message twice; the comment answers that, on a queue, only the first to fetch processes it, and the author clarifies that they were listening to a topic, where several queues receive the same message (How Queues behave in mule 4 multi workers API?). It is the book’s observation: consumers on a publish-subscribe channel receive copies, they do not compete.
  • Several consumers lose ordering. Three issuers in parallel finish in any order. The Anypoint MQ documentation says that preserving the order of a FIFO queue calls for the Subscriber’s polling strategy, which is not the default, with maxConcurrency equal to 1 on the consuming flow (Anypoint MQ Subscriber Source), which undoes the competition.

When not to use it

When a single consumer keeps up with the volume, competition only brings the problems above. When message order matters, it is lost in parallel. And when the work lives in a database or a list and not in a queue, the example’s claim works on one worker, but leads back to the first caveat’s question as soon as there are two; at that point, putting a queue between producer and consumer is usually simpler than building the lock (this page’s recommendation, backed by the Object Store limits cited).

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 number of consumers (eip.competingConsumers.consumers, 3) and the time to issue each invoice (eip.competingConsumers.workMillis, 50) are in app.yaml. The competing-consumers-test-suite.xml suite pins down the behavior, observed on Mule 4.9.17 with MUnit 3.7.1:

Test What it proves
cc-each-item-is-processed-by-exactly-one-consumer Three consumers at the same time over nine items: all nine are processed, none twice, nine invoices issued, item 5 is claimed by the consumer that reports it
cc-item-claimed-by-another-consumer-is-skipped An item already claimed by another consumer is skipped and gets no invoice; the free item gets one
cc-invalid-work-and-unknown-item A list without orderIds, or a run with more consumers than configured, gets 400; an unknown item, 404
cc-failed-item-is-processed-on-the-next-run When the issuing fails, the claim is deleted and the next run, by another consumer, claims the item and issues one invoice

The first test checks the division of the work and the absence of repeats:

<munit-tools:assert-that doc:name="Three consumers ran" expression="#[vars.vRuns.body.consumers map $.consumer]" is="#[MunitTools::equalTo(['consumer-1', 'consumer-2', 'consumer-3'])]" />
<munit-tools:assert-that doc:name="Every item processed" expression="#[flatten(vars.vRuns.body.consumers map ($.processed filter ($ startsWith 'ORD-CC-ITEM-'))) orderBy $]" is="#[MunitTools::equalTo(['ORD-CC-ITEM-1','ORD-CC-ITEM-2','ORD-CC-ITEM-3','ORD-CC-ITEM-4','ORD-CC-ITEM-5','ORD-CC-ITEM-6','ORD-CC-ITEM-7','ORD-CC-ITEM-8','ORD-CC-ITEM-9'])]" />
<!-- Evidence, not proof, of concurrency: consumers that ran one after the other would leave all items to the first one. -->
<munit-tools:assert-that doc:name="Work spread over more than one consumer" expression="#[sizeOf(vars.vRuns.body.consumers filter (not isEmpty($.processed filter ($ startsWith 'ORD-CC-ITEM-'))))]" is="#[MunitTools::greaterThan(1)]" />
<munit-tools:assert-that doc:name="Consumers met each other's claims" expression="#[sum(vars.vRuns.body.consumers map $.alreadyClaimed)]" is="#[MunitTools::greaterThan(0)]" />
<munit-tools:assert-that doc:name="No item processed twice" expression="#[sizeOf(flatten(vars.vRuns.body.consumers map ($.processed filter ($ startsWith 'ORD-CC-ITEM-'))) distinctBy $)]" is="#[MunitTools::equalTo(9)]" />

In the repository: src/test/munit/eip/competing-consumers-test-suite.xml

The comment in the test states the limit of what it proves: more than one consumer having processed items, and the consumers having bumped into each other’s claims, is evidence that they ran at the same time, not proof. Consumers running one after the other would leave everything to the first. That is why the OS:KEY_ALREADY_EXISTS path has a test of its own, with the claim written beforehand, where the result does not depend on chance.

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

### EIP competing consumers — put work on the list, then run three consumers at once
POST {{base}}/eip/invoice-work/items
Content-Type: application/json

{ "orderIds": ["ORD-4501", "ORD-4502", "ORD-4503", "ORD-4504", "ORD-4505", "ORD-4506"] }

###
POST {{base}}/eip/invoice-work/runs
Content-Type: application/json

{ "consumers": 3 }

###
GET {{base}}/eip/invoice-work/items/ORD-4503

In the repository: requests.http

The run’s response says what each consumer processed and how many items it found already claimed; the GET says who got the order and how many invoices it received. 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