How Seata Guarantees Zero-Error Cross-Database Transactions: Theory and Full Demo

This article explains Seata's distributed transaction architecture, details the AT transaction mode, walks through single‑node and cluster deployments, and provides complete code examples for stock and order services that demonstrate both successful commits and automatic rollbacks in a microservice environment.

Pan Zhi's Tech Notes
Pan Zhi's Tech Notes
Pan Zhi's Tech Notes
How Seata Guarantees Zero-Error Cross-Database Transactions: Theory and Full Demo

Background

In microservice systems, each service often uses its own database, so a business operation that spans multiple services inevitably involves cross‑database writes. If any service fails after some writes have succeeded, data inconsistency occurs, requiring a reliable distributed transaction solution.

Seata Overview

Seata is an open‑source distributed transaction framework from Alibaba that provides high performance and ease of use. It defines three core roles:

TC (Transaction Coordinator) – maintains global and branch transaction states and drives commit or rollback.

TM (Transaction Manager) – starts a global transaction, defines its scope, and triggers commit/rollback.

RM (Resource Manager) – registers branch transactions with TC and executes commit/rollback on the local resource.

TC runs as a standalone server, while TM and RM are embedded in client applications.

Transaction Lifecycle

TM requests TC to start a global transaction; TC returns an XID.

RM registers a branch transaction using the XID.

After business logic finishes, TM tells TC whether to commit or roll back.

TC instructs each RM to commit or roll back its branch.

If any branch fails, TC records the error for manual intervention.

Transaction Modes

Seata supports AT, TCC, SAGA, and XA. The AT mode is the most popular and is the focus of this guide.

AT Mode Principle

AT is non‑intrusive: Seata intercepts JDBC calls, records before‑image and after‑image data, and writes undo logs to a local undo_log table. The first phase executes the business SQL; the second phase automatically commits or rolls back based on the outcome.

@GlobalTransactional
public void purchase() {
    serviceA.doSomething();
    serviceB.doSomething();
}

Server Deployment

Single‑Node Deployment

Download Seata (e.g., v1.5.2) from https://github.com/seata/seata/releases, extract, and start the bin/seata-server.sh (Linux/macOS) or seata-server.bat (Windows). The default console port is 7091 with username/password seata.

Cluster Deployment

In production, use a database (e.g., MySQL) for the store.db mode and deploy multiple TC servers for high availability. Configure the data source in conf/application.yml and set the driver class ( com.mysql.cj.jdbc.Driver for MySQL 8.x).

Client Integration

Add seata-spring-boot-starter to a Spring Boot project. Seata automatically proxies DataSource and works with JPA/MyBatis. Use @GlobalTransactional on methods that need distributed transaction support.

Stock Service Example

Initialize a MySQL database seata-stock with a tb_stock table and the required undo_log table.

CREATE TABLE `tb_stock` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `product_code` varchar(255) DEFAULT NULL,
  `count` int(11) DEFAULT 0,
  PRIMARY KEY (`id`),
  UNIQUE KEY (`product_code`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `undo_log` (...);

Implement a REST controller with a deduct endpoint, a service that updates the stock, and a MyBatis mapper that runs the SQL

UPDATE tb_stock SET count = count - #{count} WHERE product_code = #{productCode}

. The application’s application.yml includes datasource settings and Seata properties such as seata.application-id, seata.tx-service-group, and the TC address.

spring.application.name=seata-client-stock
server.port=9002
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/seata-stock
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

seata.application-id=seata-client-stock
seata.tx-service-group=my_test_tx_group
seata.service.vgroup-mapping.my_test_tx_group=default
seata.service.grouplist.default=127.0.0.1:8091

Order Service Example

Similarly, create a seata-order database with tb_order and undo_log. The order service’s create method is annotated with @GlobalTransactional, calls the stock service via Seata‑wrapped HttpClient, and inserts an order record.

@GlobalTransactional
public void create(String userId, String productCode, int orderCount) throws Exception {
    reduceStock(productCode, orderCount);
    Order order = new Order();
    order.setUserId(userId);
    order.setProductCode(productCode);
    order.setCount(orderCount);
    order.setMoney(orderCount * 100);
    orderMapper.insert(order);
}

The reduceStock method uses DefaultHttpExecutor to POST to the stock service, automatically propagating the XID.

Testing Scenarios

Successful Commit

Invoke

http://127.0.0.1:9001/order/create?userId=张三&productCode=wahaha&orderCount=1

. Seata registers a global transaction, the stock is deducted, and an order row is inserted. After commit, the undo_log entries are removed.

Exception Rollback

Modify OrderService.create() to throw an exception after the order insert. When the same request is made, Seata rolls back both the stock deduction and the order insert, leaving both databases unchanged. The TC console shows a rollback status.

Conclusion

Seata provides a lightweight, high‑performance solution for distributed transactions in microservice architectures. Mastering its AT mode, deployment options, and client integration enables developers to ensure data consistency across services without writing complex compensation code.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

microservicesspring-bootMySQLDistributed TransactionsSeataAT ModeTC Server
Pan Zhi's Tech Notes
Written by

Pan Zhi's Tech Notes

Sharing frontline internet R&D technology, dedicated to premium original content.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.