Skip to content
javahacks.dev
Jakarta EE

Jakarta Transactions JTA and XA Explained With Examples

How Jakarta Transactions works: @Transactional, UserTransaction, two phase commit with XA resources, the cost of distributed transactions and alternatives.

7 min read
Summarize in AI
Flat illustration of a database beside the table it holds, with the Hibernate, MySQL, Redis and MongoDB logos.

A transaction groups changes so they all happen or none do. In a Jakarta EE server, the transaction manager handles it for you, including across more than one resource. This explains the API, the protocol and the trade-offs, on Jakarta EE 11. For Spring's equivalent see transactional pitfalls.

Declaring a boundary

java
@ApplicationScoped
public class TransferService {

    @PersistenceContext EntityManager em;

    @Transactional(Transactional.TxType.REQUIRED)
    public void transfer(long from, long to, BigDecimal amount) {
        Account a = em.find(Account.class, from);
        Account b = em.find(Account.class, to);
        a.debit(amount);
        b.credit(amount);
    }
}

The interceptor starts a transaction before the method, and commits after it returns. A runtime exception marks the transaction for rollback, while a checked exception does not unless you list it in rollbackOn. The common types:

TxTypeBehaviour
REQUIREDJoin the current transaction or start one (default)
REQUIRES_NEWSuspend the current one and start a new one
MANDATORYMust already be in a transaction
SUPPORTSJoin one if present, otherwise run without
NOT_SUPPORTEDSuspend any transaction while running
NEVERFail if a transaction exists

For code-controlled boundaries inject UserTransaction and call begin, commit and rollback.

Local versus global transactions

With one database, the transaction maps to a database transaction, and nothing special happens. A global transaction spans two or more resources, for example a JPA database and a JMS queue (see Jakarta Messaging). The manager must make them agree.

Two phase commit

The protocol, called XA after its standard, has two steps:

  1. Prepare. The manager asks each resource whether it can commit. Each writes its changes durably and votes yes or no.
  2. Commit. If all voted yes, the manager logs the decision and tells each to commit. If any voted no, it tells all to roll back.

The resources must be XA capable (XADataSource, XAConnectionFactory). The manager's log lets it finish transactions after a crash: a participant that prepared and lost contact holds its locks until the manager recovers it. That is the cost. A crash between the phases can leave locks held on rows until recovery runs.

Why people avoid it

ConcernDetail
LatencyExtra round trips and forced log writes
AvailabilityEvery participant must be up to commit
OperationsRecovery logs, heuristic outcomes, in-doubt transactions
PortabilityNot all brokers and cloud databases support XA

Microservices make it worse, since REST calls are not XA resources at all. The alternatives are a saga with compensations, or the outbox pattern, which writes the message in the same local transaction as the data and forwards it afterwards, see the outbox with Debezium.

Isolation and timeouts

Transaction timeouts protect against stuck work; the container default is often 30 seconds. Isolation levels are set on the resource, see isolation levels.

Drive two-phase commit by hand to see the protocol

The XA protocol is described in terms of a coordinator and resource managers. In code, the coordinator calls four methods on each XAResource: start and end to bracket the work, prepare to ask for a vote, and commit or rollback for the decision. A skeleton shows the shape that an application server runs for you. It is a sketch to read, because the application server's transaction manager performs these calls in production, and the two databases here are placeholders for any XA-capable resources.

java
XAResource orders = ordersConnection.getXAResource();
XAResource payments = paymentsConnection.getXAResource();
Xid xo = new MyXid(1, gtrid, new byte[] {1});      // same global id, different branch qualifier
Xid xp = new MyXid(1, gtrid, new byte[] {2});

orders.start(xo, XAResource.TMNOFLAGS);
ordersConnection.getConnection().createStatement().execute("insert into orders values (1)");
orders.end(xo, XAResource.TMSUCCESS);

payments.start(xp, XAResource.TMNOFLAGS);
paymentsConnection.getConnection().createStatement().execute("insert into payments values (1)");
payments.end(xp, XAResource.TMSUCCESS);

// phase 1: each resource makes its work durable and votes
int voteOrders = orders.prepare(xo);
int votePayments = payments.prepare(xp);

