Saga pattern: rollback xuyên microservices bằng bước bù

- Published on
- 14 mins read
Khách bấm đặt hàng. Order Service tạo đơn xong, Inventory giữ hàng xong, tới Payment thì thẻ bị từ chối.
Giờ đơn đã nằm trong DB, hàng đã bị giữ, còn tiền thì không có. Ở monolith, một cái rollback là xong chuyện. Tách thành microservices rồi thì chẳng còn cái rollback nào bao được cả ba service, và bạn phải tự viết đường lui cho từng bước.
# vấn đề: sao microservices không dùng được acid transaction?
Ở monolith, bạn bọc hết vào 1 @Transactional: tạo order, trừ tiền, giảm inventory. Hoặc tất cả cùng thành công, hoặc tất cả cùng rollback. Database lo ACID cho mình. Đời đẹp.
Tách ra microservices thì câu chuyện khác hẳn: Order Service nằm trên một PostgreSQL riêng, Payment Service một DB riêng, Inventory Service lại một DB khác. Lúc này không còn TransactionManager cục bộ nào bao được cả 3 database nữa. Nhiều người nghĩ ngay tới chuẩn Two-Phase Commit (2PC / XA). Có điều đưa vào hệ thống microservices chịu tải cao thì 2PC lộ ra khá nhiều điểm nghẽn. Giao thức phải giữ khoá (row lock) trên cả 3 database suốt hai pha hỏi và chốt qua mạng, nên rất chậm, và service nào cũng bị trói vào tốc độ của service chậm nhất. Coordinator mà sập đúng lúc đang chờ thì các bản ghi bị khoá treo cứng (in-doubt transaction). Chưa kể nhiều NoSQL và message broker hiện đại không hề hỗ trợ XA.
Saga Pattern (khái niệm có từ bài báo "Sagas" của Hector Garcia-Molina và Kenneth Salem năm 1987, vốn dành cho transaction chạy lâu trong một database) giải bài này: thay vì một transaction to, chia ra thành chuỗi local transaction. Service nào tự commit local transaction của service đó. Có step nào fail thì chạy compensating transaction để hoàn tác các step trước.
# saga chạy thế nào
Saga là một chuỗi local transaction, mỗi transaction cập nhật 1 service/database. Local transaction nào xong thì publish event/message để kích step tiếp theo. Có step fail thì chạy compensating transaction theo thứ tự ngược lại.

Điểm cần nhớ: Saga KHÔNG đảm bảo Isolation (chữ I trong ACID). Giữa T2 và T3, inventory đã reserve nhưng payment chưa charge, và transaction khác vẫn nhìn thấy cái state "tạm thời lệch" này. Trong hệ thống phân tán, đây là trade-off chấp nhận được (chấp nhận BASE thay vì ACID), nhưng phải chủ động xử lý: dùng trạng thái trung gian như PENDING làm "semantic lock" (xem phần dưới), thiết kế các cập nhật có thể đảo thứ tự mà vẫn đúng (cộng/trừ số dư thay vì ghi đè), hoặc đọc lại dữ liệu trước khi ghi để phát hiện thay đổi.
# hai mô hình: choreography vs orchestration
# choreography: event-driven, không có người điều phối trung tâm
Service nào cũng tự nghe event rồi tự quyết phản ứng ra sao. Không ai "chỉ huy" cả. Giống ban nhạc jazz: mọi người nghe nhau rồi ngẫu hứng.

