← Wiki

Process Manager in Mule: driving an order, payment, stock and invoice with stored state

  • 16 min read
On this page

Code

In the series’ order scenario, an order goes through payment, stock reservation and invoicing, and each step starts only if the previous one succeeded. When the services reply later, in another request and sometimes hours afterward, something has to remember which step each order is at and decide what comes next. That something is the Process Manager. Mule has no component with that name: this page’s example builds the pattern from HTTP, Object Store and Choice, and has MUnit tests.

The problem

Order ORD-6102 pays 120 for 2 units of SKU-OUT-1. The payment answers “approved” ten seconds later. The stock reservation answers “unavailable” an hour later. In that case the payment that was already approved has to be refunded, and the invoice must never go out. Had the payment been declined, nothing else should have happened.

Three things call for a solution. The path depends on the replies, so the list of steps cannot be written before the order starts. Between a step and its reply, the order has to exist somewhere, even if the application restarts. And each reply has to be tied to the right order, because the replies of many orders arrive mixed together.

The pattern in the book

The book starts from the Routing Slip, which routes a message through a dynamic series of steps but assumes the sequence is known in advance and is linear. When the decisions depend on intermediate results, or the steps may run in parallel, those assumptions do not hold. The pattern’s question is how to route a message through several processing steps when the required steps may not be known at design time and may not be sequential. The answer: use a central processing unit, the Process Manager, to keep the state of the sequence and to decide the next step from the intermediate results (Process Manager).

The incoming message, called the trigger message, initializes the Process Manager. It sends a message to the first processing unit; when the unit finishes, it replies to the Process Manager, which decides the next step. All the traffic passes through this center (hub-and-spoke), and the book itself lists the risk: the Process Manager can become a performance bottleneck. The book also warns that it can serve almost any integration problem and that using it in every situation may be overkill (Process Manager). The Routing Slip is the neighboring pattern, for the fixed sequence.

Order ORD-6102, the trigger message, reaches the Process Manager, which keeps the state and decides. It sends step 1 to Payment and gets the reply; sends step 2 to Stock and gets the reply; sends step 3 to Invoice and gets the reply.

Trigger, definition and instance

Each trigger message creates a new process. James Carr distinguishes the process definition from the instance: the definition is the mold, with the steps, the valid transitions and the conditions that decide the route; the instance is one execution of that definition, with a correlation identifier, a current state and intermediate results (Advent of EIP, day 10). The book’s page does not make this distinction. In the example, the decision table and the state diagram are the definition, and each Object Store record, with the processId as its key, is an instance.

The post from The Whiteboard Architect describes the manager as a stateful router with three tasks: matching each incoming message to the instance in progress, updating its state and sending the command to the next participant (Process Manager with Temporal).

Orchestration and choreography

In orchestration, a central controller tells each service what to do; in choreography, each service reacts to events (Advent of EIP, day 10). The Process Manager is orchestration. For Carr, orchestration is easier to trace and suits the complex flow inside one context; choreography suits low coupling between contexts (Advent of EIP, day 10). The Whiteboard Architect prefers orchestration for its explicit, debuggable flow, and points to the central coordinator as a coupling point (Process Manager with Temporal).

What belongs to the manager and what belongs to the services

The manager handles business time: the deadline for a component to say it has finished, and the escalation when it does not. Repeating a call and the rest of the failure mechanics stay in each service, which is why they have to be idempotent. When a component fails for good, the process moves to a review state (Advent of EIP, day 10). The example has no deadline and no retry in the services (see “A reply that never comes” in Caveats); its review states are SUSPENDED and COMPENSATION_FAILED. When a step fails or times out after another one has succeeded, the manager commands the compensation (Process Manager with Temporal).

Durable state, here and on other platforms

Carr describes durability in two parts: the state is written before each transition and, after a crash, the processes in progress are resumed (Advent of EIP, day 10). The example does the first part, writing the state to the persistent Object Store before sending each command. It does not do the second: nothing resumes a stopped process on its own.

Workflow platforms provide both. The pattern’s page on the book’s site, in an example added later, uses AWS Step Functions as the Process Manager (Process Manager); Standard workflows keep the execution history (Step Functions documentation). In Temporal, after a crash, the state is rebuilt by re-running the workflow code over the event history (Temporal documentation). In both, the platform keeps the state; in Mule, the flow writes the correlation, the decision and the receipt.

In Mule

