activemq.org › Handbook › What is an XA transaction? Two-phase commit with JMS and ActiveMQ
HandbookWhat is an XA transaction? Two-phase commit with JMS and ActiveMQ
An XA transaction is a distributed (global) transaction that spans more than one resource, such as a message broker and a database, so that the work on all of them is committed together or not at all. A transaction manager coordinates it with the two-phase commit protocol: it first asks every resource to prepare, then tells each one to commit or roll back.
XA is the industry-standard interface from the X/Open distributed transaction processing specification; in Java it appears as the javax.transaction.xa.XAResource interface. This page explains how XA works with JMS, when you need it, what it costs, and the usual alternative of an idempotent consumer. The official ActiveMQ documentation is on activemq.apache.org.
What is an XA transaction?
A local JMS transaction covers one session on one broker. In a transacted session, each transaction groups the messages you send and the messages you consume into one atomic unit: commit() sends the output and acknowledges the input, and rollback() discards the sends and recovers the consumed messages.
Real consumers usually touch a second system. A typical one reads a message, updates a database, then acknowledges the message. That is two resources with two separate commits, and a crash between them leaves the system half done. An XA transaction puts both under one coordinator.
The parts, as the Jakarta Transactions specification names them:
- Transaction manager: coordinates the global transaction, providing demarcation, resource management, synchronization and transaction context propagation. In Jakarta EE the application server works with it on your behalf.
- Resource managers: the systems doing the work, such as a relational database server or a JMS provider that supports
XAResource. Each one reports transaction association, completion and recovery to the transaction manager. XAResource: the Java mapping of the X/Open XA interface, the contract between a resource manager and the transaction manager.
Jakarta Messaging does not require a provider to support distributed transactions, but says that a provider that does should do it through XAResource. Providers expose it through an XAConnectionFactory, which the application server uses to create XA connections.
How two-phase commit works
The Jakarta Transactions specification walks through the sequence for a resource used inside a container-managed transaction:
- A global transaction starts. When the application obtains a connection, the server enlists that resource and the transaction manager calls
XAResource.startto associate it with the transaction. - The application does its work: sends and receives messages, runs SQL.
- The transaction manager calls
XAResource.endto disassociate the resource from the transaction. - Phase 1, prepare: on commit, the transaction manager calls
XAResource.prepareon each resource manager so it prepares the work for commit. - Phase 2, commit: the transaction manager calls
XAResource.commit, or rolls back, so every resource ends with the same outcome.
Preparing means each resource must be able to finish the transaction even after a crash. ActiveMQ's notes on how its transactions work say that the only real difference for XA is that at the prepare stage the broker writes every command it received, the sends and the acknowledgements, to its persistent store so it can recover. After a failure, the transaction manager calls XAResource.recover on each resource manager to list transactions still in a prepared or heuristically completed state, and resolves them.
Local JMS transaction vs XA transaction
| Local JMS transaction | XA transaction | |
|---|---|---|
| Scope | One session on one broker | Several resources, for example a broker and a database |
| Who ends it | Your code calls Session.commit() or rollback() | The transaction manager; calling the session's commit or rollback inside it throws TransactionInProgressException |
| Protocol | One commit | Prepare on every resource, then commit |
| Broker work in ActiveMQ Classic | Sends and acks are buffered until commit | The same, plus every command is written to the persistent store at prepare |
| Connection factory | Regular ConnectionFactory | XAConnectionFactory, used by the application server |
Should I use XA?
The ActiveMQ FAQ "Should I use XA" puts the case plainly. If you read a JMS message and write to a database, there is a small window after the database commit and before the message is acknowledged. A network, hardware or process failure inside that window means the message is redelivered and you may process it twice. XA exists to make that pair of commits atomic.
The same FAQ lists the costs:
- XA needs several syncs to disk per transaction so it can recover from any failure, which adds latency and uses resources.
- It adds complexity, and the FAQ warns that quite a few EJB servers and databases do not properly support XA.
- ActiveMQ Classic does not support XA transaction suspend and resume.
The Jakarta Messaging specification adds a portability warning: it recommends that clients avoid handling distributed transactions directly, because the XA interfaces are optional and are aimed at application server vendors.
XA is worth its cost when a duplicate or a lost update would be a real business problem, you cannot detect duplicates in your own code, every resource involved supports XA, and you already run a transaction manager. In most other cases the alternative below is simpler, and the FAQ says it performs much better because it avoids the slow disk syncs. The original 2006 archive page of that FAQ is kept at /site/should-i-use-xa.html as history.
Alternatives to XA
Idempotent consumer
The ActiveMQ FAQ's suggested optimization is to use a regular JMS transaction, without XA, and detect duplicates in your code. It points to the idempotent consumer pattern from Enterprise Integration Patterns. In outline:
- Receive the message in a transacted JMS session.
- Check whether you have already processed it, using an ID the message carries. The FAQ's example is a purchase order number plus a version.
- If it is new, do the database work and commit the database.
- Commit the JMS session. If anything throws, roll the JMS session back so the message is redelivered.
If the process dies after step 3, the message comes back, the check in step 2 finds it, and you skip it. The cost moves from extra disk syncs on every transaction to one lookup per message. The FAQ notes a further saving: redelivery is rare, so you can call Message.getJMSRedelivered() and only run the duplicate check when it returns true.
Sending from a database transaction
The reverse problem, updating a database and then publishing a message, can be handled without XA in a similar spirit. Write the outgoing message as a row in the same database transaction as the business change, and let a separate process read those rows, send them to the broker and mark them sent. That process can send a row twice if it crashes between sending and marking, so the consumers should still detect duplicates.
Acknowledgement modes and redelivery are covered in Message queue, and what happens to a message that keeps failing in Dead letter queue.
XA in ActiveMQ Classic
- Client:
org.apache.activemq.ActiveMQXAConnectionFactoryextendsActiveMQConnectionFactoryand implementsXAConnectionFactory,XAQueueConnectionFactoryandXATopicConnectionFactory. In 6.4.0 these are thejakarta.jmsinterfaces. - Broker: transactions are handled by a
TransactionStore, implemented by all persistence adapters, which holds messages and acks until commit or rollback. - Resource adapter: ActiveMQ ships a JCA 1.5 resource adapter for application servers. It delivers messages to message-driven beans with XA or local transactions, can be enlisted in XA and local transactions, and supports XA recovery through
XAResource.recover(). Outbound connections can reuse the inbound connection and session to avoid XA. - Limits: no XA suspend and resume, as noted above.
For Spring Boot setups, connection factories are covered in ActiveMQ with Spring Boot.
XA in Apache Artemis
Apache Artemis (formerly ActiveMQ Artemis) has its own resource manager that tracks the lifespan of JTA transactions. Because a client can start a transaction and then disappear, the broker can scan for old transactions and roll them back; transaction-timeout and transaction-timeout-scan-period in broker.xml control this, both in milliseconds. The broker will not roll back an XA transaction that is already prepared on its own. That has to be done as a heuristic rollback through the management API, once you are sure the transaction manager will never resolve it. See the resource manager configuration page in the Artemis documentation on artemis.apache.org.
Common problems
TransactionInProgressExceptionon commit. Inside a distributed transaction the transaction manager ends the work; do not call the session'scommit()orrollback().- Messages are not part of the global transaction. A JMS provider joins a distributed transaction through its XA objects (
XAConnection,XASessionandXAResource), so a plain connection factory is not enough. Use anXAConnectionFactorysuch asActiveMQXAConnectionFactory, or the resource adapter in an application server. - Prepared transactions left after a crash. The transaction manager must be able to call
XAResource.recoveron every resource. In Artemis, prepared transactions stay until resolved or heuristically rolled back through management. - Throughput drops after switching to XA. That is the documented cost of the extra disk syncs. Consider an idempotent consumer instead.
- Code that suspends and resumes transactions fails. ActiveMQ Classic does not support XA suspend and resume.
Frequently asked questions
What is an XA transaction?
An XA transaction is a distributed transaction that spans several resources, such as a message broker and a database, and commits on all of them or none. A transaction manager coordinates it with two-phase commit through each resource's XAResource.
What are XA transactions used for in JMS?
They make consuming a message and updating a database one atomic step, so a failure between the two commits cannot leave the message redelivered and processed twice. The ActiveMQ FAQ gives this JMS-plus-database case as the reason to use XA.
Should I use XA with ActiveMQ?
Use it only if you need atomic commits across resources and cannot detect duplicates yourself. XA needs several disk syncs per transaction, and the ActiveMQ FAQ suggests regular JMS transactions with an idempotent consumer as a faster alternative.
What is two-phase commit?
In phase one the transaction manager asks every resource to prepare the work for commit. In phase two it tells each resource to commit, or to roll back, so all of them reach the same outcome; prepared work can be recovered after a crash.
Does ActiveMQ support XA transactions?
Yes. ActiveMQ Classic provides ActiveMQXAConnectionFactory and a JCA resource adapter with XA recovery, but it does not support XA suspend and resume. Apache Artemis handles XA through its own resource manager.
Related guides
- What is a message queue? Queues, topics and publish/subscribe
- Dead letter queue (DLQ): how ActiveMQ handles messages it cannot deliver
- ActiveMQ Spring Boot setup: starter, JmsTemplate and @JmsListener
- What is a message broker?
- ActiveMQ Artemis vs ActiveMQ Classic: differences and migration
- All handbook guides
From the 2006 archive
The original ActiveMQ documentation on these topics, kept as it was published here in 2004–2007. It describes ActiveMQ 4.x and older.
Sources
- ActiveMQ: Should I use XA activemq.apache.org
- ActiveMQ: How do transactions work activemq.apache.org
- ActiveMQ: Resource Adapter activemq.apache.org
- ActiveMQ 6.4.0 ActiveMQXAConnectionFactory source (GitHub) raw.githubusercontent.com
- Jakarta Transactions 2.0 specification jakarta.ee
- Jakarta Messaging 3.1 specification jakarta.ee
- Apache Artemis: Resource Manager Configuration artemis.apache.org
- Apache Artemis news artemis.apache.org