Saga Integration Principle
Overview
ShardingSphere’s flexible transactions are implemented through the third-party servicecomb-saga component, using SPI mechanism for dynamic injection.
Core Mechanism:
- Generate compensation operations through reverse SQL technology
- INSERT → DELETE
- UPDATE → Reverse UPDATE (restore original value)
- DELETE → INSERT (based on Before Image)
Core Features
-
Complete cross-database transaction support
- Support transactions across different database instances
- Support transactions across different database types
-
Complete failure handling mechanism
- Support configurable SQL retry strategy
- Provide best-effort delivery guarantee
-
Intelligent reverse SQL support
- Automatically generate reverse SQL for update operations
- Automatically create data snapshots (Before Image)
-
Extensible persistence solution
- Default uses relational database to store transaction logs
- Support extending other storage media through SPI
Basic Flow
Init: Saga Engine Initialization
- Read and parse saga.properties configuration file
- Initialize Saga transaction log storage
- Start background compensation task scheduler
- Register SQL parsing Hook
Begin: Start Saga Global Transaction
- Generate globally unique XID
- Create SagaTransactionContext transaction context object
- Bind context to ThreadLocal of current thread
Execute Physical SQL
-
SQL parsing phase:
- Identify SQL type
- Generate reverse SQL
-
Example transformation:
/* Original SQL */ UPDATE account SET balance = balance-100 WHERE user_id = 123; /* Generated reverse SQL */ UPDATE account SET balance = balance+100 WHERE user_id = 123;
Commit-Rollback
Successful commit:
- Build forward call chain graph (DAG)
- Generate ForwardRecovery task
- Persist to transaction log table
Failure rollback:
- Build reverse call chain graph
- Generate BackwardRecovery task
- Retry with exponential backoff strategy
Seata Integration Principle
Basic Principle
Seata AT mode is a flexible transaction implementation solution based on BASE theory, implementing distributed transactions through a variant of two-phase commit.
Core Components
- Transaction Manager (TM): Responsible for defining global transaction boundary
- Resource Manager (RM): Responsible for managing branch transaction resources
- Transaction Coordinator (TC): Responsible for maintaining global transaction status
DataSource Proxy Chain
- Physical DataSource → ShardingSphere’s DataSource
- ShardingSphere’s DataSource → Seata’s DataSource
- Handle both sharding routing and distributed transactions simultaneously