// Order Service — publishes event after creating order
@Service
@RequiredArgsConstructor
public class OrderService {
private final OrderRepository orderRepository;
private final RabbitTemplate rabbitTemplate;
@Transactional
public OrderDTO createOrder(CreateOrderRequest request) {
Order order = Order.builder()
.customerId(request.getCustomerId())
.items(request.getItems())
.status(OrderStatus.PENDING)
.build();
order = orderRepository.save(order);
// Publish event → Inventory Service listens
// Lưu ý: gửi message ngay trong @Transactional là "dual write": message đi trước khi DB commit,
// DB rollback thì message vẫn đã gửi. Production nên dùng Transactional Outbox (xem đoạn ngay dưới)
rabbitTemplate.convertAndSend("order.exchange", "order.created",
new OrderCreatedEvent(order.getId(), order.getItems(), order.getTotalAmount()));
return toDTO(order);
}
}
// Inventory Service — listens and reacts
@Component
@RequiredArgsConstructor
@Slf4j
public class InventoryEventListener {
private final InventoryService inventoryService;
private final RabbitTemplate rabbitTemplate;
@RabbitListener(queues = "inventory.order-created")
public void onOrderCreated(OrderCreatedEvent event) {
try {
inventoryService.reserve(event.getOrderId(), event.getItems());
// Success → notify Payment Service
rabbitTemplate.convertAndSend("order.exchange", "inventory.reserved",
new InventoryReservedEvent(event.getOrderId(), event.getTotalAmount()));
} catch (InsufficientStockException e) {
// Fail → compensate: cancel order
rabbitTemplate.convertAndSend("order.exchange", "inventory.failed",
new InventoryFailedEvent(event.getOrderId(), e.getMessage()));
}
}
// Compensation: release inventory khi payment fails
@RabbitListener(queues = "inventory.payment-failed")
public void onPaymentFailed(PaymentFailedEvent event) {
inventoryService.release(event.getOrderId());
log.info("Inventory released for order: {}", event.getOrderId());
}
}Code trên cố tình giữ đơn giản để thấy luồng event, nhưng có một lỗ hổng kinh điển: ghi DB và gửi message là hai hệ thống khác nhau, không cùng một transaction. Order lưu xong mà broker chết thì saga không bao giờ chạy tiếp; ngược lại message đã gửi mà DB rollback thì Inventory đi reserve cho một order không tồn tại. Cách chuẩn là Transactional Outbox: ghi event vào bảng outbox trong cùng local transaction với order, rồi một tiến trình riêng (polling hoặc CDC như Debezium) đọc bảng đó và đẩy lên broker. Listener phía Inventory cũng vậy. Chi tiết có trong bài transactional outbox và idempotent consumer.
Điểm mạnh của Choreography là nhẹ. Không cần dựng thêm service điều phối nào, các service cũng chẳng cần biết nhau, chỉ nói chuyện qua event. Muốn gắn thêm bước mới (như tích điểm thành viên) thì cho service mới nghe queue là xong.
Đổi lại, quy trình càng dài thì luồng nghiệp vụ càng bị xé lẻ khắp codebase của 5-6 repo. Mỗi lần có đơn kẹt giữa chừng, bạn phải lần từng event qua cả đống log mới biết nó dừng ở đâu. Không kiểm soát kỹ thì còn dễ sinh vòng lặp sự kiện (A bắn event kích B, B lại bắn event kích ngược A). Còn muốn áp một chính sách timeout hay retry chung cho cả quy trình thì khá vất vả.
# orchestration: có người điều phối trung tâm
Một Saga Orchestrator nắm toàn bộ flow, gọi lần lượt từng service và xử lý khi có lỗi. Giống nhạc trưởng trong dàn nhạc: một người chỉ huy, cả dàn làm theo.

