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

  1. Complete cross-database transaction support

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

    • Support configurable SQL retry strategy
    • Provide best-effort delivery guarantee
  3. Intelligent reverse SQL support

    • Automatically generate reverse SQL for update operations
    • Automatically create data snapshots (Before Image)
  4. Extensible persistence solution

    • Default uses relational database to store transaction logs
    • Support extending 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 call chain graph (DAG)
  2. Generate ForwardRecovery task
  3. Persist to transaction log table

Failure rollback:

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

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

DataSource Proxy Chain

  1. Physical DataSource → ShardingSphere’s DataSource
  2. ShardingSphere’s DataSource → Seata’s DataSource
  3. Handle both sharding routing and distributed transactions simultaneously