Seata AT vs TCC: Deep Dive into Distributed Transactions with Spring Boot
This article analyzes Seata's AT and TCC modes for distributed transactions in Spring Boot, covering source code internals like undo_log, global locks, SQL parsing, and TCC's three-phase implementation with solutions for empty rollback, suspension, and idempotency, plus eight common pitfalls and interview questions.
Two Classic Incidents
Incident 1: Order placed, inventory deducted, but account debit failed. The order service's local transaction had already committed, leaving no way to roll back — manual reconciliation fixed 400+ records. Root cause: Cross-service transactions lack a unified boundary; each service only has its own local transaction.
Incident 2: After adopting Seata AT, occasional "dirty write check failed" appeared. Logs showed Compare dirty data, global rollback stuck, data neither rolled back nor committed, requiring manual DB fixes. Root cause: A business segment used update ... set stock = stock - 1 without a primary key condition, causing the before-image to capture the whole table.
The dividing line is clear: Incident 1 is "no distributed transaction"; incident 2 is "assuming distributed transactions cover everything". The former is fixed by framework, the latter by cognition — AT provides automatic compensation, not true two-phase commit. It has isolation gaps and SQL syntax boundaries.
Five Solutions: Trade-off Spectrum
XA / 2PC: Database-level two-phase commit. Strong consistency, zero business intrusion. Drawbacks: synchronous blocking, coordinator single point, poor performance, requires XA support per DB. Seen in core financial accounting; rarely used in internet businesses.
AT (Auto Transaction): Seata's flagship. Phase 1 commits local transaction and records undo_log; phase 2 asynchronously rolls back or cleans up. Zero business intrusion, good performance. Cost: global lock only locks rows, not reads ; default isolation is READ UNCOMMITTED, allowing dirty reads.
TCC: Business implements Try/Confirm/Cancel. Resource reservation, best performance, controllable isolation. Cost: high intrusion, must handle empty rollback, suspension, idempotency.
Saga: Long transaction split into chain of local transactions + reverse compensation. Suits long flows, cross-system (including third-party). No isolation; compensation written manually.
Local Message Table / Transactional Messaging: Eventual consistency. Business DB and message table in same local transaction. Reliable delivery + consumer idempotency achieve consistency. Non-blocking, most robust — the actual choice for most internet companies.
Selection mnemonic: Short transactions, need strong consistency, can accept slight intrusion → AT. Resource reservation scenarios (inventory, quota, coupons) → TCC. Long flows, cross external systems → Saga. Only eventual consistency needed → Local message table. Don't use AT for "debit" scenarios that must reserve resources.
Core Flow: AT Mode's Two-Phase Reality
3.1 Three Roles in One Order
TC (Transaction Coordinator): Independent Seata Server. Maintains global and branch transaction states, drives commit/rollback.
TM (Transaction Manager): Initiator. Method annotated with @GlobalTransactional applies for XID and ultimately decides commit or rollback.
RM (Resource Manager): Proxy DataSource per participating DB. Handles local transaction, writes undo_log, registers branch, receives TC commands for phase 2.
Complete sequence: TM requests XID from TC (globally unique) → XID propagates via Feign/RPC → Each RM registers branch with XID, executes local SQL and undo_log in same local transaction, reports success to TC → All succeed: TM notifies TC to commit; TC asynchronously tells each RM to delete undo_log. Any failure: TC notifies each RM to compensate using undo_log.
3.2 Business Side: Just One Annotation
@Service
public class OrderService {
@GlobalTransactional(
timeoutMills = 30000,
name = "create-order")
public Long createOrder(OrderDTO dto) {
// Branch 1: Order DB (local)
orderMapper.insert(build(dto));
// Branch 2: Storage Service (Feign)
storageClient.deduct(dto.getSku(), dto.getCount());
// Branch 3: Account Service (Feign)
accountClient.debit(dto.getUserId(), dto.getAmount());
return dto.getOrderId();
}
}Four prerequisites for effect: ① Every DB must have undo_log table; ② DataSource must be proxied by Seata (seata-spring-boot-starter auto-injects DataSourceProxy); ③ XID must propagate across processes (Feign interceptor / Dubbo Filter, starter includes); ④ All participants must connect to same TC cluster (consistent tx-service-group).
Core Source Code: Four Must-Read Segments
4.1 undo_log Table: Rollback's Sole Basis
CREATE TABLE undo_log (
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(6) NOT NULL,
log_modified DATETIME(6) NOT NULL,
UNIQUE KEY ux_undo_log (xid, branch_id)
);Key is rollback_info : serialized beforeImage + afterImage. beforeImage = full row snapshot before SQL; afterImage = snapshot after. Rollback uses beforeImage to generate reverse SQL; validation uses afterImage to confirm "this row is still as I left it".
4.2 Global Transaction Template: TransactionalTemplate
// io.seata.tm.api.TransactionalTemplate
public Object execute(TransactionalExecutor executor) {
// 1. Apply XID from TC (begin)
String xid = beginTransaction(executor, txInfo);
try {
// 2. Execute business (contains branches)
Object ret = executor.execute();
// 3. Notify TC global commit
globalCommit(xid);
return ret;
} catch (Throwable ex) {
// 4. Notify TC global rollback
// TC then asynchronously drives each RM to compensate
globalRollback(xid);
throw ex;
} finally {
// Clean XID from RootContext
RootContext.unbind(xid);
}
}Note: globalCommit is a "notify", not synchronous wait . TC returns immediately after receiving commit request; actual phase 2 (delete undo_log) is asynchronously batch-dispatched by TC. This explains why "commit success" doesn't mean all branches have finished cleanup.
4.3 SQL Rewriting & Image Generation (ConnectionProxy)
// io.seata.rm.datasource.exec.BaseExecutor
// One UPDATE split into six steps:
// 1. Parse SQL AST -> SQLRecognizer
// Identify table, PK, WHERE
// 2. Query beforeImage by WHERE
// select * from t where id=? for update // row lock prevents concurrent modify
// 3. Execute real business SQL
// 4. Query afterImage
// 5. Verify affected row count matches
// 6. Write both images to undo_log, commit with business SQL in same local transaction// Rollback entry AbstractUndoLogManager.undo
// 1. Validate current data with afterImage
// Is it still "my post-modify state"?
if (!afterImage.equals(current)) {
// Modified by another global transaction -> dirty write
throw new SQLException("Compare dirty data");
}
// 2. Generate reverse SQL from beforeImage
// insert -> delete
// delete -> insert
// update -> update set old_values where pk=new_value
// 3. Delete this branch's undo_log
deleteUndoLog(xid, branchId);Source-level takeaways: beforeImage query includes FOR UPDATE — first gate preventing concurrent modification of same row. afterImage validation failure throws exception and marks undo_log abnormal , requiring manual intervention — it's not "auto-repair" but "refuse to rollback on dirty data". This is Incident 2's truth: wrong image scope → validation inevitably mismatches.
4.4 Global Lock: TC-Side lock_table
Before executing local SQL, RM must acquire global lock (table name + PK value) from TC. TC records in lock_table; other global transactions modifying same row queue. Default retry 30 times, interval starting at 10ms increasing; failure throws LockWaitTimeoutException triggering global rollback.
// Two key understandings of global lock:
// 1. Locks "row", not "table"
// Hot item flash sale: same row serialized
// 2. Only blocks writes, not reads
// AT default isolation is READ_UNCOMMITTED
// Others can see your uncommitted intermediate state
// Need read committed? Use SELECT FOR UPDATE
// via global lock query, or switch to TCCTCC Hand-Coded: Three Methods + Three Defenses
TCC makes "resource reservation" explicit: Try freezes resources (available inventory → frozen inventory), Confirm deducts frozen, Cancel unfreezes. Business intrusion trades for no global lock, no dirty reads, controllable performance.
5.1 Runnable TCC Interface
@LocalTCC // Local proxy, no Dubbo needed
public interface StorageService {
@TwoPhaseBusinessAction(
name = "deduct",
commitMethod = "confirm",
rollbackMethod = "cancel")
boolean tryDeduct(
@BusinessActionContextParameter(paramName = "skuId") Long skuId,
@BusinessActionContextParameter(paramName = "count") Integer count);
boolean confirm(BusinessActionContext c);
boolean cancel(BusinessActionContext c);
}@BusinessActionContextParameter pitfall: Only explicitly annotated parameters are serialized into BusinessActionContext for Confirm/Cancel. Unannotated params unavailable; Cancel would have to reverse-query by XID — adding them is like burying a landmine.
5.2 Try's Resource Reservation Implementation
public boolean tryDeduct(Long skuId, Integer count) {
// Conditional update: available -> frozen, single step
// No select-then-update, prevents concurrent oversell
int n = jdbc.update(
"update storage set " +
"available=available-?, " +
"frozen=frozen+? " +
"where sku_id=? and available>=?",
count, count, skuId, count);
return n == 1;
}
public boolean confirm(BusinessActionContext c) {
Long skuId = get(c, "skuId");
Integer n = get(c, "count");
// Frozen -> deducted (idempotent: repeated execution same result)
jdbc.update("update storage set " +
"frozen=frozen-? where sku_id=? " +
"and frozen>=?",
n, skuId, n);
return true;
}5.3 Standard Solutions for Three Problems
Empty Rollback: Try never executed (network loss/crash), but Cancel arrives. Cancel first checks Try record: if absent, inserts a "rolled back" record and returns success without executing business.
Suspension: Cancel arrives before Try (Try network delay). Later Try executes and freezes resource, leaving it stuck forever. Solution shares table with empty rollback: Cancel writes "rolled back"; Try checks before executing, refuses if record exists.
Idempotency: Confirm/Cancel retried multiple times by TC. Use (xid, branch_id) unique key + state machine (TRYING → CONFIRMED / CANCELLED); if already terminal state, return success immediately.
-- Anti-suspension + idempotence: one table solves all
CREATE TABLE tcc_fence_log (
xid VARCHAR(128) NOT NULL,
branch_id BIGINT NOT NULL,
action_name VARCHAR(64) NOT NULL,
status TINYINT NOT NULL, -- 1 TRYING, 2 CONFIRMED, 3 CANCELLED
gmt_create DATETIME(6),
gmt_modified DATETIME(6),
PRIMARY KEY (xid, branch_id)
);Seata includes tcc_fence module; @LocalTCC auto-handles these three. But if TCC is cross-language/custom framework, this table and state flow must be hand-written — interview bonus: "one fence table simultaneously solves suspension and empty rollback" .
Eight High-Frequency Pitfalls
Every DB needs undo_log. Missing one causes branch phase-1 error, global rollback. DDL must be in unified init script.
SQL without PK condition. update t set x=1 where type=2 hits multiple rows; image lookup by PK fails unique row, validation fails. AT only supports "single row by PK" writes.
Hot row global lock queueing. Flash sale same SKU: all transactions contend one global lock, RT spikes. Fix: pre-warm inventory to Redis + async persist; avoid AT on hot path.
@GlobalTransactional on private/internal call. AOP proxy ineffective, degrades to plain local transaction — same root as @Transactional failure (recall transaction chapter).
Default READ UNCOMMITTED causes dirty reads. Others see your uncommitted intermediate state. Must-read-committed scenarios: use SELECT FOR UPDATE or switch to TCC.
TCC params missing @BusinessActionContextParameter. Cancel can't get params, falls back to XID reverse query, edge cases fail directly.
Confirm/Cancel not idempotent. TC retry mechanism guarantees repeated calls; double-charge is just a matter of time.
Transaction emits MQ / calls third-party. Global rollback cannot retract sent messages or SMS. Side effects must move after commit (recall event chapter AFTER_COMMIT).
Troubleshooting Three-Step Method
Step 1: Take XID, query TC's global_table / branch_table, see which RM branch is stuck.
Step 2: Check that RM's undo_log; log_status abnormal means phase 2 failed. Examine RM logs for SQL and exception.
Step 3: Inspect TC's lock_table for leftover global locks; leftovers cause subsequent mass timeouts — manually clean and verify business data.
Learning Path & Interview Questions
7.1 Four-Stage Roadmap
Beginner (1 week): Set up Seata Server + Nacos registration, run official AT example; understand XID propagation, undo_log schema.
Advanced (2 weeks): Read TransactionalTemplate, ConnectionProxy, UndoLogManager source; manually construct dirty write and rollback failure.
Deep (1 month): Implement a TCC business (inventory or quota), use fence table for empty rollback/suspension/idempotency; compare with Saga state machine.
Practice (ongoing): Draw consistency solution diagram for core flows (which segment AT, which TCC, which eventual consistency); establish reconciliation and compensation jobs as last defense.
7.2 Twelve Interview Questions
Differences and applicable scenarios of 2PC, TCC, Saga, Local Message Table?
Responsibilities of Seata's TC, TM, RM?
What does AT phase 1 do? Why "auto rollback"?
What's stored in undo_log? Roles of beforeImage and afterImage?
Global lock granularity? Why AT defaults to READ UNCOMMITTED?
What is dirty write? How does Seata detect? What happens after detection?
Which SQLs does AT support? Which not?
Roles of Try/Confirm/Cancel in TCC? Why resource reservation?
How do empty rollback, suspension, idempotency arise? Solutions?
Why must Cancel handle "Try never executed"?
Is Seata phase 2 commit sync or async? Failure behavior?
Issues with sending MQ in global transaction? Solution?
7.3 One-Page Cheat Sheet
Three roles: TC coordinates / TM initiates / RM resources
AT two-phase: phase 1 local commit + undo_log
phase 2 delete log or reverse compensate
Two images: beforeImage rolls back
afterImage validates dirty write
Global lock: locks row not table, only blocks writes not reads
Default READ UNCOMMITTED!
TCC three defenses: one fence table solves
empty rollback + suspension + idempotence
One sentence: AT convenient with isolation gaps,
TCC controllable but write three methodsSummary: Distributed transactions have no silver bullet, only trade-offs. AT uses undo_log for zero intrusion, costing isolation gaps and SQL boundaries. TCC uses three methods for controllable isolation and performance, costing three problems and dev effort. Message tables push consistency to eventual state, gaining highest availability. Real engineering answer: mix-and-match + reconciliation as safety net. Next up: scaling data — "Spring Boot Sharding — ShardingSphere Landing & Pitfalls".
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
