Skip to main content

dawdler-distributed-transaction

Module Introduction​

The root module of the distributed transaction module.

Architecture and Principles​

A distributed transaction has three business states: trying, confirm, and cancel. After the number of branch compensation attempts reaches the upper limit, the transaction enters the framework's internal parked state (compensation suspended); it is no longer compensated automatically and waits for manual handling (see 5.5).

The sponsor completes a distributed transaction in the following four steps:

  1. Use @DistributedTransaction to mark the sponsor and the participants.
  2. AOP intercepts @DistributedTransaction; the sponsor generates a global transaction id and context.
  3. The sponsor invokes a participant; AOP intercepts the marked participant method, generates a branch transaction id, serializes the trying state and writes it to redis, and then executes the actual business logic. If execution throws an exception, the transaction is marked as rollback and the exception is rethrown.
  4. An exception when invoking a participant, or a custom TransactionInterceptInvoker marking the transaction as cancel, is treated as a rollback: when a participant branch fails, the cancel decision is settled immediately and compensation is notified (if the sponsor process crashes at this point, the global decision is already cancel, and subsequent try registrations will be rejected); finally the sponsor uniformly changes the transaction in redis to confirm or cancel and then executes commit/rollback (sends MQ messages).

Compensator Module​

  1. After consuming the message sent by the sponsor, it executes the corresponding business method (which must be idempotent); on success it deletes the corresponding branch transaction information from redis.
  2. The scheduled compensator periodically scans transactions within a specified time range and handles transactions whose execution failed after MQ consumption (usually caused by a service outage or network failure).

Transaction Modes and Consistency​

This module is a compensatory distributed transaction with eventual consistency. The second phase (confirm/cancel) is not a synchronous callback by the sponsor: the decision is first written to storage, and then executed asynchronously through MQ notifications and the scheduled compensator. When a participant's try method returns, the local transaction has been committed and the effect is immediately visible; rollback depends on the business's second-phase method, and the framework is only responsible for state storage, message notification, and scheduled compensation.

Two Business Implementation Styles for Participants​

How much try actually does is determined by the business; there are two common styles:

  • True execution (used by the examples in this document): try directly deducts the payment and stock; confirm only sets a confirmation flag (e.g. placing the order); cancel compensates in reverse (refund, restore stock).
  • Freeze-based: try only freezes the amount and reserves stock, leaving the balance unchanged; confirm converts the frozen amount into an actual deduction; cancel unfreezes and releases the reserved stock.

Interface definition of the user service in the freeze-based style:

//User service interface definition (freeze-based)
@Service("distributed-transaction-user-service")
public interface UserService {

@DistributedTransaction(action = "user",sponsor = false)//Marks the service as a distributed transaction participant
public boolean tryFreezePayment(Integer userId, BigDecimal amount);//try: freeze the amount without actually deducting it

public boolean doPayment(DistributedTransactionContext context, String status);
//status=confirm: convert the frozen amount into a real deduction
//status=cancel: unfreeze and restore the available balance
}

Comparison of the two styles:

DimensionTrue executionFreeze-based
try semanticsDirectly execute the real businessOnly freeze/reserve resources
Intermediate stateAmount/stock already changed and visible externally until compensation completesOnly a "frozen" record exists; the real balance/stock is unchanged
confirm semanticsMark as confirmed, usually placing the order or doing nothingPost the real entry (consume the frozen amount)
cancel semanticsReverse compensation (refund/restore stock)Unfreeze and release the reservation
Impact of compensation failureThe real business has taken effect and requires manual recoveryOnly a leftover freeze record; the impact is small
Implementation costLow, intuitive for the businessHigh, requires designing freeze fields/reservation records
Applicable scenariosGeneral business where the intermediate state is briefly visibleScenarios sensitive to isolation, such as funds and sellable stock

Selection guidance: use the freeze-based style for scenarios where the intermediate state must not be visible, such as account balances and sellable stock; use the true execution style for scenarios where the intermediate state is briefly visible and can be audited afterwards, such as order status transitions. It is recommended that participants in the same transaction use the same style. Scenarios that require strong consistency semantics can only be avoided through business design; the framework does not provide this capability.