Mule 4 has no Process Manager component; the pattern is assembled from the series’ pieces. The processId is the Correlation Identifier: it goes in the command of each step and comes back in the reply. The endpoint that receives the replies is the reply channel of an asynchronous Request-Reply. The state lives in an Object Store declared persistent="true"; the connector’s overview says a persistent store “survives a Mule Runtime crash” (Object Store connector). And the decision of the next step is a DataWeave match followed by a Choice, the same decision as the Content-Based Router (Choice router).

The application exposes three manager endpoints and, for each step, a simulated service:

Endpoint Role
POST /eip/process-manager/orders The trigger message: creates the process and answers 202 RUNNING with the processId
POST /eip/process-manager/replies A step’s reply; the manager decides what comes next
GET /eip/process-manager/processes/{processId} The state: status, currentStep and history
POST /eip/process-manager/services/{payment|stock|invoice|refund} The simulated services, in the same application

Commands and replies are HTTP calls to the application itself, with no broker. Each service answers 202 right away and returns the result later, from an Async scope, which runs its processors “in a different thread, while the main flow continues” (Async scope).

The POST orders call creates the process at the PAYMENT step. PAYMENT goes to STOCK on APPROVED and to FAILED on DECLINED. STOCK goes to INVOICE on RESERVED and to COMPENSATING on UNAVAILABLE. INVOICE goes to COMPLETED on ISSUED. COMPENSATING goes to CANCELLED on REFUNDED and to COMPENSATION_FAILED on FAILED.

PAYMENT, STOCK and INVOICE are steps, with the process RUNNING. COMPENSATING is the status in which the REFUND step waits for its reply; the others are final statuses. The diagram leaves out SUSPENDED, where any step lands when the command does not go out (see Caveats).

In the MuleSoft documentation

The documentation page Enterprise Integration Patterns Using Mule does not list the Process Manager. Of the pieces this page uses, it maps the Content-Based Router (Choice Router) and Request-Reply; the Object Store, which keeps the state, does not appear in it.

The example

The decision is a table of step and outcome pairs. The match returns the process’s new status and the next step, and an outcome that the step does not have falls into the else and becomes a 400:

<ee:transform doc:name="Decide Next Step">
    <ee:variables>
        <ee:set-variable variableName="vDecision"><![CDATA[%dw 2.0
output application/java
---
(vars.vReply.step ++ ":" ++ vars.vReply.outcome) match {
    case "PAYMENT:APPROVED" -> { status: "RUNNING", nextStep: "STOCK" }
    case "PAYMENT:DECLINED" -> { status: "FAILED", nextStep: null }
    case "STOCK:RESERVED" -> { status: "RUNNING", nextStep: "INVOICE" }
    case "STOCK:UNAVAILABLE" -> { status: "COMPENSATING", nextStep: "REFUND" }
    case "INVOICE:ISSUED" -> { status: "COMPLETED", nextStep: null }
    case "REFUND:REFUNDED" -> { status: "CANCELLED", nextStep: null }
    case "REFUND:FAILED" -> { status: "COMPENSATION_FAILED", nextStep: null }
    else -> null
}]]></ee:set-variable>
    </ee:variables>
</ee:transform>

In the repository: src/main/mule/eip/process-manager/process-manager.xml

The refund is the compensation: stock ran out after the payment was approved, so the manager sends the REFUND step and the process goes through COMPENSATING until it reaches CANCELLED. It is the compensation of the Transactional Client, undoing the step that succeeded when the next one fails, with the difference that here the compensation is a step of the process, with its own reply and state.

Before sending a command, the manager writes the state, with the current step and a SENT entry in the history. The order matters because the reply can come back before the command’s 202 response arrives:

<ee:transform doc:name="Record Command Sent">
    <ee:variables>
        <ee:set-variable variableName="vState"><![CDATA[%dw 2.0
output application/java
---
vars.vState ++ { history: vars.vState.history << { step: vars.vState.currentStep, event: "SENT", at: now() as String } }]]></ee:set-variable>
    </ee:variables>
