7 Proven Solutions to Distributed Transaction Challenges in Microservices
This article explains why distributed transactions are difficult in micro‑service architectures, illustrates the problem with an e‑commerce order example, and presents seven practical solutions—including 2PC, 3PC, TCC, reliable messaging, best‑effort notification, Seata AT, and eBay's event‑queue—along with guidance on selecting the right approach for different consistency and performance requirements.
Introduction
Distributed transaction problems appear frequently in interviews and real work. In a micro‑service architecture a single business operation may span multiple services and databases, making the classic ACID guarantee insufficient. This article introduces seven common solutions.
Why Distributed Transactions Are Tricky
In monolithic apps the database ACID transaction ensures consistency. In micro‑services, an order creation may involve order, inventory, payment and points services, each with its own database. All four operations must either succeed together or fail together, which is the core challenge of distributed transactions.
Common Solutions
2PC (Two‑Phase Commit)
Strong consistency solution. A coordinator asks all participants to prepare; participants lock resources and reply YES/NO. In the commit phase the coordinator sends commit or rollback based on responses.
Drawbacks : synchronous blocking, single‑point coordinator failure, possible data inconsistency under network partitions.
public boolean prepare() {
try {
startTransaction();
executeSql("UPDATE account SET frozen = 100 WHERE id = 1");
return true; // YES
} catch (Exception e) {
rollback();
return false; // NO
}
}3PC (Three‑Phase Commit)
Adds a pre‑commit phase and timeout mechanism to avoid the blocking problem of 2PC.
CanCommit: coordinator asks participants if they can commit (no lock).
PreCommit: participants lock resources and execute SQL but do not commit.
DoCommit: final commit.
Improvements : participants auto‑commit on timeout, early abort in pre‑commit.
Remaining issues : possible inconsistency under network partitions, higher implementation complexity.
TCC (Try‑Confirm‑Cancel)
Final‑consistency pattern that splits business logic into three phases.
Try : reserve resources (e.g., freeze inventory).
Confirm : permanently apply the operation.
Cancel : release reserved resources.
public boolean tryDeductPoints(Long userId, int points) {
UserPoints user = userPointsDao.selectForUpdate(userId);
if (user.getAvailable() < points) {
throw new InsufficientPointsException();
}
userPointsDao.freeze(userId, points);
}
public boolean confirmDeductPoints(Long userId, int points) {
userPointsDao.confirmDeduct(userId, points);
}
public boolean cancelDeductPoints(Long userId, int points) {
userPointsDao.unfreeze(userId, points);
}Advantages : no global lock, high availability.
Challenges : manual rollback logic, each service must expose three interfaces.
Reliable Message (RocketMQ Transaction Message)
Uses half messages that are invisible to consumers until the local transaction succeeds, then commits or rolls back the message.
public void createOrder(Order order) {
Message msg = MessageBuilder.withPayload(order).build();
TransactionSendResult result = rocketMQTemplate.sendMessageInTransaction(
"order_topic", msg, null);
}The broker periodically checks undecided transactions.
Best‑Effort Notification
Weak‑consistency approach suitable for low‑latency‑tolerant scenarios such as SMS alerts. After the main business flow finishes, a notification is sent; on failure it retries with increasing intervals and finally requires manual intervention.
public void notify(String event) {
int retryCount = 0;
while (retryCount < RETRY_INTERVALS.length) {
try {
if (sendNotification(event)) return;
} catch (Exception e) { }
Thread.sleep(RETRY_INTERVALS[retryCount] * 60 * 1000);
retryCount++;
}
alertManualIntervention(event);
}Seata AT Mode
Automated TCC that records undo logs without business‑code intrusion.
Global lock managed by TC.
SQL proxy generates rollback logs.
Two‑phase asynchronous commit improves throughput.
UPDATE product SET stock = stock - 10 WHERE id = 1001;
/* Seata records undo log */
INSERT INTO undo_log (branch_id, xid, before_image, after_image)
VALUES (?, ?, '{"stock":100}', '{"stock":90}');Performance comparison shows AT reduces lock hold time to 1‑10 ms versus 500‑2000 ms for traditional 2PC.
eBay Event Queue
Combines local transaction with an event table to guarantee eventual consistency. A compensating mechanism handles failures.
BEGIN TRANSACTION;
INSERT INTO orders (...);
INSERT INTO event_queue (event_type, payload, status)
VALUES ('ORDER_CREATED', '{"orderId":1001}', 'PENDING');
COMMIT;Solution Selection Guide
2PC/3PC : strong consistency, low performance, medium complexity – suitable for bank core systems.
TCC : eventual consistency, high performance, high complexity – ideal for e‑commerce transactions and points systems.
RocketMQ transaction message : eventual consistency, high performance, medium complexity – fits order creation and logistics notifications.
Best‑effort notification : weak consistency, high performance, low complexity – used for SMS and operational alerts.
Seata AT : eventual consistency, high performance, low complexity – works well for typical micro‑service business.
eBay event queue : eventual consistency, high performance, medium complexity – used for internal state synchronization.
Golden Rules
Strong consistency required : choose 2PC or ZooKeeper, accepting performance cost.
High‑concurrency scenario : choose reliable messaging or Seata AT for eventual consistency.
Weak consistency scenario : best‑effort notification offers the lowest cost.
Conclusion
Over the past decade distributed‑transaction techniques have evolved from strict strong‑consistency protocols to high‑performance eventual‑consistency solutions. The right choice depends on business tolerance for inconsistency, performance requirements, and operational complexity.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
macrozheng
Dedicated to Java tech sharing and dissecting top open-source projects. Topics include Spring Boot, Spring Cloud, Docker, Kubernetes and more. Author’s GitHub project “mall” has 50K+ stars.
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.