Framework Guarantees and Business Obligations​

Framework guarantees:

  • The sponsor's confirm/cancel decision is persisted to storage before the MQ message is sent. After the business succeeds, if persisting the confirm decision fails, an exception is thrown to the caller instead of returning business success; if the MQ notification for an already-persisted decision fails, only a warning is logged and the scheduled compensator resends according to the stored state. When the business itself fails, exceptions in the cancellation phase do not override the original business exception.
  • An exception from the decision storage call does not mean the decision definitely was not written (for example, the write succeeded but the response was lost). The caller should verify the final decision by the globalTxId in the logs and combine this with business idempotency; the exception must not be treated as "business not executed" to unconditionally re-place orders or re-deduct payments.
  • Real-time MQ notification plus scheduled fallback scanning ensures that transactions are not lost even if a participant is briefly unavailable.
  • For branches whose TRYING state exceeds the deadline, the compensator forcibly rolls back according to CANCEL (logged with the force_cancel marker), so they never hang indefinitely. After a global transaction is marked as cancel, the try methods of subsequent participants are no longer executed and directly throw DistributedTransactionCanceledException (carrying the globalTxId); the sponsor must treat this as "the transaction has been canceled" and must not use the return value of this invocation. This exception class is transmitted over RPC as part of the api package, so both ends need to upgrade the framework package in sync.
  • The compensation fence guarantees that at most one executor runs for the same branch at any moment: the compensator acquires it before executing confirm/cancel business, and a participant's try acquires it before executing the business as well; a late try that collides with an in-progress compensation fails fast as canceled (preventing hanging, see 5.2.1); while held, the lease is renewed at one third of the TTL period, so long executions no longer break mutual exclusion due to a fixed TTL expiring; on renewal failure (lease lost), all state write-backs are abandoned and the scheduled timer re-delivers (degrading to the old behavior when storage does not support renewal); once the failure count (on the consumer side, an increment for each real compensation failure, performed atomically via storage-side increment by the consumer within the fence) exceeds maxRetryTimes, the branch enters parked and is no longer compensated automatically. Scheduled deliveries do not count as failures (they do not consume the real-failure quota; while the channel is unavailable the message keeps being resent and automatically continues after recovery), and the record is retained until branch cleanup, awaiting manual handling.
  • A sponsor-side RPC wait timeout only means giving up waiting; it does not mean the server-side try has stopped: the framework places a try_unknown marker on such branches with "unknown try result", and after a successful empty rollback does not delete the branch immediately but defers it to deadline re-check (after the deadline the scheduled timer naturally re-delivers, and the branch is deleted after a second idempotent compensation), so a try committed late within the deadline is still offset by cancel and never hangs without compensation.

The following is the responsibility of the business:

  • Idempotency: confirm/cancel may arrive multiple times (MQ redelivery, timer resend, multiple compensator instances), so second-phase methods must be idempotent.
  • Empty rollback: the branch record is written to storage before try executes, so cancel is still invoked when try fails; the business's cancel must be able to handle the case where "try did not succeed" (for example, return success directly when there is no corresponding record in the record table).
  • Hanging prevention (the fallback for late-commit protection): after a sponsor-side RPC timeout the framework defers the branch to deadline re-check, but a try committed after the deadline exceeds the timeout contract declared by the transaction (consistent with the force_cancel semantics). For business where "late commits are unacceptable", the cancel empty rollback must write a cancellation tombstone in the same local transaction, and the try must check the tombstone in the same local transaction before committing and refuse to commit.
  • Compensation completeness: cancel must fully offset the effects of try, including the ledgers and details written during the try phase.
  • No global lock: two global transactions may modify the same row of data at the same time; hot rows need to be isolated through business means (freeze-based style, optimistic locking, or row locking).
  • Irreversible operations must not be performed in try (shipping, sending external SMS, calling third-party deductions, etc.); cancel cannot roll back such operations.

1. Submodule Introduction​

dawdler-distributed-transaction-core distributed transaction core module

dawdler-distributed-transaction-api distributed transaction common classes and annotation module

