← Wiki

Event-Driven Consumer in Mule: the payment event updates the order as it arrives

  • 10 min read
On this page

Code

The payment provider notifies when a payment is confirmed or declined, and the order has to change state as soon as the notice arrives, without anyone asking every so often whether there is news. Consuming each message at the moment it is delivered is the problem the Event-Driven Consumer solves. In Mule, it is a flow that starts with a trigger: here, the HTTP Listener; with messaging, the VM Listener or the Anypoint MQ Subscriber.

The problem

The provider sends PAYMENT_CONFIRMED or PAYMENT_FAILED for order ORD-4301. If the order service fetched these events every minute, the order could spend up to a minute without knowing it was paid, and the service would burn queries in the minutes when nothing happened. What is wanted is the opposite: nothing runs while there is no event, and each event triggers processing the moment it arrives.

The pattern in the book

The book asks how an application can consume messages automatically, as they become available. The solution is an Event-Driven Consumer, which receives messages automatically as they are delivered on the channel (Event-Driven Consumer). The book also calls it an asynchronous receiver, because it has no thread running until a callback thread hands it a message: the delivery is an event that puts the receiver into action. The messaging system invokes the consumer when the message reaches the channel, and the consumer passes it to the application through a callback. How the system obtains the message is an implementation detail, and may or may not be event-driven; all the consumer knows is that it can sit idle, with no active thread, until it is invoked.

The opposite is the Polling Consumer, which goes and fetches the message when it wants to. 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:

The Payment provider sends the event to the channel; the channel delivers and invokes the Consumer (orders), which writes the order state.

In Mule

Some connectors have sources, or triggers: components that let the connector start a flow when it receives information from its resource. The HTTP Listener and the Scheduler also serve as a flow’s source (Anypoint Connectors Overview). A flow that starts with an event-driven source is an Event-Driven Consumer: Mule invokes the flow when the message arrives, and between one message and the next the flow does not run. The Scheduler, which starts the flow by time, is the source of the Polling Consumer.

In the example, the source is the HTTP Listener. When it receives a request, it triggers the flow with the request’s data, and, when the flow ends, it sends the HTTP response according to the result (Configure HTTP Listener Source). The flow runs once per event, and the event has already been processed when the provider receives the response.

With messaging, the most direct form of the pattern is the Anypoint MQ Subscriber (<anypoint-mq:subscriber>): the application declares the queue it listens to, and Mule triggers the flow with each message that arrives on it. In the default strategy, prefetch, the source listens continuously and consumes messages as they reach the queue (Anypoint MQ Subscriber Source). The VM Listener (<vm:listener>) does the same over the VM Connector’s queues (VM Connector Reference). The shape of the flow is the one on this page, with a different source. The example uses the HTTP Listener only because the project runs without a broker and does not simulate one with VM.

Underneath, it is the connector that goes and gets the messages from the broker. With prefetch, it keeps a local buffer of messages, ready to hand to the flow when the application accepts them; with the polling strategy, it queries the queue at a fixed frequency and brings up to 10 messages at a time, which it hands to the flow one by one, in order (Anypoint MQ Subscriber Source). The flow is still called for each message, without asking anything. The book allows for this: how the consumer obtains the message may or may not involve polling (Polling Consumer). As this page reads it, what separates the two patterns is who decides the time: in the Subscriber, the connector delivers when there is a message; in the Polling Consumer, the flow decides when to ask.

The POST /eip/payment-events endpoint validates eventId, orderId and type. If they are not valid, the failure path answers 400; if they are, os:store writes the order state and answers 200 CONSUMED. Separately, the GET /eip/payment-events/{orderId} endpoint reads the state, PAID or PAYMENT_FAILED, with os:retrieve.

Anypoint MQ also has the Consume operation, which takes a single message when the flow asks for it (Anypoint MQ Subscriber Source). That is the shape of the Polling Consumer: the connector is the same, and the pattern changes with the source or operation chosen.

In the MuleSoft documentation

The documentation page Enterprise Integration Patterns Using Mule does not list the Event-Driven Consumer. The closest row is the Message Endpoint’s, which it maps to the Mule SDK’s sources and operations; the sources page, Creating Message Sources with the Mule SDK, gives the HTTP Listener as an example of a source, the same one used on this page. The same table maps the Polling Consumer to that sources page; this series separates the two by source: the one that reacts to the event is an Event-Driven Consumer, and the Scheduler, which queries, is a Polling Consumer.

The example

The flow starts at the HTTP Listener, validates the event and stores the order’s state:

<http:listener doc:name="POST /eip/payment-events" config-ref="http-listener-config" path="/eip/payment-events" allowedMethods="POST">
	<http:response statusCode="#[vars.httpStatus default 200]" />
</http:listener>
<choice doc:name="Validate Payment Event">
	<when expression="#[(not (payload is Object)) or isEmpty(payload.eventId) or isEmpty(payload.orderId) or not (['PAYMENT_CONFIRMED', 'PAYMENT_FAILED'] contains payload.'type')]">
		<raise-error doc:name="Raise BAD_REQUEST Error - Bad event" type="APP:BAD_REQUEST" description="eventId, orderId and type (PAYMENT_CONFIRMED or PAYMENT_FAILED) are required" />
	</when>
</choice>
<set-variable doc:name="SET vEvent" variableName="vEvent" value="#[output application/java --- payload]" />
<os:store doc:name="Store Payment State" key="#[vars.vEvent.orderId]" objectStore="eip-payment-event-state-store">
	<os:value><![CDATA[#[output application/java --- {
	orderId: vars.vEvent.orderId,
	status: if (vars.vEvent.'type' == "PAYMENT_CONFIRMED") "PAID" else "PAYMENT_FAILED",
	lastEventId: vars.vEvent.eventId,
	processedAt: now() as String
}]]]></os:value>
</os:store>

