Saga Integration Principles
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 Functional Features
-
Complete cross-database transaction support
- Supports transactions across different database instances
- Supports transactions across different database types
-
Complete failure handling mechanism
- Supports configurable SQL retry strategy
- Provides best-effort delivery guarantee
-
Intelligent reverse SQL support
- Automatically generates reverse SQL for update operations
- Automatically creates data snapshots (Before Image)
-
Extensible persistence solution
- Default uses relational database for transaction log storage
- Supports extending to 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 invocation chain graph (DAG)
- Generate ForwardRecovery task
- Persist to transaction log table
Failure rollback:
- Build reverse invocation chain graph
- Generate BackwardRecovery task
- Retry with exponential backoff strategy
Seata Integration Principles
Basic Principles
Seata AT mode is a flexible transaction implementation solution based on BASE theory, implementing distributed transactions through variant of two-phase commit.
Core Components
- Transaction Manager (TM): Responsible for defining global transaction boundaries
- Resource Manager (RM): Responsible for managing branch transaction resources
- Transaction Coordinator (TC): Responsible for maintaining global transaction status
Data Source Proxy Chain
- Physical DataSource → ShardingSphere’s DataSource
- ShardingSphere’s DataSource → Seata’s DataSource
- Simultaneously handle sharding routing and distributed transactions