dawdler-distributed-transaction-compensator compensator module

2. Adding Dependencies to the Web-side pom​

<groupId>club.dawdler</groupId>
<artifactId>dawdler-distributed-transaction-core</artifactId>

3. Adding Dependencies to the Dawdler Server-side pom​

<groupId>club.dawdler</groupId>
<artifactId>dawdler-distributed-transaction-core</artifactId>

4. Adding Dependencies to the Web-side Compensator Module's pom​

<groupId>club.dawdler</groupId>
<artifactId>dawdler-distributed-transaction-compensator</artifactId>

5. Usage​

5.1 Configuring the Distributed Transaction​

Define the services according to the business; the web interface acts as the sponsor and the service interfaces act as participants.

The participants in the examples in this document use the true execution style (try directly deducts the payment and stock, and cancel compensates in reverse). For the difference between the two styles, see Transaction Modes and Consistency.

Take placing an order as an example, involving 3 services in total (see the example for details):

5.1.1 Order Service​

Define the interface in the api layer

//Order service interface definition
@Service("distributed-transaction-order-service")
public interface OrderService {

@DistributedTransaction(action = "order",sponsor = false)//Marks the service as a distributed transaction participant
public boolean createOrder(Integer userId, Integer productId, BigDecimal amount);

public boolean updateStatusOrder(DistributedTransactionContext context, String status);
}
5.1.2 User Service​

Define the interface in the api layer

//User service interface definition
@Service("distributed-transaction-user-service")
public interface UserService {
@DistributedTransaction(action = "user",sponsor = false)//Marks the service as a distributed transaction participant
public Map<String, Object> tryPayment(Integer userId,BigDecimal amount);

public boolean doPayment(DistributedTransactionContext context, String status);
}

5.1.3 Product Stock Service​

Define the interface in the api layer

//Product stock service interface definition
@Service("distributed-transaction-product-service")
public interface ProductService {

@DistributedTransaction(action = "product",sponsor = false)//Marks the service as a distributed transaction participant
public Map<String, Object> tryDeductStock(Integer productId, Integer stock);

public boolean doDeductStock(DistributedTransactionContext context,String status);

}
5.1.4 The Web Interface for Placing Orders​

Declare the sponsor on the web interface (the framework also supports placing the sponsor on the server side and having the server side call multiple services, but this is generally not recommended).

@RequestMapping(value = "/order")
@Controller
public class OrderController {
@RemoteService
UserService userService;//Inject the user service

@RemoteService
OrderService orderService;//Inject the order service

@RemoteService
ProductService productService;//Inject the product stock service

@DistributedTransaction(action = "createOrder",sponsor = true)//Marks the distributed transaction sponsor
@RequestMapping(value = "/createOrder.do", viewType = ViewType.json)
@ResponseBody
public Map<String, Object> createOrder(@RequestParam Integer productId, @RequestParam Integer stock,
@RequestParam BigDecimal amount) throws Exception {
int userId = 1;//Define a user id
Map<String, Object> result;
boolean success = orderService.createOrder(userId, productId, amount);//Call the order creation service
if(!success) {
result = new HashMap<>();
result.put("success", false);
result.put("msg", "Order creation failed!");
return result;
}
result = userService.tryPayment(userId, amount);//Deduct the user's amount
success = (boolean) result.get("success");
if(!success) {
return result;
}

result = productService.tryDeductStock(productId, stock);//Deduct the stock
return result;
}
}

5.2 Configuring redis​

redis is used to store transaction states, so that transaction states can still be queried after an unexpected service crash or shutdown.

When the sponsor is on the web side, place distributed-transaction-redis.properties in the web-side classpath.

When the sponsor is on the server side (also supported, but generally not recommended), place distributed-transaction-redis.properties in the dawdler server-side classpath.

For redis configuration, refer to dawdler-redis-plug

Note: the participant's branch context (including method input arguments) is serialized and stored in redis. If the input arguments contain sensitive information (phone numbers, ID numbers, keys, etc.), it is also persisted there; therefore redis access control and network isolation must be properly set up, and sensitive fields should be masked beforehand if necessary.