In the repository: src/main/mule/eip/event-driven-consumer/event-driven-consumer.xml

There is no Scheduler and no loop: the flow runs only while a request is being served. GET /eip/payment-events/{orderId} reads the state the events left behind, and answers 404 for an order that received no event.

Each event overwrites the order’s state, so the last one stored decides. The flow imposes no order of its own: in the tests, events go one after the other, and the last one sent wins; events sent at the same time would run in parallel, and the last write would win. The flow also does not check the eventId, so a repeated event is applied again. Both choices keep the example the size of the pattern; the caveats below say what changes in a real consumer.

Caveats

  • Repeated events. An event-driven consumer receives what the channel delivers, including the same message twice. In Anypoint MQ, the Subscriber’s default acknowledgment mode is AUTO: the message is acknowledged only when the flow ends without an error, and, if the flow ends with a propagated error, it goes back to the queue and is delivered again (Anypoint MQ Subscriber Source). The JMS listener does the same: it acknowledges at the end of a successful flow and, on error, recovers the session and the message is redelivered (Listen for New Messages Using the JMS Connector). A flow that already wrote part of its work before failing will do that part again. The edc-repeated-event-is-applied-again test shows the effect in the example; the Idempotent Receiver shows how to refuse the repeat.
  • Order. Delivering at the moment of arrival does not guarantee processing in arrival order. In the Anypoint MQ documentation, preserving the order of a FIFO queue calls for the polling strategy, which is not the default, with maxConcurrency set to 1 on the consuming flow, and that makes each fetch bring one message at a time, with many more API calls (Anypoint MQ Subscriber Source). In the example, a PAYMENT_FAILED that arrives after a PAYMENT_CONFIRMED leaves the order as failed. When order matters, the event has to carry what allows it to be ordered (a sequence number or a source timestamp) and the consumer has to compare before writing.
  • Acknowledging before processing loses messages. In Anypoint MQ’s IMMEDIATE mode, the message is acknowledged, that is, deleted from the queue, before it goes to the flow; if the application restarts between the acknowledgment and the processing, the message may no longer be available (Anypoint MQ Subscriber Source). The book makes the same observation in its RabbitMQ example: a consumer that acknowledges on receipt, before processing, is not a Transactional Client (Event-Driven Consumer).
  • Over HTTP, the sender waits for the processing. The HTTP Listener responds only when the flow ends (Configure HTTP Listener Source). That is what assures the provider the event was applied, but it also makes the provider wait for the whole processing and receive an error if the flow fails. For long processing, this page recommends putting a queue between the provider and the flow: the provider gets its response when the event enters the queue, and the queue’s consumer does the work.

When not to use it

When the consumer needs to control the pace, the Event-Driven Consumer lets the channel decide when work arrives, and peaks arrive with it. A system that can only take one batch a minute, or a source that announces nothing, such as a database table or a folder of files, calls for the Polling Consumer. And when one consumer cannot keep up with the volume, the answer is to have several reading the same channel, which brings the work-splitting problems of 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 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 event-driven-consumer-test-suite.xml suite pins the behavior, observed on Mule 4.9.17 with MUnit 3.7.1:

Test What it proves
edc-event-is-processed-as-it-arrives The HTTP Listener runs the flow when the event arrives; a GET right after the 200 already sees the order PAID, with no polling
edc-each-event-runs-the-flow-once-and-the-last-one-stored-decides Two events for the same order, sent one after the other, run the flow once each, and the last one stored decides the state
edc-invalid-event-returns-400-and-unknown-order-404 An event without a known type gets 400 and changes nothing; an order with no event gets 404
edc-repeated-event-is-applied-again Nothing checks the eventId, so the same event sent twice runs the flow twice

The first test sends the event, reads the state right after and checks that the flow ran once:

<munit-tools:assert-that doc:name="200" expression="#[vars.vResponse.status]" is="#[MunitTools::equalTo(200)]" />
<munit-tools:assert-that doc:name="JSON" expression="#[vars.vResponse.contentType]" is="#[MunitTools::startsWith('application/json')]" />
<munit-tools:assert-that doc:name="Consumed" expression="#[vars.vResponse.body.result]" is="#[MunitTools::equalTo('CONSUMED')]" />
<munit-tools:assert-that doc:name="Order already PAID" expression="#[vars.vState.body.status]" is="#[MunitTools::equalTo('PAID')]" />
<munit-tools:assert-that doc:name="By this event" expression="#[vars.vState.body.lastEventId]" is="#[MunitTools::equalTo('EVT-EDC-1')]" />
<munit-tools:assert-that doc:name="State JSON" expression="#[vars.vState.contentType]" is="#[MunitTools::startsWith('application/json')]" />
<munit-tools:verify-call doc:name="One run per event" processor="logger" times="1">
	<munit-tools:with-attributes>
		<munit-tools:with-attribute attributeName="doc:name" whereValue="INFO: Log event consumed" />
	</munit-tools:with-attributes>
</munit-tools:verify-call>

In the repository: src/test/munit/eip/event-driven-consumer-test-suite.xml

To call the endpoints, run the application in Anypoint Studio (port 8081) and use the Event-Driven Consumer entries in requests.http:

### EIP event-driven consumer — processed when it arrives
POST {{base}}/eip/payment-events
Content-Type: application/json

{ "eventId": "EVT-4301", "orderId": "ORD-4301", "type": "PAYMENT_CONFIRMED" }

###
GET {{base}}/eip/payment-events/ORD-4301

In the repository: requests.http

Send the same event with "type": "PAYMENT_FAILED" to see the last event decide the state. 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