Seata
While migrating to microservice architectures brings exceptional business agility and horizontal scalability, it simultaneously introduces a formidable challenge: maintaining data consistency across distributed systems. In traditional monolithic applications, developers heavily rely on local database transactions (ACID) to ensure data integrity. However, in a decentralized microservice environment, a single business operation frequently spans multiple databases and discrete services, rendering traditional local transactions obsolete.
Seata (Simple Extensible Autonomous Transaction Architecture), an open-source distributed transaction solution initiated by Alibaba, is engineered to provide high-performance and user-friendly distributed transaction services in microservice architectures.
At its foundation, Seata treats Java applications as both initiators and participants of distributed transactions, collectively referred to as TM (Transaction Manager). The architecture revolves around three core components that work in harmony:
- TC (Transaction Coordinator): An independent, centralized server responsible for maintaining the status of global and branch transactions, as well as driving the final commitment or rollback of global transactions.
- TM (Transaction Manager): Responsible for defining the boundaries of a global transaction—specifically beginning, committing, or rolling it back. Typically embedded within the service that initiates the global call.
- RM (Resource Manager): Manages the resources associated with branch transactions. It communicates with the TC to register branch transactions, report their execution statuses, and execute local branch commits or rollbacks. Usually represented by the data source owners in downstream microservices.
The standard execution workflow is straightforward: the TM requests the TC to initialize a global transaction. As the transaction propagates across various RMs, the TC monitors their individual execution results and ultimately dictates whether the global transaction should commit or roll back.
The Four Transaction Modes of Seata
To accommodate diverse business scenarios and performance requirements, Seata offers four mainstream distributed transaction modes:
- AT Mode (Auto Transaction): An evolution of the two-phase commit protocol. It requires zero business code modification and automatically generates rollback logs through SQL parsing. This is the most widely adopted mode.
- TCC Mode (Try-Confirm-Cancel): Does not rely on database-level support for phase locking. Instead, it achieves distributed transaction control through custom business logic implementation. While it delivers superior performance, it demands higher development effort.
- Saga Mode: Tailored for long-running transactions, leveraging forward actions and compensating services to achieve eventual consistency. It is ideal for asynchronous and complex business workflows.
- XA Mode: Relies on the database-level XA protocol to guarantee strong consistency. However, its performance is constrained by resource locking, and it imposes strict requirements on the underlying database engine.
For the vast majority of enterprise applications, AT Mode is strongly recommended as the default choice due to its exceptionally low intrusiveness into existing codebases.
Practical Implementation of Seata AT Mode
Implementing Seata AT Mode within a Spring Boot ecosystem involves a few standard configuration steps.
1. Database Preparation
Every database participating in a Seata-managed transaction must contain an undo_log table. This table stores the inverse SQL statements required to revert data changes during a rollback.
CREATE TABLE `undo_log` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`branch_id` bigint(20) NOT NULL,
`xid` varchar(100) NOT NULL,
`context` varchar(128) NOT NULL,
`rollback_info` longblob NOT NULL,
`log_status` int(11) 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 AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
2. Maven Dependencies
Include the relevant Seata and Spring Cloud Alibaba dependencies in your project's build file:
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-seata</artifactId>
</dependency>
3. Registry and Configuration Setup
Create a registry.conf file under your project's resources directory to point to your discovery and configuration centers (such as Nacos):
registry {
type = "nacos"
nacos {
application = "seata-server"
serverAddr = "127.0.0.1:8848"
group = "SEATA_GROUP"
namespace = ""
}
}
config {
type = "nacos"
nacos {
serverAddr = "127.0.0.1:8848"
group = "SEATA_GROUP"
namespace = ""
}
}
4. Applying the @GlobalTransactional Annotation
In the business layer, the initiator of the distributed transaction simply needs to annotate the orchestration method with @GlobalTransactional.
import io.seata.spring.annotation.GlobalTransactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class OrderServiceImpl implements OrderService {
@Autowired
private AccountClient accountClient;
@Autowired
private OrderMapper orderMapper;
@Override
@GlobalTransactional(name = "create-order-tx", rollbackFor = Exception.class)
public void createOrder(Order order) {
// 1. Create local order record
orderMapper.insert(order);
// 2. Invoke remote account service to deduct balance
accountClient.reduceBalance(order.getUserId(), order.getMoney());
// Simulate an exception to test global rollback
if (order.getMoney().compareTo(new BigDecimal("9999")) > 0) {
throw new RuntimeException("Amount exceeds limit, triggering rollback!");
}
}
}
When the createOrder method executes, any runtime exception thrown will prompt Seata to automatically revert both the remote service calls and local database modifications using the entries preserved in the undo_log, ensuring absolute data consistency.
Conclusion
As a prominent open-source solution in the realm of distributed transactions, Seata dramatically lowers the barrier for developers managing data consistency in microservices, largely thanks to its non-intrusive AT mode. By properly orchestrating the TC, TM, and RM components alongside the @GlobalTransactional annotation, development teams can reliably build resilient, highly available distributed systems tailored to specific business demands.