When multiple applications share one redis instance, the keyPrefix in distributed-transaction.properties (default gtid_) can be used to isolate the transaction keys of each application; the sponsor and the compensator must use the same keyPrefix.

5.2.1 Storage Structure and Concurrency Safety in redis​

Each global transaction corresponds to a hash whose key is gtid_<globalTxId>. The fields in the hash fall into three categories:

Field nameValueDescription
@decisiontrying/confirm/cancelGlobal decision. Atomically created as trying when the transaction starts; confirm/cancel is a one-way, irreversible transition, and no branches can be registered once the decision is settled
<branchTxId>Serialized contextBranch context, including parameters, deadline, etc.; written only once when the branch is registered
<branchTxId>@statustrying/confirm/cancel/parkedCurrent branch status; when read, it is displayed according to the decision if the global decision has already been made (except parked)
<branchTxId>@retryNumberBranch retry count, atomically incremented via HINCRBY on a real compensation failure on the consumer side

The status and retry count are stored in separate fields rather than written into the serialized context because the sponsor and compensator modify them concurrently: with separate storage, both sides only write their own status fields, the retry count is atomically incremented via HINCRBY, and they do not overwrite each other.

The hash expiration time depends on @decision: while the global decision is still trying or there are in-flight branches (including parked), the hash never expires (PERSIST); when the decision has been settled and all branches have been compensated (only the @decision field remains), it is retained as a tombstone for a period according to expireTime before expiring, providing an observation window for late reads and writes.

All write operations are executed atomically in a single Lua script: when creating/updating a branch, the context HSET, the status field HSET, and the @retry HSETNX initialization are completed together (registration is only allowed while the global decision is trying, branches cannot be duplicated, and registering after the decision has been made reports an error directly); when the decision is settled, @decision transitions one-way from trying to confirm/cancel (re-entering with the same direction is idempotent, and the opposite direction is rejected directly); single-branch status transitions are conditional updates (a branch that does not exist is not revived, parked is not overwritten, and directions conflicting with the global decision are not written); when deleting a branch, companion fields such as @status/@retry are cleaned up together, and once all branches are deleted the hash enters the tombstone retention period. On reads, a single hgetAll is executed, and then the status, retry, and global decision fields are merged back into the context to ensure that a single read sees a view of a single moment in time. If the decision field is missing or unrecognizable, reads and writes all fail closed by throwing an exception and requiring manual intervention, never inferring the global result from old branch states.