// phase 2: the coordinator records its decision, then tells everyone
if (voteOrders == XAResource.XA_OK && votePayments == XAResource.XA_OK) {
    orders.commit(xo, false);
    payments.commit(xp, false);
} else {
    orders.rollback(xo);
    payments.rollback(xp);
}

Two details matter. Both resources share the global transaction id and differ in the branch qualifier, which is how each resource manager knows the branches belong together. And prepare is the point of no return for a participant: once it has voted yes, it must be able to commit even after a crash, so it holds the locks on the affected rows until it hears the decision. The window between the vote and the decision is the in-doubt period, and a coordinator crash in that window leaves resources waiting. On restart the coordinator reads its log, asks each resource for its prepared transactions with recover, and completes them.

java
Xid[] inDoubt = orders.recover(XAResource.TMSTARTRSCAN | XAResource.TMENDRSCAN);
for (Xid xid : inDoubt) {
    if (coordinatorLog.committed(xid)) orders.commit(xid, false);
    else orders.rollback(xid);              // presumed abort: no record of a commit means roll back
}

The rule in the loop is called presumed abort: the coordinator logs the decision to commit before telling anyone, so a transaction with no commit record never committed and is safe to roll back. Application servers and libraries such as Narayana implement this recovery loop; the useful thing for you to know is that it exists, runs on a schedule, and needs its log on durable storage.

A transfer across two databases in a Jakarta EE server

In an application server, none of the calls above appear in your code. You declare a boundary, use two XA data sources, and the container enlists both.

java
@ApplicationScoped
public class SettlementService {

    @Resource(lookup = "java:/jdbc/OrdersXA")   DataSource orders;
    @Resource(lookup = "java:/jdbc/LedgerXA")   DataSource ledger;

    @Transactional(Transactional.TxType.REQUIRED)
    public void settle(long orderId, BigDecimal amount) throws SQLException {
        try (Connection c1 = orders.getConnection();
             PreparedStatement s1 = c1.prepareStatement("update orders set status = 'SETTLED' where id = ?")) {
            s1.setLong(1, orderId);
            s1.executeUpdate();
        }
        try (Connection c2 = ledger.getConnection();
             PreparedStatement s2 = c2.prepareStatement("insert into ledger(order_id, amount) values (?, ?)")) {
            s2.setLong(1, orderId);
            s2.setBigDecimal(2, amount);
            s2.executeUpdate();
        }
    }
}

The data sources must be configured as XA data sources in the server; configuring them as ordinary ones makes the second connection a separate local transaction, and the two updates no longer succeed or fail together. A runtime exception from the method rolls back both. The pitfall is silent: the code looks the same and loses atomicity. Test it by throwing after the first update and checking that neither table changed.

Check the one-phase optimisation

When only one resource took part, a good transaction manager skips the prepare phase and commits that resource directly. That is why a service with one database and @Transactional pays no XA cost, and why the cost appears only when a second resource joins. If latency increased after adding a JMS send to a method, the second resource turned a local commit into a two-phase one. Measure before and after, and consider the outbox alternative described in the section above.

Timeouts, heuristics and the cost of in-doubt transactions

Two operational settings decide how painful two-phase commit is. The transaction timeout bounds how long a global transaction may run before the manager rolls it back, and it should be longer than the slowest legitimate use and short enough that a stuck transaction does not hold locks for minutes. Most servers default to 30 or 60 seconds; set it per method with a timeout attribute where the work is known to be quick, so a hang is cut early.

The second is the set of heuristic outcomes. When a participant loses contact with the coordinator after voting yes, an administrator or a timeout may force it to commit or roll back on its own. If the guess disagrees with the coordinator's decision, the result is a heuristic mixed outcome: one resource committed and the other rolled back, and the only repair is manual. Monitor for HeuristicMixedException and HeuristicRollbackException in logs, and treat each as an incident with the in-doubt record kept for reconciliation. A system that never sees them in testing can still see them once in a year, which is why the alternative of avoiding global transactions is attractive in the first place.

Where this does not apply

If you only use one database, a local transaction is all you have, and no XA is needed. Plain Java SE with JDBC uses manual transactions. The specification is at Jakarta Transactions and the XA background in the X/Open XA overview.

Also inHibernate
Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.