Transactional Client in Mule: the debit and the paid order written together, or neither
- 11 min read
On this page
Code
A payment makes two writes: the debit in the payments ledger and the PAID status on the order. If the first succeeds and the second fails, a debit is left for an order that is still unpaid. Transactional Client solves this by putting both operations inside a transaction that the client itself opens and closes. In Mule, the Try scope or the flow’s source opens the transaction, but it only covers operations of transactional connectors. The example uses the Object Store, which is not transactional, and shows both things: the Try that looks transactional and is not, and the compensation that is left.
The problem
Order ORD-5201 receives a payment of 50. The flow writes the debit, then tries to mark the order as paid, and the second write fails. The client gets 500, but the debit is already in the ledger. Checking the ledger shows a charge; checking the order shows an open order. The client’s second attempt runs into the debit that was left.
The pattern in the book
The book asks how a client can control its transactions with the messaging system. The solution is to make the client’s session with the messaging system transactional, so the client can specify the transaction boundaries (Transactional Client).
Sender and receiver can both be transactional. For the sender, the message enters the channel only when it commits the transaction; for the receiver, the message leaves the channel only when it commits. A sender with an explicit transaction can work with a receiver with an implicit transaction, and the other way around.
The book’s page has a note about the cloud: Transactional Client semantics can degrade performance heavily in highly distributed systems, which is why many cloud messaging systems do not implement it. Amazon SQS, for example, uses the Visibility Timeout: the consumer does not remove the message, it only becomes invisible to the others, and becomes visible again if it is not deleted within the deadline.
The diagram redraws the book’s sketch (CC BY 4.0) in the order scenario:
In Mule
In Mule 4, only the flow’s source (such as jms:listener and vm:listener) and the Try scope define the transaction type (Transaction Management). The Try treats the child operations as one transaction when transactionalAction is ALWAYS_BEGIN or BEGIN_OR_JOIN (Try Scope). The condition is in the transactions documentation: in a local transaction (Single Resource), the operation must support transactions, and all operations must be of the same connector and use the same global configuration (config-ref) (Transaction Management).
The transactional connectors have their own transactions pages. In the Database Connector, several queries can run atomically inside a Try, with each operation in ALWAYS_JOIN or JOIN_IF_POSSIBLE (Database Connector Transactions). In the JMS Connector, a message published in a transaction is sent only after the commit, and a consumed message is acknowledged only after it; on a rollback, it goes back to the destination for redelivery (JMS Transactions). That is the book’s transactional receiver. To join different resources (VM, JMS and Database) in a single transaction, the documentation describes XA transactions, with two-phase commit (XA Transactions).
The example has none of these connectors: the project uses no external system and does not simulate a broker with VM. Both writes go to the Object Store, and the connector’s documentation says object stores do not support transactional access or modification (Object Store Connector). In that case, what is left is compensation: undoing the first write when the second fails. Compensation is not a transaction: another reader can see the debit before it is undone, and a crash between the failure and the undo, or an undo that fails, leaves the debit in place (this page’s inference).
In the MuleSoft documentation
The documentation page Enterprise Integration Patterns Using Mule maps Transactional Client to Transaction Management, the same page this one uses to explain when the Try opens a transaction. The example shows what is left outside it: with the Object Store, which does not support transactions, the way out is compensation.
The example
Both writes sit in a sub-flow that both endpoints use:
<sub-flow name="sf-debit-ledger-and-mark-order-paid" doc:description="The two writes of a payment that must succeed or fail together: the ledger debit, then the order's PAID status.">
<os:store doc:name="Write Ledger Debit" key="#[vars.vOrderId]" objectStore="eip-tc-ledger-store">
<os:value><![CDATA[#[output application/java --- { orderId: vars.vOrderId, amount: vars.vAmount, entry: 'DEBIT' }]]]></os:value>
</os:store>
<os:store doc:name="Mark Order Paid" key="#[vars.vOrderId]" objectStore="eip-tc-orders-store">
<os:value><![CDATA[#[output application/java --- { orderId: vars.vOrderId, status: 'PAID' }]]]></os:value>
</os:store>
</sub-flow>
In the repository: src/main/mule/eip/transactional-client/transactional-client.xml
Before: a Try with ALWAYS_BEGIN
The first endpoint puts the sub-flow inside a Try that asks for a local transaction:
<try doc:name="Try Charge In Transaction" transactionalAction="ALWAYS_BEGIN" transactionType="LOCAL">
<flow-ref doc:name="Refer to sf-debit-ledger-and-mark-order-paid" name="sf-debit-ledger-and-mark-order-paid" />
</try>
The XML looks like it says “both writes in one transaction.” It does not. The Try opens the transaction, but no operation inside it can join, because the Object Store does not support transactions (Object Store Connector) and the transactions documentation requires the operation to support them. Each write runs and stays done, whatever happens to the Try. When the second one fails, the caller gets 500 and the debit stays.
After: compensation
The second endpoint assumes there is no transaction and undoes the debit when the second write fails:
<try doc:name="Try Charge With Compensation">
<flow-ref doc:name="Refer to sf-debit-ledger-and-mark-order-paid" name="sf-debit-ledger-and-mark-order-paid" />
<error-handler>
<on-error-continue doc:name="On Error Continue (compensate the debit)" type="ANY" logException="false">
<logger doc:name="WARN: Log payment compensated" level="WARN" message="#['Payment of order ' ++ vars.vOrderId ++ ' failed (' ++ error.errorType.namespace ++ ':' ++ error.errorType.identifier ++ '), compensating the ledger debit, correlationId=' ++ correlationId]" />
<os:contains doc:name="Check Debit Written" key="#[vars.vOrderId]" objectStore="eip-tc-ledger-store" target="vDebitWritten" />
<choice doc:name="Check Debit To Undo">
<when expression="#[vars.vDebitWritten]">
<try doc:name="Try Undo Ledger Debit">
<os:remove doc:name="Undo Ledger Debit" key="#[vars.vOrderId]" objectStore="eip-tc-ledger-store" />
<error-handler>
<on-error-continue doc:name="On Error Continue (the undo failed)" type="ANY" logException="false">
<logger doc:name="ERROR: Log compensation failed" level="ERROR" message="#[output application/java --- 'Compensation of order ' ++ (vars.vOrderId as String) ++ ' failed (' ++ error.errorType.namespace ++ ':' ++ error.errorType.identifier ++ '), the ledger debit is still recorded, correlationId=' ++ correlationId]" />
<set-variable doc:name="SET vCompensationFailed" variableName="vCompensationFailed" value="#[true]" />
</on-error-continue>
</error-handler>
</try>
</when>
</choice>
<set-variable doc:name="SET vCompensated" variableName="vCompensated" value="#[true]" />
</on-error-continue>
</error-handler>
</try>
<choice doc:name="Check Compensated">
<when expression="#[vars.vCompensationFailed default false]">
<raise-error doc:name="Raise COMPENSATION_FAILED Error - Debit not undone" type="APP:COMPENSATION_FAILED" description="Payment not recorded and the compensation failed: the ledger debit is still recorded" />
</when>
<when expression="#[vars.vCompensated default false]">
<raise-error doc:name="Raise SERVICE_UNAVAILABLE Error - Payment not recorded" type="APP:SERVICE_UNAVAILABLE" description="Payment not recorded; the ledger debit was undone" />
</when>
</choice>
<set-payload doc:name="Set Paid Response" value="#[output application/json --- { orderId: vars.vOrderId, status: 'PAID' }]" />
The on-error-continue catches the failure of the writes. If the debit was written (Check Debit Written), it is removed. The removal has its own Try: if it fails, the flow sets vCompensationFailed and responds 500 with Payment not recorded and the compensation failed: the ledger debit is still recorded. If the removal succeeds, the flow responds 503 with Payment not recorded; the ledger debit was undone. The two codes tell the caller different things: 503 is “nothing was stored, you can try again”; 500 is “a debit is left without an order, someone needs to look.” If the first write already failed, there is nothing to undo, and the response is also 503.
Both endpoints refuse a second payment of the same order with 409, so the repeated attempt does not overwrite the debit that already exists.
Caveats
- A connector without transactions does not join the Try. In a 2019 MuleSoft forum case, in Mule 4, a Try with
ALWAYS_BEGINwrapped an SFTP write and a Salesforce update, and the SFTP was not undone when Salesforce failed. The answer points out that SFTP and Salesforce support neither local nor XA transactions and suggests the reliability pattern or sagas (Rollback not working with try scope in mule4 flow). That is the example’s case, with the Object Store in place of the two connectors. - On Error Continue commits the transaction. The Try documentation says
on-error-continuecompletes the Try successfully and commits the transactions in progress, and thaton-error-propagaterolls back and throws the error again (Try Scope). In a 2023 Stack Overflow case, database inserts inside a transactional Try were not rolled back because the handler wason-error-continue; the answer points toon-error-propagate(MuleSoft’s rollback database transaction problem). The example’s compensation useson-error-continueprecisely because there is no transaction to roll back. - The one that opened it rolls it back. When the transaction starts at the flow’s source and the Try only continues it, the Try’s
on-error-propagatedoes not roll back: only the flow’s handler can, because the flow opened it (Transaction Management). - Runtime version. KB article 001123111 describes, on Mule 4.2.0 and 4.2.1, a Try with
ALWAYS_BEGINand a database insert inALWAYS_JOINwhere the transaction was committed even with the error propagated; the fix is patch SE-12711 or Mule 4.2.2 (Transaction not being rolled back with error propagation on Mule 4.2.0 and 4.2.1). A test that makes the second operation fail and checks the database catches this kind of regression (this page’s recommendation).
When not to use it
When both writes can go to the same database, a Database Connector transaction solves it without compensation, and it is the way to prefer whenever the inconsistency between the two writes matters (this page’s recommendation). When the systems support neither transactions nor XA, like the SFTP and Salesforce of the forum case, the answer cited was the reliability pattern or sagas; the design becomes compensation or a process that tolerates intermediate states (this page’s recommendation). And when there is only one write, the transaction has nothing to group.
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 suite transactional-client-test-suite.xml pins the behavior, observed on Mule 4.9.17 with MUnit 3.7.1:
| Test | What it proves |
|---|---|
tc-both-writes-succeed |
With both writes successful, both endpoints respond 200 PAID and the ledger and the order have the payment |
tc-before-try-transaction-does-not-roll-back-the-debit |
Before: with the second write failing, the caller gets 500, the debit of 50 stays and the order is not paid |
tc-after-compensation-undoes-the-debit |
After: with the second write failing, the debit is undone, the caller gets 503 and no record stays |
tc-after-first-write-fails-nothing-to-undo |
After: with the debit itself failing, there is nothing to undo; 503 and nothing stored |
tc-invalid-payment-is-rejected |
A payment with amount 0 in “before,” or without orderId in “after,” gets 400 |
tc-second-payment-of-an-order-is-refused |
A second payment of an already paid order gets 409 on both endpoints, and the first debit stays |
tc-after-failed-compensation-answers-500 |
After: with the undo also failing, the caller gets 500 compensation failed and the debit stays stored |
The failure tests use mocks that return OS:STORE_NOT_AVAILABLE. tc-after-first-write-fails-nothing-to-undo mocks the first write, and tc-after-failed-compensation-answers-500 also mocks the debit’s removal. The mock of the second write:
<munit:behavior>
<munit-tools:mock-when doc:name="Mark Order Paid fails" processor="os:store">
<munit-tools:with-attributes>
<munit-tools:with-attribute attributeName="doc:name" whereValue="Mark Order Paid" />
</munit-tools:with-attributes>
<munit-tools:then-return>
<munit-tools:error typeId="OS:STORE_NOT_AVAILABLE" />
</munit-tools:then-return>
</munit-tools:mock-when>
</munit:behavior>
In the repository: src/test/munit/eip/transactional-client-test-suite.xml
The “before” test shows the result, the debit that is left, and does not test the attribute: no test runs the Try without ALWAYS_BEGIN. Since the Try has no transactional resource, the same Try without the attribute would leave the same debit (an inference from the transactions documentation). What the test proves is that the XML does not deliver what it seems to promise.
To call the endpoints, run the application in Anypoint Studio (port 8081) and use the Transactional Client entries in requests.http:
### EIP transactional client — before: Try with ALWAYS_BEGIN; after: compensation
POST {{base}}/eip/payments/transactional/before
Content-Type: application/json
{ "orderId": "ORD-5201", "amount": 50 }
###
POST {{base}}/eip/payments/transactional/after
Content-Type: application/json
{ "orderId": "ORD-5202", "amount": 70 }
###
GET {{base}}/eip/payments/transactional/ORD-5201
In the repository: requests.http
With the real stores, both calls succeed and the GET shows the debit and the order PAID: requests.http covers only the happy path, and the failing “before” and “after” are in the tests (tc-before-... and tc-after-...), which mock the second write. The other patterns are in the catalog of integration patterns in Mule and, by component name, in the index by component.