</ee:transform>
<os:store doc:name="Store Process State" key="#[vars.vState.processId]" objectStore="eip-pm-process-store">
    <os:value><![CDATA[#[output application/java --- vars.vState]]]></os:value>
</os:store>

Each reply is applied once per process and step. The manager writes a receipt keyed processId:step with failIfPresent="true": with that parameter, the store throws OS:KEY_ALREADY_EXISTS instead of overwriting (Object Store connector reference). Of two copies of the same reply arriving together, only one gets the receipt:

<try doc:name="Try Claim Reply">
    <os:store doc:name="Claim Reply Receipt" key="#[vars.vReply.processId ++ ':' ++ vars.vReply.step]" objectStore="eip-pm-receipts-store" failIfPresent="true">
        <os:value><![CDATA[#[output application/java --- { outcome: vars.vReply.outcome, receivedAt: now() as String }]]]></os:value>
    </os:store>
    <error-handler>
        <on-error-continue doc:name="On Error Continue (a copy claimed it first)" type="OS:KEY_ALREADY_EXISTS" logException="false">
            <set-variable doc:name="SET vClaimLost" variableName="vClaimLost" value="#[true]" />
        </on-error-continue>
    </error-handler>
</try>

The copy that loses the receipt gets a 200 DUPLICATE and nothing changes. The same step with an outcome different from the one already applied gets a 409 Conflicting reply. A reply for a step the process is not waiting for, and that never arrived, also gets a 409. It is the same defense as the Idempotent Receiver, applied per step instead of per message.

The simulated service picks the outcome from the command, so the demo and the tests can force each path: the payment is DECLINED when the amount is above 1000 (eip.processManager.paymentLimit), and the stock is UNAVAILABLE when the sku starts with SKU-OUT:

<async doc:name="Async Reply Later">
    <ee:transform doc:name="Perform Step">
        <ee:message>
            <ee:set-payload><![CDATA[%dw 2.0
output application/json
var c = vars.vCommand
---
{
    processId: c.processId,
    step: vars.vStep,
    outcome: vars.vStep match {
        case "PAYMENT" -> if (c.amount > (p('eip.processManager.paymentLimit') as Number)) "DECLINED" else "APPROVED"
        case "STOCK" -> if ((c.sku default "") startsWith "SKU-OUT") "UNAVAILABLE" else "RESERVED"
        case "INVOICE" -> "ISSUED"
        else -> "REFUNDED"
    },
    reference: vars.vStep ++ "-" ++ uuid()
}]]></ee:set-payload>
        </ee:message>
    </ee:transform>
    <try doc:name="Try Send Reply">
        <http:request doc:name="POST Reply To Process Manager" config-ref="eip-self-http-request-config" method="POST" path="${eip.processManager.replyPath}" />
        <error-handler>
            <on-error-continue doc:name="On Error Continue (reply lost)" type="ANY" logException="false">
                <logger doc:name="WARN: Log reply lost" level="WARN" message="#['Reply ' ++ vars.vStep ++ ' for process ' ++ (vars.vCommand.processId default '') ++ ' not delivered (' ++ error.errorType.namespace ++ ':' ++ error.errorType.identifier ++ '), correlationId=' ++ correlationId]" />
            </on-error-continue>
        </error-handler>
    </try>
</async>

In the repository: src/main/mule/eip/process-manager/process-manager-services.xml

On the happy path, the process’s GET ends in COMPLETED with six history entries: PAYMENT:SENT, PAYMENT:REPLY:APPROVED, STOCK:SENT, STOCK:REPLY:RESERVED, INVOICE:SENT and INVOICE:REPLY:ISSUED. An order of 5000 ends in FAILED right after the payment reply, with no stock or invoice step.

Caveats

  • The state has no lock. The receipt serializes the replies of the same step, but reading the state, changing it and writing it back are separate operations. The only point with extra protection is SUSPENDED: the write rereads the state and suspends only if the current step and the history are still the ones it sent, otherwise it keeps the newer state (compare-and-set). Rereading and writing are two operations, not one atomic step, even on a single worker. The connector itself warns that the Object Store does not support transactional access and that, for the same key updated in parallel, another solution is advisable (overview).
  • The receipt holds as far as the store goes. The receipt is atomic per key on one worker; across workers, only in a Mule cluster, where the connector reference says the synchronization “is also guaranteed across nodes”. A public case: in a MuleSoft knowledge base article, the Salesforce connector’s listener, which keeps state in an OSv2, fails with “Object already exists for the key” when it runs on several CloudHub workers that write the same key at the same time, and the way out the article gives is to run on a single worker (MuleSoft KB). The lesson for the manager is the same: a single worker, or a Mule cluster.
  • A command that does not go out. If the manager cannot send the command, the process stays SUSPENDED with the error, caught by a Try scope. The start endpoint answers 503 with the processId in the body; the replies endpoint, whose reply was applied, answers 200 APPLIED with status SUSPENDED, because the service that replied did its part. The example has no endpoint to resume: SUSPENDED and COMPENSATION_FAILED call for recovery by hand or through a Scheduler.
  • A reply that never comes. There is no timeout: a service that does not reply leaves the process waiting at the step. A real manager needs a Scheduler that looks for processes stopped for too long. The test pm-reply-lost-leaves-process-waiting shows the case: the loss goes to the log and the process stays RUNNING at PAYMENT.
  • The state grows. The runtime’s local store has no TTL by default; in Object Store v2 the default entryTtl is 30 days (connector reference). The receipts store keeps each receipt for 7 days (entryTtl); the processes store keeps all of them, so in production it also needs a TTL or a cleanup. In Object Store v2, an expirationInterval that is blank or less than or equal to zero makes the entryTtl be ignored (OSv2 guide).
  • The receipt goes out before the state. In process-manager.xml, the receipt (Claim Reply Receipt, line 152) is written before the state (Store Process State, line 259, or Store Ended Process, line 243). If the runtime crashes between the two, the copy that resends the reply gets DUPLICATE and the process stays stuck at the step.
  • Persistent is not tested. That the process survives a restart is the connector’s guarantee for a persistent store (overview); MUnit does not show it.
  • The manager can become the bottleneck. It is the risk the book points out. And, since every process goes through it, if it goes down, no process moves.

When not to use it

If all the steps reply synchronously within one request, a single flow that calls payment, stock and invoice in sequence, with a Choice for each outcome and a Try for the refund, is already the orchestration, and its state is the request itself: no store, no replies endpoint, no correlation. The Process Manager pays off when the steps reply asynchronously or take long, when the process has to survive a restart between steps, or when the next step depends on the results in a way that a fixed sequence cannot express.

The choice fits on a spectrum with three points. In the Routing Slip, the sequence is known in advance and linear (Routing Slip), and the state travels in the message. In the Process Manager, the state is in the coordinator, which decides the next step from the results. At the opposite end is a dedicated, distributed workflow engine, with more visibility and control and more operational complexity (Advent of EIP, day 10).

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 process-manager-test-suite.xml suite has 15 tests, observed on Mule 4.9.17 with MUnit 3.7.1. In the end-to-end tests, the services reply on their own and the test polls the state until it changes, instead of sleeping:

Test What it proves
pm-happy-path-completes The order is paid, reserved and invoiced; the process ends COMPLETED with the whole history
pm-declined-payment-fails A payment above the limit ends FAILED, with no stock or invoice
pm-stock-unavailable-refunds-and-cancels Without stock, the manager refunds and ends CANCELLED, with no invoice
pm-duplicate-reply-is-applied-once With the services silenced, the same payment reply sent twice is APPLIED and then DUPLICATE; a reply for the wrong step is 409
pm-concurrent-copies-apply-once Two copies sent at the same time: one APPLIED, the other DUPLICATE (the second receipt hits OS:KEY_ALREADY_EXISTS)
pm-conflicting-reply-is-409 DECLINED after APPROVED was applied is 409 and the state does not change
pm-reply-for-unknown-process-is-404 A reply and a GET for a processId that nobody started give 404
pm-late-reply-after-completion-is-409 After COMPLETED, a late copy of the invoice reply and a DECLINED payment reply (the payment had been APPROVED) give 409, and the history stays at six entries
pm-invalid-requests-are-400 An order without a positive integer quantity, a reply without an outcome and an outcome the step does not have give 400; the unknown outcome does not move the process
pm-command-not-sent-suspends-the-process A payment command that does not go out: 503 with the processId and the process SUSPENDED; a reply for it is 409
pm-reply-applied-next-command-not-sent-is-200-suspended The payment reply is applied, the stock command does not go out: 200 APPLIED with SUSPENDED
pm-suspend-does-not-overwrite-a-newer-state If the state has already advanced to STOCK before the error is handled, the process is not suspended
pm-refund-failed-ends-compensation-failed The refund answers FAILED: the process ends COMPENSATION_FAILED and a late reply is 409
pm-reply-lost-leaves-process-waiting A reply that the service cannot deliver goes to the log and the process waits at PAYMENT
pm-unknown-service-is-404 A step that is not payment, stock, invoice or refund gives 404

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

### EIP process manager — start a process (amount above 1000 is declined; sku SKU-OUT... is out of stock), then read it
POST {{base}}/eip/process-manager/orders
Content-Type: application/json

{ "orderId": "ORD-6101", "amount": 120, "sku": "SKU-BOOK", "quantity": 2 }

###
# Replace PM-... with the processId from the response above
GET {{base}}/eip/process-manager/processes/PM-replace-me

In the repository: requests.http

Changing the sku to SKU-OUT-1, the same GET ends in CANCELLED after the refund. The other patterns, with the Mule component that implements each one, are in the catalog of integration patterns in Mule and, by component name, in the index by component.

Code for this page