dawdler-distributed-transaction-compensator
Module Introduction
The web-side compensator module of the distributed transaction framework. It consumes and executes the sub-transactions of distributed transaction participants in real time, runs the scheduled compensation mechanism, and releases redis and rabbitmq resources.
1. Adding the dependency to the web-side pom
<groupId>club.dawdler</groupId>
<artifactId>dawdler-distributed-transaction-compensator</artifactId>
2. Configuration file
The compensator loads its configuration from distributed-transaction-compensator.properties on the classpath, and the unified configuration center can override it. Defaults are used when nothing is configured.
# Delay before the scheduled compensator first runs (seconds), default 15
initialDelaySeconds=15
# Interval between runs of the scheduled compensator (seconds), default 15
delaySeconds=15
# Maximum compensation retries; exceeding it moves the branch to the parked state with an alert, default 50
maxRetryTimes=50
# Processing timeout for all branches of a single compensation message (seconds); on timeout the message is dropped and resent by the timer, default 300
processTimeoutSeconds=300
| Configuration item | Description | Default |
|---|---|---|
| initialDelaySeconds | Delay before the compensation timer first runs (seconds) | 15 |
| delaySeconds | Interval between compensation timer runs (seconds) | 15 |
| maxRetryTimes | Maximum compensation retries for a single branch transaction; exceeding it moves the branch to the parked state, outputs an ERROR alert and stops automatic compensation | 50 |
| processTimeoutSeconds | Processing timeout for all branches of a single compensation message (seconds); on timeout the message is dropped and resent by the compensation timer | 300 |
The TTL of the compensation execution fence (
compensationFenceTtlSeconds, default 600) is configured indistributed-transaction.properties(see section 5.2.1 of the main module README) and must be greater thanprocessTimeoutSeconds; otherwise a branch dropped on a processing timeout may be executed twice after the fence expires.
3. Startup behavior
The compensator starts with the web application (WebListener2StartCompensator):
- Validates the Processor SPI registration at startup: when no implementation is registered, an action is duplicated, or a remote service injection fails, an exception is thrown and the deployment is aborted instead of surfacing the problem at the first compensation message;
- When an unavailable redis/rabbitmq makes the consumer or the timer fail to start, an exception is likewise thrown and the deployment aborted, so the application does not go live with incomplete compensation capability; after fixing the problem, restart the application.
4. Compensation behavior
- The compensation timer queries Redis every
delaySecondsfor transactions that have not completed within the transaction timeout and resends MQ messages to trigger confirm/cancel. The query uses a deadline index (a zset, taking only due members withZRANGE ... BYSCORE ... LIMIT); the index is maintained by the writing side, and the compensator has a built-in periodic reconciliation (once every 600 seconds by default, with the first run immediately on call, adjustable viaindexReconcileSecondsindistributed-transaction.properties) that backfills and self-heals it. The transaction timeout defaults todefaultTransactionTimeoutSeconds(seedistributed-transaction.properties, 300 seconds by default, and it must be greater thancompensateLater), and can also be declared per transaction via@DistributedTransaction'stransactionTimeoutSeconds(a sponsor declaration applies to the whole transaction and the timeout is timed uniformly from the sponsor's transaction start time);compensateLateris only the fallback compensation time for legacy branches without adeadline. - Forced rollback of TRYING timeouts: branches stuck in TRYING (e.g. the sponsor crashed before deciding, or persisting the decision still failed after retries) are compensated with CANCEL after the timeout; the decision is written back to storage (consistent with what was actually delivered, so later rounds do not re-evaluate it) and a WARN log tagged
force_cancelis emitted, following the TCC spec to prevent resource suspension. The alert is rate limited by globalTxId (at most once every 60 seconds per transaction) so a long-stuck transaction does not flood every round; the limiter only affects logging - the state still transitions to CANCEL and the compensation message is still delivered. - Retry limit: once a single branch's compensation count reaches
maxRetryTimes, it moves to theparkedstate with an ERROR alert log and is no longer compensated automatically; manual intervention is required, and the record is retained untilexpireTimepasses. - Atomic retry counting: the retry count is stored as a separate branch field (
@retry); both timer delivery and consumer-side execution failures increment it atomically withHINCRBYon the storage side and return the new value, so the timer and the message consumer (or compensators in multiple instances) compensating the same branch concurrently never overwrite each other and no update is lost. - Delivery counts as a retry: before each delivery of a compensation message the timer atomically increments the branch's retry count on the storage side, so the count keeps accumulating even when the message channel is unavailable (broker failure) or the consumer does not process the message (consumer down, queue binding error); on reaching
maxRetryTimesthe branch moves toparkedwith an ERROR alert, so it is never resent indefinitely and flooding logs. - Compensation failures count as retries: a missing processor, an exception thrown from process, process returning false, and a successful compensation whose branch-record deletion fails all count as failures and are atomically incremented on the storage side; when the limit is reached the branch moves to
parkedimmediately. The consumer skips branches that are alreadyparkedor have reached the limit, so duplicate messages never compensate beyond the limit. - Compensation execution fence (fencing): before executing confirm/cancel business logic the consumer must acquire the branch's execution fence (
SET NX PX+ TTL, 600 seconds by default, adjustable viacompensationFenceTtlSecondsindistributed-transaction.properties); when someone else holds it, this delivery is skipped and the timer resends it. Thus at most one compensator executes the business for a branch at any moment - duplicate MQ deliveries, timer resends after a processing-timeout drop, and concurrent duplicate execution across multiple instances are eliminated at the framework level. After acquiring the fence the branch is re-read inside the fence, and a branch already deleted by a concurrent compensation is skipped; while holding it, the lease is renewed every third of the TTL so a long execution no longer loses the mutex when a fixed TTL lapses, and after the business returns one last renewal-and-lease-check happens before any state write-back (delete/count/park) - a lost lease abandons all write-backs and hands the message back to the timer (when storage does not support renewal it degrades to the old behavior with a warning only). The fence is released on completion only by a matching token; when the holder crashes it is released automatically when the TTL expires and does not block later compensations. - Empty-rollback anti-suspension: branches whose initiating RPC wait timed out (try result unknown) carry a
try_unknownmarker; after the business cancel's empty rollback succeeds the branch is not deleted immediately but deferred to a deadline re-check - after the deadline the timer resends it naturally, and it is deleted after a second idempotent compensation round, so a late try committed within the deadline is still cancelled out. A try committed after the deadline is outside the transaction's declared timeout contract (same semantics asforce_cancel) and must be handled by a business tombstone (see "Anti-suspension" in the main module README). - Processing timeout: when all branches of a single compensation message take longer than
processTimeoutSeconds, the consumer logs an ERROR and drops the message (without requeueing it), and the compensation timer resends it at thedelaySecondsrhythm as a fallback. The in-flight execution still holds the branch's fence (the fence TTL is greater than the processing timeout), so a resent compensation skips it because the fence is held and never executes concurrently. - Consumer manual ack: MQ messages are switched to manual acknowledgement (autoAck=false, prefetch=10) and acked only after all branches of the message are processed, so messages not acked when the consumer process crashes are redelivered by the broker and no message is lost. Message-level failures (parse failure / branch load failure / thread pool rejection / processing timeout) drop that message with an ERROR alert and do not requeue it, avoiding a hot loop of poison messages, and the compensation timer resends it at the
delaySecondsrhythm as a fallback. - Multi-instance deployment: the compensator supports deployment in multiple instances; with several instances their timers scan and deliver repeatedly (duplicate delivery is harmless), at most one instance holds the fence and executes the business for a branch at any moment, and concurrent duplicate execution is eliminated at the framework level. Business compensation handling should still remain idempotent (to defend against extreme cases such as a duplicate delivery arriving late after the fence expires).
- Compensation execution depends on
distributed-transaction-redis.propertiesanddistributed-transaction-rabbitmq.properties; for configuration see dawdler-redis-plug and dawdler-rabbitmq-plug.