XA Integration Principle

Overview

Java implements XA (eXtended Architecture) distributed transaction model through defining JTA (Java Transaction API) interface. JTA specification mainly contains three core components:

  1. TransactionManager: Transaction coordinator, responsible for coordinating and managing global transactions
  2. XAResource: Resource manager interface, implemented by each resource vendor
  3. UserTransaction: Simple transaction interface for developers

Problems with Traditional Architecture

  1. High deployment cost: Must rely on heavyweight application server
  2. Complex O&M: Requires professional personnel for configuration and maintenance
  3. High resource consumption: Full application server occupies more system resources

Embedded Transaction Manager

Modern distributed systems adopt embedded transaction manager solutions:

  • Provides services as lightweight jar package
  • Can be directly integrated with application process
  • Typical representatives: Atomikos, Bitronix

ShardingSphere XA Transaction Core Features

  1. Cross-database XA transaction support
  2. Strong consistency guarantee mechanism: Uses standard two-phase commit protocol (2PC)
  3. Fault recovery capability: Built-in transaction log persistence mechanism
  4. Extensible transaction manager integration: Based on SPI mechanism
  5. Diversified connection pool support
  6. Multiple access methods: Spring Boot Starter, Namespace approach

Execution Flow

Transaction Initiation Phase

  1. Application calls begin() method to start distributed transaction
  2. XAShardingTransactionManager initializes XA transaction context
  3. Creates corresponding global transaction instance

XA Resource Registration

  1. Create corresponding database connection for each physical shard SQL
  2. Register each physical connection’s XAResource to current XA transaction
  3. Send XAResource.start command to database

Commit/Rollback Flow

Commit Phase

  1. Transaction boundary marking: Call XAResource.end instruction
  2. Prepare phase: Send prepare instruction to all XAResources
  3. Resolution phase:
    • All votes pass: Send commit instruction
    • Veto: Trigger rollback instruction

Exception Handling Mechanism

  • Operation atomicity: Either all commit successfully, or all roll back
  • Data strong consistency: All participants reach final consistent state
  • Fault recovery: Ensures interrupted transactions can be recovered through persisted logs