Besides the hash, the writer also maintains a deadline index (zset):

  • The key is <keyPrefix>deadline_index (default gtid_deadline_index) and it never expires;
  • The member is <globalTxId>:<branchTxId>, and the score is the moment at which the branch can be compensated = deadline (when greater than 0) or addtime + compensateLater (compensateLater is determined by the writer side, i.e. the sponsor side, configuration);
  • Scheduled compensation uses ZRANGE ... BYSCORE ... LIMIT to fetch only due branches, instead of scanning the whole database and then HGETALL on each key;
  • For compatibility with redis cluster (multi-key Lua fails across slots), hash writes and index registration are two independent commands, and if the process crashes between them the registration is missed. Therefore the compensator is configured with periodic reconciliation (default once every 600 seconds, executed immediately on the process's first invocation, adjustable via indexReconcileSeconds in distributed-transaction.properties), which re-scans the whole database to fill in the missing index entries and cleans up deleted/parked members. Reconciliation only handles branch transaction hashes; non-hash keys such as the index key (zset) and fence keys (string) are all skipped; an error on a single key only skips that key and does not affect the current round; a reconciliation failure does not affect due delivery based on the existing index.

Compensation execution fence (fencing, preventing the same branch from being executed concurrently and repeatedly): each branch corresponds to an independent String key <keyPrefix>fence_<globalTxId>:<branchTxId> (default gtid_fence_...), whose value is a random token and which carries a TTL (default 600 seconds, adjustable via compensationFenceTtlSeconds in distributed-transaction.properties). There are two parties that hold the fence:

  • Compensator (consumer side): before executing confirm/cancel business, it first acquires the fence via SET NX PX: if it is already held, another compensator is processing this branch, so this delivery is skipped and waits for the timer to resend; after a successful acquisition it re-reads the branch and skips directly if it has already been deleted by concurrent compensation; while held, it renews the lease to storage at one third of the TTL period (a probe renewal being rejected is treated as a lost lease, abandoning this delivery to the timer for re-delivery; when storage does not support renewal it degrades to the old behavior with a single WARN), and after the business returns and before any state write-back (deletion/counting/parking) it performs a final renewal, i.e. a lost-lease check; if the lease is lost, all write-backs are abandoned to prevent interleaving with a new holder; after execution it releases by verifying the token, and if the holder crashes the fence naturally expires with the TTL.
  • Participant's try (sponsor-side aspect): after branch registration, it also acquires the fence before executing the try business, mutually excluding with the compensator to prevent hanging; if the global decision is settled only after registration (e.g. forced cancellation by a timer timeout) while compensation is in progress, a late try must not write business data; if it cannot acquire (the fence is held by the compensator), it fails fast as canceled through the branch failure path; if the acquisition call itself fails (e.g. a redis glitch), it likewise does not execute the business and finishes as canceled; after try execution it releases by token in a finally block, and if the sponsor process crashes the fence naturally expires with the TTL without hanging the mutual exclusion.

compensationFenceTtlSeconds must be greater than the compensator's processTimeoutSeconds (default 300), otherwise a branch whose processing timed out and was discarded may be executed again after the fence expires; it is also recommended to be no smaller than the branch's maximum transactionTimeoutSeconds, otherwise a slow try is still executing while the fence expires first, and the compensator will concurrently enter and execute cancel (the sponsor side outputs a WARN when it detects this configuration combination).

When implementing TransactionRepository yourself (see 5.7), the same concurrency-safety semantics must be guaranteed: conditional status updates, atomic retry-count increments, and a compensation fence with NX+TTL that is released by token. The sponsor, the compensation timer, and the message consumer concurrently read and write the same batch of records.

5.3 Configuring rabbitmq​

MQ is used to notify transaction participants in real time to invoke the corresponding services. The configuration file is distributed-transaction-rabbitmq.properties.

For rabbitmq configuration, refer to dawdler-rabbitmq-plug

5.4 Configuring the Transaction Compensator​

Create a new project and add the compensator module dependency; the compensator starts on the web side. It both consumes rabbitmq messages to invoke the corresponding services and supports periodically reading unfinished transactions from redis for supplementary processing.

Both the redis and rabbitmq configurations are placed in the transaction manager's classpath; refer to the redis and rabbitmq configurations above (note: the compensator's redis and rabbitmq configurations must be consistent with those of the sponsor).

When the compensator starts, it validates the SPI registration of Processors (throw an exception if not registered, if an action is duplicated, or if remote service injection fails); if redis/rabbitmq being unavailable prevents the consumer or timer from starting, it also throws an exception directly to stop the deployment from continuing, avoiding going live with incomplete compensation capability (restart the application after fixing the problem).

The compensator supports multi-instance deployment: with multiple instances, each instance's timer scans and delivers repeatedly (duplicate delivery has no effect), and at most one instance at any moment holds the compensation fence to execute business for the same branch (see 5.2.1); after the holder crashes the fence is automatically released with the TTL. The fence only prevents concurrent duplicate execution; business compensation is still recommended to remain idempotent.

The compensator's own tuning parameters are configured in distributed-transaction-compensator.properties, including the timer's initial delay, execution interval, maximum retry count, processing timeout for a single compensation message, etc.; see dawdler-distributed-transaction-compensator for details.

5.4.1 Configuring Processors​

A Processor is the handler of a distributed transaction participant.

A participant's Processor extends DistributedTransactionCustomProcessor.

Processor for the user service:

public class UserCompensator extends DistributedTransactionCustomProcessor {
@RemoteService //Inject the user service
UserService userService;
public UserCompensator() {
super("user");//Define the Processor alias, which corresponds to the action in the DistributedTransaction annotation
}

@Override
public boolean process(DistributedTransactionContext context, String status) {
return userService.doPayment(context, status);//Call the corresponding service
}
}