/**
* Saga Orchestrator — biết toàn bộ flow, điều phối step-by-step.
*
* Implement dưới dạng state machine hoặc sequential steps.
* Mỗi step: execute → success → next step / fail → compensate previous steps.
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class CreateOrderSagaOrchestrator {
private final OrderService orderService;
private final InventoryClient inventoryClient;
private final PaymentClient paymentClient;
private final NotificationClient notificationClient;
/**
* Execute saga: từng step, rollback nếu fail.
*
* Flow: Create Order → Reserve Inventory → Charge Payment → Confirm
* Compensate: Cancel Order ← Release Inventory ← Refund Payment
*/
public OrderDTO execute(CreateOrderRequest request) {
// Step 1: Create order (PENDING status)
OrderDTO order = orderService.create(request);
log.info("Saga step 1/4: Order created | orderId={}", order.getId());
try {
// Step 2: Reserve inventory
inventoryClient.reserve(order.getId(), request.getItems());
log.info("Saga step 2/4: Inventory reserved | orderId={}", order.getId());
try {
// Step 3: Charge payment
paymentClient.charge(order.getId(), order.getTotalAmount(), request.getPaymentMethod());
log.info("Saga step 3/4: Payment charged | orderId={}", order.getId());
// Step 4: Confirm order
orderService.confirm(order.getId());
notificationClient.sendOrderConfirmation(order.getCustomerId(), order.getId());
log.info("Saga step 4/4: Order confirmed | orderId={}", order.getId());
return orderService.getById(order.getId());
} catch (PaymentException e) {
// Compensate step 2: release inventory
log.warn("Saga compensation: payment failed, releasing inventory | orderId={}",
order.getId());
inventoryClient.release(order.getId());
orderService.cancel(order.getId(), "Payment failed: " + e.getMessage());
throw new OrderCreationFailedException("Payment failed", e);
}
} catch (InsufficientStockException e) {
// Compensate step 1: cancel order
log.warn("Saga compensation: insufficient stock, cancelling order | orderId={}",
order.getId());
orderService.cancel(order.getId(), "Insufficient stock: " + e.getMessage());
throw new OrderCreationFailedException("Insufficient stock", e);
}
}
}Code orchestrator ở trên là bản tối giản. Bản chạy production còn thiếu mấy thứ quan trọng:
- Lưu trạng thái saga: orchestrator chết giữa step 2 và step 3 thì khi khởi động lại phải biết saga đang ở đâu để chạy tiếp hoặc compensate. Trạng thái (bước hiện tại, kết quả từng bước) cần được ghi vào DB sau mỗi bước, thay vì chỉ giữ tạm trên call stack.
- Lỗi không lường trước: code chỉ bắt
PaymentExceptionvàInsufficientStockException. Lỗi mạng,RuntimeExceptionkhác hay notification fail sau khi đã confirm sẽ để order kẹt ởPENDINGmà không ai compensate. - Kết quả mơ hồ: gọi
chargebị timeout không có nghĩa là chưa trừ tiền. Phải hỏi lại Payment (theoorderId) hoặc compensate theo kiểu "refund nếu đã charge".
Đây cũng là lý do nhiều team dùng sẵn engine như Temporal, AWS Step Functions hay BPMN engine (phần dưới) thay vì tự viết.
Orchestration gom toàn bộ luồng điều khiển về một chỗ. Nhìn vào một class hoặc một sơ đồ là biết đơn hàng đi qua những bước nào, đang dừng ở đâu. Timeout, retry hay bước bù đều nằm ở nhạc trưởng, nên không phải lo phụ thuộc vòng giữa các service con.
Cái giá là Orchestrator thành điểm nhạy cảm của cả kiến trúc. Nó phải biết giao diện của mọi service tham gia. Hạ tầng của nó sập thì mọi đơn hàng mới đứng hình. Và nếu dev dồn cả logic nghiệp vụ chi tiết vào đó thay vì chỉ điều phối, nó rất dễ phình thành một "god service".
# khi nào dùng cái nào?
| Tiêu chí | Choreography | Orchestration |
|---|---|---|
| Số service | 2-3 (đơn giản) | 4+ (phức tạp) |
| Độ phức tạp của flow | Thẳng, ít rẽ nhánh | Nhiều nhánh, nhiều điều kiện |
| Cách chia team | Mỗi team giữ 1 service | 1 team giữ cả flow |
| Nhu cầu debug | Thấp (flow đơn giản) | Cao (flow phức tạp) |
| Business nhìn thấy flow | Khó | Dễ (flow hiện rõ) |
| Dễ thay đổi | Cao (thêm listener) | Vừa (sửa orchestrator) |
Kinh nghiệm: flow đơn giản (2-3 step) thì bắt đầu bằng Choreography. Khi flow từ 4 step trở lên hoặc rẽ nhánh, compensation phức tạp thì chuyển sang Orchestration.
# mấy vấn đề phải xử lý
# idempotency: "bị trừ tiền 2 lần vì retry"
Message broker có thể giao một message nhiều lần (at-least-once). Compensating transaction cũng có thể bị gọi nhiều lần. Nên step nào cũng PHẢI idempotent.
@Service
@RequiredArgsConstructor
@Slf4j
public class PaymentService {
private final PaymentRepository paymentRepository;
@Transactional
public PaymentResult charge(UUID orderId, BigDecimal amount) {
// Check idempotency: đã charge cho order này chưa?
Optional<Payment> existing = paymentRepository.findByOrderId(orderId);
if (existing.isPresent()) {
log.info("Payment already processed for order: {}", orderId);
return existing.get().toResult(); // Return existing result, don't charge again
}
// First time → execute charge
// Check-then-act ở trên chưa đủ: 2 message trùng tới cùng lúc vẫn lọt qua cả hai.
// Cần UNIQUE(order_id) ở bảng payment để insert thứ hai fail, và gửi orderId làm
// idempotency key cho payment gateway để chính gateway không trừ tiền 2 lần
Payment payment = processCharge(orderId, amount);
return payment.toResult();
}
}# timeout: "saga kẹt mãi không xong"
Step nào cũng cần timeout. Service không trả lời trong X giây → coi như fail → chạy compensate.
// Orchestrator với timeout per step
CompletableFuture<InventoryResult> inventoryFuture = CompletableFuture
.supplyAsync(() -> inventoryClient.reserve(orderId, items))
.orTimeout(10, TimeUnit.SECONDS); // 10s timeout
try {
InventoryResult result = inventoryFuture.join();
} catch (CompletionException e) {
// orTimeout làm future fail với TimeoutException, join() bọc nó trong CompletionException
if (!(e.getCause() instanceof TimeoutException)) {
throw e;
}
// Timeout = treat as failure → compensate.
// Nhưng request có thể đã tới Inventory và reserve thành công, nên release luôn
// (release phải idempotent: chưa reserve thì không làm gì)
inventoryClient.release(orderId);
orderService.cancel(orderId, "Inventory service timeout");
throw new SagaTimeoutException("Inventory reservation timed out");
}Hai chỗ dễ sai ở đây. Một, get() không ném TimeoutException trực tiếp mà bọc trong ExecutionException (join() thì bọc trong CompletionException), nên catch (TimeoutException e) quanh get() không biên dịch được. Hai, orTimeout chỉ làm future của mình kết thúc, không huỷ được request đang chạy (thread trong ForkJoinPool.commonPool() vẫn chờ tiếp). Trong thực tế nên đặt timeout ngay ở HTTP client (connect/read timeout) và coi timeout là "không rõ kết quả" chứ không phải "chắc chắn thất bại".
# semantic lock: tránh "dirty read" giữa các step của saga
Khi order còn PENDING (đang giữa các step), người khác không nên thấy nó như đã xong. Dùng field status: PENDING → CONFIRMED hoặc PENDING → CANCELLED. Các thao tác khác (huỷ đơn, sửa đơn, giao hàng) phải kiểm tra status này trước: gặp order chưa ở trạng thái cuối thì từ chối hoặc chờ, đó mới là "lock".
public enum OrderStatus {
PENDING, // Saga đang chạy — chưa final
INVENTORY_RESERVED, // Step 2 done
PAYMENT_CHARGED, // Step 3 done
CONFIRMED, // Saga complete — happy path
CANCELLED, // Saga compensated — sad path
COMPENSATION_FAILED // Compensation cũng fail — cần manual intervention
}# saga + bpmn: dùng process engine làm orchestrator
BPMN engine (Activiti, Flowable, Camunda) vốn đã hợp làm Saga Orchestrator. Mỗi service task là 1 step của saga, error boundary event là chỗ kích compensation, còn compensation handler chứa logic hoàn tác.
<!-- BPMN as Saga Orchestrator (rút gọn: bỏ khai báo namespace và phần diagram) -->
<error id="PAYMENT_FAILED" errorCode="PAYMENT_FAILED"/>
<process id="createOrderSaga">
<startEvent id="start"/>
<sequenceFlow id="f1" sourceRef="start" targetRef="createOrder"/>
<!-- Step 1: Create Order -->
<serviceTask id="createOrder" activiti:delegateExpression="${createOrderDelegate}"/>
<boundaryEvent id="createOrderCompensation" attachedToRef="createOrder">
<compensateEventDefinition/>
</boundaryEvent>
<serviceTask id="cancelOrder" isForCompensation="true"
activiti:delegateExpression="${cancelOrderDelegate}"/>
<!-- compensation handler nối với boundary event bằng association, không phải sequenceFlow -->
<association id="a1" sourceRef="createOrderCompensation" targetRef="cancelOrder"
associationDirection="One"/>
<sequenceFlow id="f2" sourceRef="createOrder" targetRef="reserveInventory"/>
<!-- Step 2: Reserve Inventory -->
<serviceTask id="reserveInventory" activiti:delegateExpression="${reserveInventoryDelegate}"/>
<boundaryEvent id="reserveCompensation" attachedToRef="reserveInventory">
<compensateEventDefinition/>
</boundaryEvent>
<serviceTask id="releaseInventory" isForCompensation="true"
activiti:delegateExpression="${releaseInventoryDelegate}"/>
<association id="a2" sourceRef="reserveCompensation" targetRef="releaseInventory"
associationDirection="One"/>
<sequenceFlow id="f3" sourceRef="reserveInventory" targetRef="chargePayment"/>
<!-- Step 3: Charge Payment (may fail, delegate ném BpmnError("PAYMENT_FAILED")) -->
<serviceTask id="chargePayment" activiti:delegateExpression="${chargePaymentDelegate}"/>
<boundaryEvent id="paymentError" attachedToRef="chargePayment">
<errorEventDefinition errorRef="PAYMENT_FAILED"/>
</boundaryEvent>
<sequenceFlow id="f4" sourceRef="chargePayment" targetRef="success"/>
<!-- Happy path end -->
<endEvent id="success"/>
<!-- Error path: trigger compensation for all completed steps (ngược thứ tự hoàn thành) -->
<sequenceFlow id="f5" sourceRef="paymentError" targetRef="compensateAll"/>
<intermediateThrowEvent id="compensateAll">
<compensateEventDefinition/>
</intermediateThrowEvent>
<sequenceFlow id="f6" sourceRef="compensateAll" targetRef="sagaFailed"/>
<endEvent id="sagaFailed"/>
</process>Cái lợi: flow nhìn được trên diagram, có version control, có sẵn monitoring, retry/timeout hỗ trợ sẵn, và quan trọng nhất là engine tự lưu trạng thái từng process instance vào DB, giải quyết luôn chuyện orchestrator chết giữa chừng. Nhiều hệ thống enterprise làm Saga theo cách này, khỏi phải tự viết orchestrator framework từ đầu.
Một lưu ý khi chọn engine: Camunda 7 Community Edition đã dừng ở bản 7.24 (10/2025), không còn bản vá; Camunda 8 (engine Zeebe) có hỗ trợ compensation event nhưng mô hình chạy khác hẳn (job worker gọi qua gRPC thay vì delegateExpression chạy trong JVM). Activiti và Flowable vẫn giữ kiểu nhúng vào ứng dụng như ví dụ trên.
# tổng kết
| Aspect | Saga | Distributed Transaction (2PC) |
|---|---|---|
| Consistency | Eventual (BASE) | Strong (ACID) |
| Availability | High | Low (blocking) |
| Performance | Good (async) | Poor (locks) |
| Complexity | Cao hơn (compensation logic) | Thấp hơn (framework lo) |
| Scalability | High | Limited |
| Use case | Microservices | Monolith/tightly-coupled |
Saga là một trade-off: bạn đổi strong consistency lấy availability và scalability, và trả giá bằng việc tự viết compensation.
Nếu sắp tách một luồng nghiệp vụ ra nhiều service, mình sẽ bắt đầu từ một tờ giấy: liệt kê từng step, viết bước bù ngay cạnh nó, rồi hỏi với mỗi bước hai câu. Gọi hai lần thì có sao không? Timeout thì coi là thành công, thất bại hay chưa rõ? Chưa trả lời được hai câu đó thì chưa nên bàn choreography hay orchestration.
Phần gửi event cho an toàn đọc tiếp ở bài transactional outbox và idempotent consumer. Muốn ôn lại ACID trong một database thì xem ACID trong SQL.
Chỉ là những ghi chép cá nhân với hy vọng mang lại chút giá trị. Nếu thấy hữu ích, đừng ngại chia sẻ cho bạn bè & đồng nghiệp nhé!
Happy coding 😎 👍🏻 🚀 🔥.
On this page
- # vấn đề: sao microservices không dùng được acid transaction?
- # saga chạy thế nào
- # hai mô hình: choreography vs orchestration
- # choreography: event-driven, không có người điều phối trung tâm
- # orchestration: có người điều phối trung tâm
- # khi nào dùng cái nào?
- # mấy vấn đề phải xử lý
- # idempotency: "bị trừ tiền 2 lần vì retry"
- # timeout: "saga kẹt mãi không xong"
- # semantic lock: tránh "dirty read" giữa các step của saga
- # saga + bpmn: dùng process engine làm orchestrator
- # tổng kết