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

  1. Complete cross-database transaction support

    • Supports transactions across different database instances
    • Supports transactions across different database types
  2. Complete failure handling mechanism

    • Supports configurable SQL retry strategy
    • Provides best-effort delivery guarantee
  3. Intelligent reverse SQL support

    • Automatically generates reverse SQL for update operations
    • Automatically creates data snapshots (Before Image)
  4. 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

  1. Read and parse saga.properties configuration file
  2. Initialize Saga transaction log storage
  3. Start background compensation task scheduler
  4. Register SQL parsing hook

Begin: Start Saga Global Transaction

  1. Generate globally unique XID
  2. Create SagaTransactionContext transaction context object
  3. Bind context to ThreadLocal of current thread

Execute Physical SQL

  1. SQL parsing phase:

    • Identify SQL type
    • Generate reverse SQL
  2. 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:

  1. Build forward invocation chain graph (DAG)
  2. Generate ForwardRecovery task
  3. Persist to transaction log table

Failure rollback:

  1. Build reverse invocation chain graph
  2. Generate BackwardRecovery task
  3. 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

  1. Transaction Manager (TM): Responsible for defining global transaction boundaries
  2. Resource Manager (RM): Responsible for managing branch transaction resources
  3. Transaction Coordinator (TC): Responsible for maintaining global transaction status

Data Source Proxy Chain

  1. Physical DataSource → ShardingSphere’s DataSource
  2. ShardingSphere’s DataSource → Seata’s DataSource
  3. Simultaneously handle sharding routing and distributed transactions