SuperAPI AI Directory

seata-patterns

General & other

View repository

Updated 10-15 21:48

About this skill

Seata Distributed Transactions

Source:https://seata.apache.org/docs/
GitHub:https://github.com/apache/incubator-seata

Capability Boundaries

✅ Strong Suits

  1. AT mode (recommended starting point) — Based on datasource proxy, zero intrusion, covers 80% of scenarios
  2. TCC mode — Custom Try/Confirm/Cancel, better performance, suitable for high-concurrency core business
  3. SAGA mode — Long-process transactions (>10s), state machine driven, eventual consistency
  4. XA mode — Strong consistency, standard protocol, suitable for financial core
  5. undo_log table — Must be created for AT mode (in each business database)
  6. @GlobalTransactional — Global transaction entry point
  7. @GlobalLock — Read isolation enhancement

❌ Out of Scope

  1. Single database transaction → Spring @Transactional
  2. Eventual consistency (strong consistency not required) → Kafka/RocketMQ transactional messages

Four-mode selection decision tree

需要分布式事务?
├── 需要强一致性(金融核心) → XA模式(性能差)
├── 最终一致即可
│   ├── 事务执行时间 > 10秒 → SAGA模式(状态机)
│   ├── 高并发 + 愿意写Confirm/Cancel → TCC模式
│   └── 80%场景(默认推荐) → AT模式(零侵入)

The mistakes LLMs most commonly make

# Mistake Correct approach
1 Not knowing that AT mode requires an undo_log table Create in each business database undo_log table
2 Using a non-ACID database with AT mode AT depends on local transactions, must be MySQL/PostgreSQL/Oracle
3 Global transaction timeout not set (default 60s may not be enough) Configure @GlobalTransactional(timeoutMills = 300000)
4 TCC mode Confirm failure does not handle idempotency Confirm must be idempotent (globally unique ID + deduplication index)
5 TCC mode does not handle empty rollback Use useTCCFence = true(Seata 1.5.1+)
6 Read isolation not handled (reading data from an uncommitted global transaction) Add to queries FOR UPDATE + @GlobalLock
7 Thinking SAGA mode automatically rolls back SAGA requires manually written compensation logic
8 Global transaction takes too long (lock conflicts) Set a reasonable timeout (15~30 seconds recommended)

Core modes

Mode 1: AT mode (zero intrusion, recommended)

-- ✅ 每个业务数据库必须建 undo_log 表
CREATE TABLE IF NOT EXISTS undo_log (
    id BIGINT NOT NULL AUTO_INCREMENT,
    branch_id BIGINT NOT NULL,
    xid VARCHAR(128) NOT NULL,
    context VARCHAR(128) NOT NULL,
    rollback_info LONGBLOB NOT NULL,
    log_status INT NOT NULL,
    log_created DATETIME NOT NULL,
    log_modified DATETIME NOT NULL,
    PRIMARY KEY (id),
    UNIQUE KEY ux_undo_log (xid, branch_id)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4;
// ✅ AT 模式:只需注解,零业务侵入
@Service
public class OrderService {
    @GlobalTransactional(timeoutMills = 300000, rollbackFor = Exception.class)
    public void createOrder(OrderDTO dto) {
        orderService.create(dto);           // 远程服务A(本地事务)
        inventoryService.deduct(dto);       // 远程服务B(本地事务)
        accountService.debit(dto);          // 远程服务C(本地事务)
        // 任一失败 → 全部自动回滚(基于 undo_log)
    }
}

Mode 2: TCC mode (high-concurrency core business)

@LocalTCC
public interface AccountTccAction {
    @TwoPhaseBusinessAction(
        name = "accountTcc",
        commitMethod = "confirm",
        rollbackMethod = "cancel",
        useTCCFence = true  // ← Seata 1.5.1+ 自动处理幂等/悬挂/空回滚
    )
    boolean prepare(BusinessActionContext ctx,
        @BusinessActionContextParameter(paramName = "accountDTO") AccountDTO dto);

    // ✅ Confirm 必须幂等(可重复执行不改变结果)
    boolean confirm(BusinessActionContext ctx);

    // ✅ Cancel 必须是幂等补偿(可能先于 Try 执行=空回滚)
    boolean cancel(BusinessActionContext ctx);
}

Mode 3: SAGA mode (long-process state machine)

// SAGA 使用状态机引擎,通过 JSON 配置编排长事务
// 每个步骤有正向(serviceMethod)和补偿(compensateMethod)

// 适用场景:订单履约、审批流、物流追踪
// 补偿顺序必须严格反向执行
// 补偿操作必须幂等且可重试

Mode 4: Read isolation enhancement (@GlobalLock + FOR UPDATE)

@GlobalLock
@Transactional
public Order getOrder(Long orderId) {
    // ✅ FOR UPDATE + @GlobalLock 解决 AT 模式脏读
    return orderMapper.selectForUpdate(orderId);
}
<select id="selectForUpdate" resultMap="BaseResultMap">
    SELECT * FROM orders WHERE id = #{id} FOR UPDATE
</select>

Gotchas

  1. AT mode does not support non-ACID databases — MySQL/PostgreSQL/Oracle work, Redis/Mongo do not
  2. The undo_log table must be in the same database as the business table — Different databases cannot roll back
  3. TCC's Confirm must be idempotent — Repeated execution does not change the result
  4. TCC's Cancel must handle empty rollback — Try was not executed but Cancel has already been received
  5. SAGA mode has no automatic rollback — Compensation logic must be written manually (state machine configuration)
  6. Global locks can cause deadlocks — Set a reasonable timeout (timeoutMills)
  7. @GlobalTransactional defaults to a 60s timeout — Automatically rolls back after timeout, manually adjust for long transactions
  8. Seata TC must be deployed as a cluster with at least 3 nodes — Prevents single point of failure
  9. The undo_log table is cleaned up periodically — Completed undo_logs can be deleted (resident in memory)
  10. Monitor global transaction success rate/failure rate — Use Seata Dashboard or Prometheus

Data Privacy

This skill does not collect, store, or transmit any user data.