Seata Saga Learning Notes: State-Machine-Orchestrated Distributed Long Transactions
Our bank’s core system still runs on that old mainframe. Recently the team has been pushing a modernization effort, slowly migrating it off onto a new distributed architecture. The moment I got into it I was lost — I wasn’t at all familiar with distributed transactions; AT, TCC, Saga, XA were just names I’d heard floating around.
So I’m learning on the fly. Seata is the distributed-transaction framework I’ve been focusing on lately, and its Saga mode happens to fit our migration scenario especially well: the legacy core can’t be touched, you can only call the interfaces it exposes, yet you still have to guarantee the data eventually reconciles. So this post is basically my study notes — written as I learn. If anything here is off, please feel free to correct me.
1. Getting to know the four modes
Seata gives four modes: AT / TCC / Saga / XA. I couldn’t tell them apart at first; later I realized the dividing line is actually pretty practical — it comes down to “can you modify the participant, and do you need to lock resources?”
- AT: near-zero intrusion; the framework auto-records an
undo_logto roll back. The catch: the participant must be a relational DB that supports local transactions, and you have to be able to touch it. Our old mainframe? No chance. - TCC: strong business intrusion — you write the try/confirm/cancel trio yourself. Great performance, but again it assumes you can modify the participant’s logic.
- Saga: long flows, cross-system, unmodifiable participants — its home turf. Each step just calls an interface and pairs it with a compensation operation.
- XA: protocol-based strong consistency, but resources stay locked until commit, so performance is poor; only for low-concurrency traditional scenarios.
To keep myself from getting dizzy, I still made a table (this one genuinely helped when I was starting out):
| Mode | Intrusion | Needs global lock? | Fits | Consistency |
|---|---|---|---|---|
| AT | Almost none (auto undo_log) | Yes | Most OLTP, relational DBs | Strong |
| TCC | Strong (hand-write try/confirm/cancel) | No | Core high-concurrency, lockable resources | Strong |
| Saga | Medium (write compensation) | No | Long flows, cross-system, legacy | Eventual |
| XA | None (protocol-based) | Yes (locked till commit) | Traditional strong-consistency, low concurrency | Strong |
Side note: Saga is way older than Seata — it comes from a 1987 paper titled Sagas. Seata uses the “Orchestration” flavor — a central state machine does the scheduling, instead of services shouting at each other (that variant is called “Choreography”). I picked this up from reading around, so it might not be perfectly precise.
2. What Saga is actually thinking
I first assumed Saga was another two-phase-commit thing, then realized it doesn’t lock resources at all — it commits in one phase and cleans up via “compensation afterward.” The core idea is actually simple:
Split one big transaction into a chain of local transactions; give every step a “regret pill” (a compensation operation); if any step fails, undo everything you already did, in reverse order.
Take “placing an order” as the most straightforward example; the forward chain looks like this:
Forward execution (step by step):
deduct inventory → deduct balance → create order → success
If "deduct balance" fails, compensate in reverse (LIFO):
compensate deduct balance → compensate deduct inventory
These are the points that took me a while to untangle:
- Every state has both a “forward service” and a “compensation service.” E.g. “deduct inventory” maps to
reduce(), and its regret pill iscompensateReduce()(put the inventory back). - Failure compensates in reverse (last-in-first-out). Whichever succeeded last gets undone first. In the example above, inventory deduction already succeeded and balance deduction failed, so we only undo balance and inventory; the order was never created, so nothing to do there.
- The compensation itself must be idempotent and re-entrant. A flaky network might retry compensation several times; your compensation logic has to survive that.
- Watch out for “empty compensation”: sometimes the forward service never actually ran (say it timed out), yet the compensation request arrives first. Your compensation logic needs to recognize that and not blow up.
To put all this into Seata Saga, the core is a State Machine.
Before diving into code, seeing an actual state diagram made it click for me — here’s the example one from the official docs. You can already spot the forward steps each paired with a purple compensation node:

Forward steps each pair with a compensation node (source: Seata official documentation).
3. How Seata Saga actually runs
Seata Saga is held up by a few roles (this part I’m still digesting, so I’ll write it as I understand it):
- StateMachineEngine: the “brain” embedded directly in your app. It loads the state machine definition, drives the flow, triggers compensation on failure, and records the whole process.
- Statelang (state language): a JSON file that describes the entire state machine — what states there are, which service each state calls, who compensates it on failure, where to go next. If hand-writing JSON feels tedious, there’s also an official Seata Saga Designer (an Eclipse-based drag-and-drop tool) to draw it and export.
- Persistence log: the state machine definition and every execution trace get written to the database. This is the bit I think matters most — because the log lives in the DB, if the app crashes it can resume from the breakpoint on restart and finish the unfinished compensation. For a migration-era system like ours, the last thing we want is to get stuck halfway at 3 a.m.; that recovery ability is a hard requirement.
Unlike AT / TCC, the Seata Saga state machine engine is embedded in your application — coordination and recovery both rely on its own database tables, so it usually doesn’t need an extra TC (Seata Server) hanging around to coordinate global transactions the way AT/TCC do. Deployment stays light. I didn’t expect this at first and assumed every mode needed a TC.
One caveat so I don’t mislead you: in some official examples (especially the Dubbo / Spring Cloud integration ones) the demo still tells you to start Seata Server first. So whether you actually need a TC depends on your Seata version and integration style — what I describe here is the “pull in seata-saga and run the state machine standalone” case.
Saga needs these tables (the DDL ships with the Seata release, usually under seata/script, look for the saga-related ones):
seata_state_machine_def—— state machine definitionseata_state_machine_inst—— state machine execution instanceseata_state_inst—— single state execution record (this is what recovery relies on)
Only these three. I first assumed there was a fourth table, seata_state_inst_log, but counting against the official script showed there isn’t — I misremembered.
4. Hands-on: a Saga for order + inventory deduction
Reading concepts always felt floaty to me; I only really got it after typing it out. Below I’ll build a complete chain using “place an order → deduct inventory → deduct balance → create order, and if any step fails, compensate the already-completed steps in reverse.” This actually resembles what I picture as “new system calling the legacy core’s interfaces.”
1. Add the dependency
<dependency>
<groupId>io.seata</groupId>
<artifactId>seata-saga-spring</artifactId>
<version>2.0.0</version> <!-- use the Seata version you're actually on -->
</dependency>
2. Write the state machine JSON
Create createOrderSaga.json under resources/statelang/:
{
"Name": "createOrderSaga",
"Comment": "deduct inventory, then balance, then create order; compensate in reverse on any failure",
"StartState": "ReduceInventory",
"Version": "1.0.0",
"States": {
"ReduceInventory": {
"Type": "ServiceTask",
"ServiceName": "inventoryService",
"ServiceMethod": "reduce",
"CompensateState": "CompensateReduceInventory",
"Next": "ReduceBalance",
"Input": ["$.[inventoryId]", "$.[count]"],
"Output": { "inventoryStatus": "$.#root" },
"Status": { "#root == 0": "SU" }
},
"CompensateReduceInventory": {
"Type": "ServiceTask",
"ServiceName": "inventoryService",
"ServiceMethod": "compensateReduce",
"Input": ["$.[inventoryId]", "$.[count]"]
},
"ReduceBalance": {
"Type": "ServiceTask",
"ServiceName": "accountService",
"ServiceMethod": "reduce",
"CompensateState": "CompensateReduceBalance",
"Next": "CreateOrder",
"Input": ["$.[userId]", "$.[amount]"],
"Output": { "balanceStatus": "$.#root" }
},
"CompensateReduceBalance": {
"Type": "ServiceTask",
"ServiceName": "accountService",
"ServiceMethod": "compensateReduce",
"Input": ["$.[userId]", "$.[amount]"]
},
"CreateOrder": {
"Type": "ServiceTask",
"ServiceName": "orderService",
"ServiceMethod": "create",
"CompensateState": "CompensateCreateOrder",
"Next": "Succeed",
"Input": ["$.[userId]", "$.[inventoryId]", "$.[count]"],
"Output": { "orderId": "$.#root" }
},
"CompensateCreateOrder": {
"Type": "ServiceTask",
"ServiceName": "orderService",
"ServiceMethod": "cancel",
"Input": ["$.[orderId]"]
},
"Succeed": {
"Type": "Succeed"
}
}
}
The first time I looked at this JSON I was lost; only after matching the fields one by one did it click: CompensateState is “who cleans up if this step fails,” Next is “where to go if it succeeds,” and Input/Output are how parameters flow in and out.
3. Write the forward / compensation services
The services exist as Spring Beans; the state machine finds them by ServiceName, and the method parameter order must line up with the Input in the JSON:
@Service("inventoryService")
public class InventoryService {
/** Forward: deduct inventory; return 0 means success */
public int reduce(String inventoryId, int count) {
// TODO: real inventory deduction logic
return 0;
}
/** Compensation: put the inventory back (must be idempotent) */
public void compensateReduce(String inventoryId, int count) {
// TODO: restore inventory logic
}
}
@Service("accountService")
public class AccountService {
public int reduce(String userId, BigDecimal amount) { return 0; }
public void compensateReduce(String userId, BigDecimal amount) { }
}
@Service("orderService")
public class OrderService {
public String create(String userId, String inventoryId, int count) { return "order_123"; }
public void cancel(String orderId) { }
}
4. Wire up the engine and the template
Configure the state machine engine and the call template, pointing at the datasource that persists things:
@Configuration
public class SeataSagaConfig {
@Bean
public StateMachineEngine stateMachineEngine(DataSource dataSource) throws Exception {
DbStateMachineConfig config = new DbStateMachineConfig();
config.setDataSource(dataSource); // state def + exec log both land here
// Note: this takes a Spring Resource[], not a String[]
config.setResources(new PathMatchingResourcePatternResolver()
.getResources("classpath*:statelang/*.json"));
config.setEnableAsync(true); // run async for better throughput
DefaultStateMachineEngine engine = new DefaultStateMachineEngine();
engine.setStateMachineConfig(config);
engine.init(); // load state defs on startup
return engine;
}
@Bean
public SagaTransactionalTemplate sagaTransactionalTemplate(StateMachineEngine engine) {
SagaTransactionalTemplate template = new SagaTransactionalTemplate();
template.setStateMachineEngine(engine);
return template;
}
}
SagaTransactionalTemplate took me a moment to grasp: it just wraps “start the state machine + wrap it in a transaction context,” so all you do is execute(...) and hand it over.
5. Fire the call
@Autowired
private SagaTransactionalTemplate sagaTransactionalTemplate;
public String createOrder(OrderCmd cmd) {
Map<String, Object> startParams = new HashMap<>();
startParams.put("inventoryId", cmd.getInventoryId());
startParams.put("count", cmd.getCount());
startParams.put("userId", cmd.getUserId());
startParams.put("amount", cmd.getAmount());
String businessKey = "createOrder_" + cmd.getOrderId(); // business key, for idempotency & lookup
StateMachineInstance inst = sagaTransactionalTemplate.execute(
"createOrderSaga", // state machine name, matches JSON "Name"
null, // tenantId
businessKey,
startParams);
if (ExecutionStatus.SU.equals(inst.getStatus())) {
return "order placed, id: " + inst.getEndParams().get("orderId");
} else {
throw new RuntimeException("order failed, auto-compensated, status=" + inst.getStatus());
}
}
6. So how does compensation actually happen?
Suppose accountService.reduce() throws an exception:
- The engine catches it and marks
ReduceBalanceas failed; - Following
CompensateStatebackward, it callsCompensateReduceBalance, thenCompensateReduceInventory; - Each compensation result is also written to the log;
- Finally the state machine instance becomes
FA(failed) — to the caller it means “order didn’t go through, and it’s already rolled back cleanly.”
If the process crashes halfway, after restart the engine scans the unfinished instances and continues the compensation along the trace recorded in seata_state_inst — that’s the “persistence” point from earlier, and the fallback we care about most during migration.
5. JSON fields I’ve noted so far
No need to memorize everything; just get the common ones familiar, then fill in as you write:
| Field | What it does |
|---|---|
Name / Version / StartState |
state machine name, version, the entry state |
Type |
state type: ServiceTask (call a service), Choice (branch), Succeed/Fail (success/failure end), CompensationTrigger (trigger compensation), SubStateMachine (sub state machine), ScriptTask (script) |
ServiceName / ServiceMethod |
the service bean name and method to call |
CompensateState |
which compensation state to use if this one fails |
Next |
where to go on success |
Input / Output |
in/out parameter mapping, using JSONPath expressions (e.g. $.[count], $.#root for the return value) |
Status |
translate a business return code into a status (SU success, UN unknown/retry, FA failure triggers compensation — see the ExecutionStatus enum for your version) |
Retry |
retry policy: Exceptions, MaxAttempts, IntervalSeconds, BackoffRate |
Catch |
catch exceptions and branch elsewhere |
Choice can fork based on context (e.g. route by amount to different risk checks); SubStateMachine can pull a complex sub-flow out for reuse. Together they can describe a fairly complicated business orchestration. I haven’t used those two in anger yet, just noting them down.
6. My takeaways on Saga so far
The good
- Doesn’t require participants to support local transactions — it can pull legacy systems and third parties into the transaction. During our migration, calling the legacy core’s interfaces leans on exactly this.
- One-phase commit, no global lock, so response time and throughput stay comfortable for long flows.
- Can recover after a crash, with the persistence log as the eventual-consistency backstop.
The pitfalls to watch
- Weak isolation: two Sagas concurrently editing the same resource can cause dirty reads or lost updates. Mitigations exist — semantic locks, re-read validation, version numbers, countermeasures — but I’m still reading up on these.
- You write the compensation yourself, and it must be idempotent, re-entrant, and able to swallow “empty compensation” (compensation arriving before the forward ever ran).
- “Unknown” states can show up: a service times out and you don’t know if it actually succeeded. That
UNstatus often needs a human fallback, or a scheduled job to reconcile/retry. - Compared to AT’s “almost zero intrusion,” Saga’s intrusion is that you have to design the compensation semantics for every step.
One line: Saga moves the “consistency” burden from the framework’s shoulders onto your business design. It doesn’t do the compensation for you — it only guarantees the compensation gets executed reliably, in order. The rest of the headache is on you.
7. Wrapping up
- Seata’s Saga mode is a distributed-transaction solution for long flows, cross-system, unmodifiable participants — it lines up unusually well with our stretch of migrating off the legacy core.
- Its core is a state machine: write the “forward steps + compensation steps” in JSON, the engine drives it, and on failure it compensates in reverse.
- It runs embedded in your app and recovers via the DB log, generally without deploying a separate Seata Server.
- The cost is weak isolation and compensation you must make idempotent — it fits scenarios where “eventual consistency” is acceptable, not strong-consistency core trades.
Notes stop here for now. I’m still a beginner at distributed stuff, so if anything above is wrong, please be gentle and correct me. Once this actually goes live in the migration, I’ll probably come back and add a real war-story post.
References: Seata official documentation · Seata Saga mode





