Mastering Distributed Transactions with Seata: Theory, Options, and Hands‑On Practice
This article explains the concept of distributed transactions, compares common solutions such as 2PC, 3PC, TCC, and message‑based eventual consistency, and provides a detailed walkthrough of configuring and using the Seata middleware—including AT mode workflow, server and client setup, and real‑world testing—so developers can confidently implement reliable cross‑service transactions.
Distributed Transaction Overview
Distributed transactions involve participants, transaction managers, resource servers, and coordinators located on different nodes of a distributed system.
When a system is small, a monolithic architecture with a single database can handle order creation in one transaction. As traffic grows, sharding and SOA split the application into separate services (order, inventory, user) that communicate via RPC, making global consistency harder.
Seata Advantages
Many distributed‑transaction solutions exist: XA‑based 2PC/3PC, business‑level TCC, message‑queue based eventual consistency, and the Seata middleware, which supports AT, TCC, SAGA, and XA modes.
2PC
Implemented via the XA protocol, 2PC separates a global transaction manager and local resource managers (usually databases). It offers strong ACID guarantees with minimal code intrusion but blocks resources during the commit phase, leading to poor performance under high concurrency.
3PC
3PC adds a preparation phase and timeout mechanisms for both coordinator and participants, reducing the blocking problem of 2PC but incurring an extra network round‑trip and still suffering performance penalties.
TCC
TCC (Try‑Confirm‑Cancel) requires three methods per business operation. It avoids resource locking because each branch commits immediately, but the approach is invasive and increases development effort.
Message Transaction (Final Consistency)
Combines a local transaction with a message‑queue operation; the message is stored as a pending record and only committed after the local transaction succeeds, providing eventual consistency with higher throughput.
Order system sends a pre‑deduction message to MQ and receives ACK.
MQ invokes a callback to verify the local transaction; on success it commits, on failure it rolls back.
Inventory service consumes the message, performs the local deduction, and retries on failure.
Seata
Seata evolved from 2PC and offers multiple transaction modes. The AT mode, which is the focus here, records before‑ and after‑images of data changes in an undo_log table, enabling automatic rollback without locking resources.
AT Mode Workflow – Phase 1
When a SQL statement is executed, Seata’s JDBC proxy parses the statement, extracts metadata (type, table, condition), queries the before‑image, executes the business SQL, then queries the after‑image and writes both images together with transaction metadata into undo_log .
<code>update user set name='小富最帅' where name='程序员内点事'</code>The undo record contains branchId, xid, beforeImage, afterImage, and other metadata.
<code>{
"branchId":641789253,
"xid":"xid:xxx",
"undoItems":[{
"afterImage":{...},
"beforeImage":{...},
"sqlType":"UPDATE"
}]
}</code>AT Mode Workflow – Phase 2
During the second phase the global transaction coordinator (TC) decides to commit or rollback. If commit, each branch removes its undo log; if rollback, the branch reads the undo log, generates reverse SQL, and reverts the data.
Seata Practice
Seata Server
Download the latest seata-server-1.4.0 package, then edit conf/file.conf and conf/registry.conf to choose persistence (file, db, redis) and registry (eureka, nacos, zk, etc.).
file.conf
Defines how transaction logs are persisted. When using the db mode, create the tables global_table , branch_table , and lock_table in the chosen database.
registry.conf
Configures the service registry and configuration center. In this tutorial the eureka registry is used.
Starting the Server
Run seata-server under seata/bin to launch the Seata service.
Seata Client
Create three Spring Boot services: order-server , storage-server , and account-server . Register them to Eureka and add the Seata starter with a transaction group (e.g., my_test_tx_group ).
<code>spring:
application:
name: storage-server
cloud:
alibaba:
seata:
tx-service-group: my_test_tx_group
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://47.93.6.1:3306/seat-storage
username: root
password: root
eureka:
client:
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:8761/eureka/
instance:
hostname: 47.93.6.5
prefer-ip-address: true</code>The business flow: the order service creates an order record, then calls the storage and account services via RPC. All three services must succeed; otherwise Seata rolls back the whole transaction.
<code>@GlobalTransactional(name = "create-order", rollbackFor = Exception.class)
public void create(Order order) {
String xid = RootContext.getXID();
LOGGER.info("----> Transaction start");
orderDao.create(order);
storageApi.decrease(order.getProductId(), order.getCount());
accountApi.decrease(order.getUserId(), order.getMoney());
LOGGER.info("----> Transaction end, xid: {}", xid);
}</code>Testing Seata
After starting all services, invoke the order API. Successful execution shows records inserted in the order table, inventory usage incremented, and account balance deducted. The TM (order‑server) logs two‑phase commit messages.
When an exception is forced in the account service, Seata rolls back the global transaction, leaving no changes in any database.
Undo logs are written to the undo_log table during the first phase and removed quickly after a successful commit.
Summary
The article compared 2PC, 3PC, TCC, MQ‑based eventual consistency, and Seata, then demonstrated a complete Seata AT‑mode implementation. While distributed transactions guarantee data consistency, they introduce latency and complexity; therefore they should be used only when strong consistency is essential.
Sanyou's Java Diary
Passionate about technology, though not great at solving problems; eager to share, never tire of learning!
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.