Distributed XA Transactions in a Spring Boot / Camel Application
In this article, I’ll show how to set up distributed transactions (XA, known also as 2PC) in a Spring Boot / Camel application. Moreover, I’ll describe how to make sure this setup actually works.
What is XA and why do I care?
XA provides an implementation of 2PC (two-phase commit). It’s a distributed transaction architecture supported both by JavaEE platform and by Spring application framework. As opposed to local transactions, it allows to join multiple resources (databases, message brokers etc.) in a single distributed transaction with two distinct phases: prepare and commit.
Without a two-phase commit, handling multiple resources with independent transactions within one operation could lead to inconsistency. For example, if you need to read a message from a queue and write it to the database, one of the following scenarios could happen.
Scenario A, message loss:
- Open transaction for the message broker
- Open transaction for the database
- Read a message from the queue into memory
- Write a message from memory to the database
- Commit message broker transaction (acknowledging the message removes it from the queue)
- Fail to commit the database transaction, e.g. due to database failure or network connectivity, thus loosing the message completely.
Scenario B, message duplication:
- Open transaction for the message broker
- Open transaction for the database
- Read a message from the queue into memory
- Write a message from memory to the database
- Commit the database transaction (the message is durably written to the database)
- Fail to commit the message broker transaction due to the broker failure or loss of network connectivity — the message is unacknowledged and stays in the queue
- Message broker is online again, and the same message is consumed and saved to the database for the second time.
I’ll use Spring Boot and Camel frameworks to demonstrate how Scenario A is solved by using XA transactions, in other words, by consuming a message from an ActiveMQ queue and persisting it to a database, all part of a single two-phase transaction that joins PostgreSQL database and ActiveMQ message broker. I’ll use Atomikos as a distributed transaction manager.
What’s the problem with testing?
It’s not easy to test such scenarios, as they always involve a failure of one of the resources. It’s not sufficient just to throw an exception in the code or cause an application error.
As much as I like and recommend the books “Camel in Action” and “Apache Camel Developer’s Cookbook”, none of them really gets the XA testing right: the code example from the first book simply simulates an exception at the end of the route. It doesn’t really simulate an actual failure that could cause inconsistency: even without XA, if we simply used two different transactions for the resources, they’d be rolled back correctly by Camel anyway. The code example from the second book practically does the same.
An actual test of XA should simulate the error on the resource side during commit, e.g. a connectivity issue. This is the actual problem that XA was designed for, a problem that none of those examples address.
Setting up the Project
First, I’m going to need an empty project, which can be quickly generated by Spring Initializr (in this article, I’ll use Maven build, but for Gradle, the process should be very similar).
I’ll add Spring Boot starters for Atomikos and Camel — they do a pretty good job of configuring everything for us. So add the following starters to your project:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jta-atomikos</artifactId>
</dependency>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring-boot-starter</artifactId>
</dependency>
By the way, if you want to know how Spring Boot configures Atomikos under the hood, check out the AtomikosJtaConfiguration class. It has quite a lot of extensibility to cover almost all your needs.
I also need a PostgreSQL driver and two components for the Camel framework — namely, ActiveMQ and SQL:
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-sql</artifactId>
</dependency>
<dependency>
<groupId>org.apache.activemq</groupId>
<artifactId>activemq-camel</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>42.2.10</version>
</dependency>
Lastly, I’ll add a dependencyManagement section to set up versions of Camel dependencies:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.apache.camel</groupId>
<artifactId>camel-spring-boot-dependencies</artifactId>
<version>2.24.3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Setting up the Spring Boot Properties
Most of the configuration for a Spring Boot application happens in the application.yml file (or application.properties, if you don’t like YAML). Let’s see how the configuration looks like:
spring:
activemq:
# we'll use an external ActiveMQ broker
broker-url: tcp://localhost:61616
datasource:
# we'll use an external PostgreSQL database
url: jdbc:postgresql://localhost:5432/xatest
xa:
# this is needed to make sure the PostgreSQL data source is XA-aware
data-source-class-name: org.postgresql.xa.PGXADataSource
username: postgres
password: postgres
# this is required to always execute schema.sql file on application start
# (replace with database migrations for production)
initialization-mode: always
jta:
atomikos:
connectionfactory:
# allow to set transacted flag on a session level;
# set it to true if you don't want any local transactions at all
ignore-session-transacted-flag: false
# just a name of ActiveMQ broker as an XA resource, for convenience
unique-resource-name: xa.amq
min-pool-size: 10
max-pool-size: 20
datasource:
# just a name of PostgreSQL database as an XA resource, for convenience
unique-resource-name: xa.db
# Atomikos does its own connection pooling, don't use any other connection pool library!
min-pool-size: 10
max-pool-size: 20
# specifying a test query for your database is important,
# otherwise, Atomikos connection pool won't be able to
# health-check the connections, which will lead to failure
# during connection recovery
test-query: "select 1"
properties:
# a default timeout for an XA transaction (5 minutes)
default-jta-timeout: 300000
logging:
level:
# just for convenience, we'll log the transaction prepare/commit/rollback process
com.atomikos.datasource.xa.XAResourceTransaction: DEBUG
As you’ve already guessed, we’ll use an external ActiveMQ message broker and an external PostgreSQL database. We won’t use an embedded broker and an embedded H2 database (although they too support XA transactions), because it’s not easy to test a loss of connectivity to embedded resources.
Important thing here is to use an XA-aware datasource for the PostgreSQL database (org.postgresql.xa.PGXADataSource) instead of a default one. Another thing to note is that Atomikos uses its own connection pool (see reasoning behind this in this article), so we’ll set some pool size settings instead of the default ones.
An important parameter is spring.jta.atomikos.datasource.test-query. This query is used by Atomikos to health-check the connections to the database in the pool. If you don’t set it up, the application will have trouble recovering from a lost database connection. For PostgreSQL, a typical query would be SELECT 1.
To initialize the database, I use the following script, which I’ll place in src/main/resources folder:
drop table if exists message;
create table message (
id serial primary key,
contents varchar(256) not null
);
Setting up the Spring Beans
Now for the last part of the setup — some additional Spring beans to make it all work. First, let’s set up a Camel ActiveMQ component and redelivery policy:
@Configuration
public class ActiveMQConfig {
@Bean("activemq")
public ActiveMQComponent activeMq(
ConnectionFactory connectionFactory,
JtaTransactionManager jtaTransactionManager) {
ActiveMQComponent component = new ActiveMQComponent();
component.setAcknowledgementMode(JmsProperties.AcknowledgeMode.CLIENT.getMode());
component.setCacheLevelName("CACHE_CONSUMER");
component.setConnectionFactory(connectionFactory);
component.setTransacted(true);
component.setTransactionManager(jtaTransactionManager);
return component;
}
@Bean
public ActiveMQConnectionFactoryCustomizer activeMQConnectionFactoryCustomizer() {
return factory -> {
RedeliveryPolicy policy = new RedeliveryPolicy();
policy.setRedeliveryDelay(1000);
policy.setMaximumRedeliveries(2);
factory.setRedeliveryPolicy(policy);
};
}
}
Acknowledgement mode should be set to CLIENT. This means that the application will acknowledge the message delivery only when transaction is finished, as opposed to the AUTO mode, where the message is considered to be acknowledged by the broker once it’s consumed by the application.
I also specify that the ActiveMQComponent is transacted, and provide the JtaTransactionManager instance which is backed by XA-capable Atomikos implementation.
The redelivery policy setting means that the application will try to process the message three times with an interval of 1 second. This may be useful in case of a recoverable error during processing. We’ll see how the application will process the message after the connectivity issue is resolved, thanks to this setting.
Take a note on how I set up the redelivery policy — I create an instance of the ActiveMQConnectionFactoryCustomizer class, which is a part of the Spring Boot framework that allows me to customize the default connection factory any way I want.
Another thing I’ll need is a SpringTransactionPolicy instance that’s connected to said transaction manager. I set its propagation level to PROPAGATION_REQUIRED, which means that a new transaction will be created whenever the code enters a transactional Camel route.
@Configuration
public class TransactionConfig {
@Bean("policyPropagationRequired")
public SpringTransactionPolicy transactionPolicyPropagationRequired(
@Autowired JtaTransactionManager transactionManager) {
SpringTransactionPolicy policy = new SpringTransactionPolicy(transactionManager);
policy.setPropagationBehaviorName("PROPAGATION_REQUIRED");
return policy;
}
}
At long last, I configure a Camel route that should take the message from the queue and insert it into the database table:
@Component
public class XaRoute extends RouteBuilder {
@Override
public void configure() {
from("activemq:TestQueue")
.transacted("policyPropagationRequired")
.to("sql:insert into message(contents) values(:#${body})")
.log("Delay...")
.delay(10000)
.log("Delay finished, committing");
}
}
The route is marked as transacted with the transaction policy that I’ve created earlier. This means that the route will be executed in a transaction, and since I’ve configured Atomikos to be my transaction manager, this transaction will be distributed.
The route also simulates a 10 second delay during the transaction which will give me time to stop the database server and simulate failure.
Setting Up PostgreSQL and ActiveMQ
For external dependencies, I’ll use Docker, namely, the official Docker image for PostgreSQL and this third-party rmohr/activemq image for ActiveMQ. By the way, for production, always make sure you build your own images.
To run PostgreSQL, I need to specify the container name xa-test-postgres, database name xatest, password postgres and a special parameter max_prepared_transactions, which normally goes into the postgresql.conf file. It defines how many prepared transactions are allowed at once, and is required for the XA transactions to happen.
docker run --name=xa-test-postgres -e POSTGRES_PASSWORD=postgres \
-e POSTGRES_DB=xatest -d -p 5432:5432 \
postgres -c 'max_prepared_transactions=100'
Now run ActiveMQ:
docker run --name=xa-test-activemq -p 61616:61616 -p 8161:8161 -d \
rmohr/activemq
Now I’m all set set to test the configured XA transactions.
Testing that XA actually works
To send messages to ActiveMQ, I’ll use a nearly ungooglable, but very useful tool fmtn/a. I just grab the last release and run the following:
./a -p test TestQueue
This command sends the message with contents “test” to the TestQueue queue which is monitored by my application. What I expect is this message to appear in the message table in the database.
Now for the fun part. As soon as I see the following line in the logs:
INFO 8717 --- [umer[TestQueue]] route1 : Delay...
I run the following command to stop the PostgreSQL database, simulating a connectivity failure:
docker container kill xa-test-postgres
Examining the results
Now I head over to http://localhost:8161/admin/queues.jsp (login with admin/admin by default) and check out the queue status — the TestQueue should have 1 message which is still not consumed, which is visible in the “Number Of Pending Messages” column. This means that the application didn’t consume the message from the queue, which is good:
Now run PostgreSQL container again:
docker start xa-test-postgres
I now have about 30 seconds until Atomikos regains its connection to the database, and a retry happens. I log in to the PostgreSQL Docker container, which should be now running again, and check out the database state:
$ docker exec -it xa-test-postgres sh
# psql -U postgres xatest
xatest=# select * from message;
There’s 0 messages — this is good, because the application didn’t commit the message to the database.
Once again, the message was not duplicated and was not lost. It’s kept safely in the ActiveMQ queue.
Now I wait a little, the application regains its connections to the database and retries the message processing. As soon as this happens, I observe that there’s no longer a message in the queue, and the message table contains exactly one message.
Hooray!
Conclusion
In this article, I’ve set up XA transactions in a Spring Boot / Camel application and tested that it actually works as expected at least in one scenario. What else could I try?
- simulate ActiveMQ failure: this would require me to set up a database for ActiveMQ to use as a persistent storage, otherwise, the message will be lost anyway;
- a reverse scenario — taking a message from the database table, sending it to the queue and removing it from the database;
- simulating ActiveMQ or database failures in the above reverse scenario;
- implementing this as a completely automated test using Testcontainers framework or something similar.
The source code to the article is available on GitHub.