Processor for the product stock service:

public class ProductCompensator extends DistributedTransactionCustomProcessor {
@RemoteService
ProductService productService;
public ProductCompensator() {
super("product");
}

@Override
public boolean process(DistributedTransactionContext context, String status) {
return productService.doDeductStock(context, status);
}
}

Processor for the order service:

public class OrderCompensator extends DistributedTransactionCustomProcessor {
@RemoteService
OrderService orderService;
public OrderCompensator() {
super("order");
}

@Override
public boolean process(DistributedTransactionContext context, String status) {
return orderService.updateStatusOrder(context, status);
}
}

These processors are injected via SPI; the contents of the META-INF/services/club.dawdler.distributed.transaction.compensate.process.DistributedTransactionCustomProcessor file are as follows:

com.anywide.shop.compensator.OrderCompensator
com.anywide.shop.compensator.ProductCompensator
com.anywide.shop.compensator.UserCompensator

5.5 Configuration of Retention Time and Delayed Processing Time for Failed Distributed Transactions​

Retention time:

Configure distributed-transaction.properties in the sponsor module's classpath to set the retention time.

expireTime=259200 #Number of seconds to retain the completed-decision tombstone and the empty-sponsor hash; default 259200 seconds = 3 days if not configured. Transactions with in-flight branches (including parked) never expire.

Configure distributed-transaction.properties in the compensator module's classpath to set the delayed processing time.

deadline is persisted when the branch is written, and the compensator's timer runs every 15 seconds (adjustable via delaySeconds in distributed-transaction-compensator.properties); according to the deadline index, it only delivers branches that have become due, so it does not compensate immediately upon expiry. compensateLater is now only used in fallback scenarios: for branches in old data that have no deadline, the compensation time is calculated as addtime + compensateLater.

compensateLater=60 #Fallback compensation time for legacy branches without a deadline (addtime+compensateLater seconds); default 60 seconds if not configured; must be less than defaultTransactionTimeoutSeconds.
defaultTransactionTimeoutSeconds=300 #Global default timeout in seconds used when a transaction does not declare a timeout; default 300 seconds if not configured; must be greater than compensateLater.

For branches stuck in TRYING (for example, the sponsor crashed before deciding), the compensator forcibly rolls back according to the global decision as CANCEL after the timeout, conforming to the TCC specification and preventing resource hanging; a WARN is output in the log with the force_cancel marker. Once the compensation count of a single branch reaches the upper limit (default 50, adjustable via maxRetryTimes), the branch enters parked and an ERROR is logged; it is no longer compensated automatically and requires manual intervention; the hash also does not expire due to the in-flight parked branch. The count only counts real consumer-side compensation failures (the consumer atomically increments @retry on the storage side within the fence); scheduled deliveries do not count; while the channel is unavailable the timer keeps resending wake-up messages, automatically continues after the channel recovers, and never lets a branch exceed the parking limit prematurely.

The sponsor's confirm/cancel decision is persisted to storage before the MQ message is sent: after the business succeeds, if persisting the confirm decision fails, an exception is thrown to the caller; if the business itself fails, the original business exception is preserved. If the MQ notification for an already-persisted decision fails, only a warning is logged and the scheduled compensator resends according to the stored state. A storage call exception may mean the decision result is uncertain; the caller must verify the final decision and ensure business idempotency, and should not unconditionally redo the business.

5.5.1 Declaring a Timeout per Transaction​

defaultTransactionTimeoutSeconds is the global default transaction timeout. Long transactions whose execution time may exceed this value (e.g. batch processing, slow calls) can declare a larger timeout individually on the annotation, avoiding being forcibly rolled back before try finishes:

@DistributedTransaction(action = "createOrder", sponsor = true, transactionTimeoutSeconds = 300)

A timeout declared by the sponsor applies to all branches of the entire transaction; one declared by a participant only takes effect when the sponsor has not declared one; when neither declares one, defaultTransactionTimeoutSeconds is used (default 300 seconds).

