Video in progress

Staff 🌱 Spring

Why do people often avoid XA (JTA) transactions for writing to several databases at once, and what is done instead?

XA gives atomicity with a two-phase commit, but it is slow, holds resources locked for a long time, leaves "in-doubt" transactions when the coordinator crashes, and systems like Kafka don't support it. Instead you use an outbox, idempotent consumers and compensation.

📖 Answer

In Spring Boot 3, JTA still works (through Atomikos or Narayana), so technically you can do it. The problem is the price.

How 2PC works: the coordinator asks each resource "are you ready?" (prepare), and if everyone says "yes", it commits. Between prepare and commit, every database holds its locks.

Why people avoid it:

  • Latency: every transaction gets extra network steps and disk writes (the coordinator log).
  • Blocking: if the coordinator crashes after prepare, resources stay "in-doubt" and hold locks until someone resolves it by hand or through recovery.
  • Who supports it: Kafka, most cloud services and REST APIs can't be XA participants. In microservices it is almost never used.
  • Operations: keeping the transaction log, recovery and monitoring are things the team has to know.
  • Availability: if one resource is slow, everything gets slow.

What to do instead:

  1. One database, one transaction. In many cases this is the right answer: fit both writes into one database.
  2. Transactional outbox. The business write and the "needs to be sent" event go in one local transaction; then a relay (polling or Debezium CDC) sends it to Kafka.
  3. An idempotent receiver makes "at-least-once" delivery safe.
  4. Saga and compensation, when several services take part.
  5. Reconciliation: a daily comparison job to find possible discrepancies (financial systems need it anyway).

When XA is appropriate: two relational databases, or a database plus a JMS broker, inside one monolith, both supporting XA well, with small volume and a strict need for atomicity (say, a legacy banking system). Even then I ask to keep the transaction short and to test recovery in advance.

The main point for an interview: "instead of distributing atomicity, we keep it in one place and handle the rest with eventual consistency, and we agree with the business on the intermediate states that result."