Timing is calculated uniformly based on the sponsor transaction's start time: each branch's deadline = sponsor transaction start time + the effective timeout in seconds, so that all branches of the same transaction expire at the same time and are forcibly rolled back as a whole.

5.5.2 Resolving Compensator Parameter Names​

A participant branch's input arguments are stored in redis along with the branch context in the form of "parameter name -> parameter value"; after try completes and compensation occurs, the business obtains them via context.getDatas().get("<parameter name>"). Parameter names are resolved by the following priority:

  1. When compiled with -parameters, the declared name provided by Parameter#isNamePresent is used (interface methods are equally applicable);
  2. Otherwise, the LocalVariableTable in the bytecode is read (compilation must carry debug information -g, which is satisfied by Maven's default debug=true; and the type must be loaded by a class loader that is component-scanned, WebComponentInjector/ServiceInjector are preloaded by default).

When neither is available, the framework outputs a distributed_transaction_parameter_names_unavailable WARN log, and the branch's parameter names degrade to arg0/arg1, so a business lookup by the real parameter name only yields null. In this case, enable -parameters for the module that compiles this type, or ensure that debug information is retained.

5.6 Customizing Rollback Settings Based on Response Results​

The framework rolls back the entire transaction when invoking a participant throws an exception. Special requirements can be extended via TransactionInterceptInvokerHolder. For example, the order placement flow:

Create order -> deduct amount -> deduct stock

When the amount-deducting or stock-deducting service throws an exception, the entire transaction is rolled back; if it is due to insufficient stock (rollback can also be triggered by throwing an exception), the user's amount needs to be refunded and the user notified.

Set a TransactionInterceptInvoker via TransactionInterceptInvokerHolder to intercept the execution result of the distributed transaction and decide whether to roll back based on the business-defined return value.

Custom TransactionInterceptInvoker code:

@Override
public void contextInitialized(ServletContext arg0) {
TransactionInterceptInvokerHolder.setTransactionInterceptInvoker(new TransactionInterceptInvoker() {
@Override
public Object invoke(ProceedingJoinPoint invocation, DistributedTransactionContext tc) throws Throwable {
Object result = invocation.proceed();//Get the return result of the service call
if(result instanceof Map) {
Map resultMap = (Map) result;
Boolean success = (Boolean)resultMap.get("success");
if(success==null || !success) {//Set the transaction to roll back if it failed
tc.setCancel(true);
}
}
return result;
}
});
}

Concrete implementation of the invoked product stock service:

@Override
@DBTransaction
public Map<String, Object> tryDeductStock(Integer productId, Integer stock) {
Map<String, Object> resultMap = new HashMap<>();
Product product = new Product();
product.setProductId(productId);
product.setStock(stock);
int result = productMapper.deductStockByPrimaryKey(product);
if(result == 0) {
resultMap.put("success", false);//Set this as a call failure
resultMap.put("msg", "Insufficient stock!");//Set the specific reason
return resultMap;
}
//...The code for persisting the detail records below is omitted; refer to the concrete distributed transaction example if needed
return resultMap;
}

5.7 Customizing Transaction Storage and Message Sending (SPI Extension)​

Transaction state storage (TransactionRepository) and transaction message sending (MessageSender) are both plugged in via SPI (java.util.ServiceLoader); redis and rabbitmq implementations are provided by default and are already registered via SPI in the framework jar:

  • Storage: RedisRepository, reads distributed-transaction-redis.properties;
  • Message sending: AMQPSender, reads distributed-transaction-rabbitmq.properties.

If a custom SPI implementation is present in the classpath, the custom implementation is used; otherwise, the default implementations above are used. To switch to other storage (e.g. a relational database) or another message middleware (e.g. kafka), just implement the corresponding interface and register it via SPI.

5.7.1 Customizing Transaction Storage​

Extend club.dawdler.distributed.transaction.repository.TransactionRepository and provide a public no-argument constructor:

public class JdbcTransactionRepository extends TransactionRepository {
public JdbcTransactionRepository() {
// Initialize the data source and serializer (the serializer field)
}

@Override
public int create(DistributedTransactionContext transaction) throws Exception {
// ...
}
// Other abstract method implementations are omitted...
}

Create a file META-INF/services/club.dawdler.distributed.transaction.repository.TransactionRepository in the classpath, containing the fully qualified name of the implementation class:

com.anywide.shop.tx.JdbcTransactionRepository

A custom implementation must follow the same concurrency-safety semantics as RedisRepository; the sponsor, the compensation timer, and the message consumer concurrently read and write the same branch, and the following method contracts must not be violated:

MethodConcurrency contract
beginGlobalTransactionAtomically create a brand-new global transaction id and persist the trying decision; if it already exists, an error must be raised and rejected (it must not be reused); the base class throws UnsupportedOperationException by default
decideGlobalTransactionAtomically decide trying to confirm/cancel, one-way and irreversible, idempotent when re-entered in the same direction, returning the effective global decision (i.e. the "winner"); branch registration must be closed after the decision; the base class throws UnsupportedOperationException by default
getGlobalDecisionReturn trying/confirm/cancel; throw an exception when the decision is missing or unknown (fail closed), and never infer from branch states; the base class throws UnsupportedOperationException by default
incrementRetryTimeAtomically increment on the storage side and return the new value (e.g. redis's HINCRBY); it must not be implemented as read-modify-write, otherwise concurrent increments lose updates; return 0 (not counted) when the branch does not exist, is already parked, or its state is inconsistent with the global decision. Parking is determined solely by this count, and it is only called on a real consumer-side compensation failure (scheduled deliveries are not counted)
updateStatusByBranchTxIdConditional update: a branch that does not exist must not be created (revived), a branch currently parked must not be overwritten, and a direction conflicting with the global decision must not be written
findBranchByBranchTxIdReturn null when the branch does not exist (already deleted by compensation); when reading a branch, the global decision must be presented (except parked)
acquireCompensationFence/releaseCompensationFenceNX+TTL acquisition and token-matched release, single-key atomic operations (cluster compatible); holders are the compensator (before executing confirm/cancel business) and the participant's try (before executing business in the sponsor-side aspect, to prevent hanging); the fence TTL must be greater than the compensator's processTimeoutSeconds and is recommended to be no smaller than the branch's maximum transactionTimeoutSeconds
renewCompensationFenceRenew the TTL by token while held; return true = still held, false = lease lost (token mismatch/fence already lost); throw UnsupportedOperationException when renewal is not supported, and the consumer side degrades to the old behavior (writing back as usual without renewal), with residual concurrency risk covered by business idempotency
markTryOutcomeUnknownPlace a marker when sponsor-side RPC waiting times out (unknown try result) (write only if present, idempotent); after a successful consumer-side empty rollback, the branch deletion is deferred to deadline re-check based on it; return false when the branch does not exist; throw UnsupportedOperationException when not supported, and the consumer side degrades to the old behavior (delete immediately), with the hanging-prevention window retained but queryable in logs
updateUsed only to persist business context; the status and retry count must not be written back as a whole through it (which would overwrite the atomic operations above)
5.7.2 Customizing Message Sending​

Implement club.dawdler.distributed.transaction.message.MessageSender and provide a public no-argument constructor:

public class KafkaMessageSender implements MessageSender {
public KafkaMessageSender() {
// Initialize the kafka producer
}

@Override
public void send(String msg) {
// Send to the custom message middleware; the queue name can use MessageSender.QUEUE_NAME
}
}

Create a file META-INF/services/club.dawdler.distributed.transaction.message.MessageSender in the classpath, containing the fully qualified name of the implementation class:

com.anywide.shop.tx.KafkaMessageSender

Note: the sponsor and the compensator each load implementations via SPI on their own side, so a custom implementation must be found in both classpaths, and the storage and message middleware configurations on both sides must point to the same environment. When multiple SPI implementations are registered, the framework takes the first one and outputs a warning.

send must throw an exception on failure (with a clear reason) and must not silently swallow it: the sponsor side records the reason and the compensation timer resends; initialization failures should also be thrown there, rather than returning an instance that is bound to fail later. The default AMQPSender follows this contract; initialization failures are not cached permanently, and sending can continue without a restart once the message middleware recovers.