Method and related device for orchestration and compensation of distributed transactions

CN122924923APending Publication Date: 2026-10-16CTRIP COMP TECH SHANGHAI
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611281290.0
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-21
Publication Date
2026-10-16

AI Technical Summary

Technical Problem

[0004]本申请提供一种分布式事务的编排与补偿方法及相关装置,能够解决分布式事务中并行分支补偿容易遗漏或误操作的问题中的至少一部分

Benefits of technology

本申请通过将TCC事务的控制信息前置到流程定义元数据中,结合统一委托节点的动态路由机制,将TCC事务的编排逻辑从业务代码硬编码升级为流程定义可配置,降低TCC事务在并行多服务场景下的开发和维护成本。通过分支事务台账的持久化存储与已执行Try分支集合的动态构建,使得通用Confirm/Cancel节点能够基于实际执行结果精确驱动补偿操作,该集合驱动机制有效解决并行TCC场景下哪些分支需要Confirm、哪些需要Cancel的难题,避免传统实现中依赖业务方自行维护执行清单所导致的遗漏补偿或误补偿问题。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122924923A_ABST
    Figure CN122924923A_ABST
Patent Text Reader

Abstract

The application provides a distributed transaction arrangement and compensation method and related device. The arrangement and compensation method comprises: generating a transaction identifier and a business identifier and writing into a flow variable, initializing a transaction state; configuring an extension field containing a participant identifier and a branch identifier in each Try branch, parsing and routing the Try by a unified delegation node; recording a request response, a stage, a state, a retry number and a timestamp for each Try branch, forming a branch ledger; triggering multiple Try branches in parallel, querying the ledger or an engine history to obtain a set of Try branches that have been successfully executed; entering a Confirm path when all key Try branches are successful, executing Confirm by a general Confirm node traversing the set; entering a Cancel path when any Try branch fails, times out or decision is not satisfied, executing Cancel by a general Cancel node traversing the set. The application realizes accurate compensation in a parallel TCC scene through a ledger-driven general compensation mechanism, avoids missing compensation or false compensation, and ensures consistency and recoverability of the distributed transaction.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of microservices technology, and more specifically, to a method and apparatus for orchestrating and compensating distributed transactions. Background Technology

[0002] Distributed transactions are a core technical challenge in microservice architectures. The TCC (Try, Confirm, Cancel) pattern ensures eventual consistency across services through a three-phase operation. However, existing TCC implementations suffer from several shortcomings: First, the Try, Confirm, and Cancel operations of each participant are typically hard-coded into the business logic, resulting in fragmented and unintuitive execution paths. When business logic changes, the calling logic of each participant must be modified individually, leading to high maintenance costs. Second, in parallel processing scenarios, determining which branches require Confirm and Cancel operations after multiple Try branches execute concurrently often relies on the business side maintaining its own execution status list, which can easily result in missed or duplicate compensation. Third, exception recovery mechanisms (such as retries and dead-letter handling) are independent of business state management, lacking a unified state tracking and recovery linkage mechanism, making it difficult to accurately restore the state when the process is interrupted. Fourth, inconsistent handling strategies for idempotency, null rollback, and anti-hanging issues among participants can easily lead to duplicate commits or erroneous rollbacks, resulting in data inconsistency. Currently, there is a lack of a standardized technical solution that deeply integrates workflow orchestration capabilities with TCC transaction processing and can uniformly manage parallel branch compensation.

[0003] It should be noted that the information disclosed in the background section above is only used to enhance the understanding of the background of this application, and therefore may include information that does not constitute prior art known to those skilled in the art. Summary of the Invention

[0004] This application provides a method and related apparatus for orchestrating and compensating distributed transactions, which can solve at least part of the problem of easy omission or misoperation in parallel branch compensation in distributed transactions.

[0005] According to one aspect of this application, a method for orchestrating and compensating distributed transactions is provided, comprising: generating a global transaction identifier xid and a business identifier bizId; writing the global transaction identifier xid and the business identifier bizId into a process variable before starting a process instance, and initializing the global transaction state to TRYING in a global transaction table; configuring an extended field containing at least a participant identifier (participant) and a branch identifier (branchId) in each Try branch; during execution, a unified delegation node parses the extended field and routes the execution of the Try branch to the corresponding participant based on the participant identifier (participant); and recording request messages, response messages, current stage, state, number of retries, error information, and timestamps for each Try branch, forming a system with the global transaction identifier xid and the branch identifier (branchId) as the identifiers. `branchId` is the branch transaction ledger at the joint dimension. Multiple Try branches are concurrently triggered after the parallel gateway. The set of successfully executed Try branches is obtained by querying records with a successful stage status in the branch transaction ledger or by querying historical activity instances in the workflow engine. When the decision condition is met and all key Try branches are successful, the system enters the Confirm path. The general Confirm node iterates through the successfully executed Try branch set and calls the Confirm operation of the corresponding participant. When any key Try branch fails, times out, or is missing from the successfully executed Try branch set, the system enters the Cancel path. The general Cancel node iterates through the successfully executed Try branch set and calls the Cancel operation of the corresponding participant.

[0006] In some embodiments, the method further includes unified state machine protection, which includes idempotent replay, empty rollback, and anti-hanging; the idempotent replay means that when the branch state is already CONFIRM_SUCCESS or CANCEL_SUCCESS, the corresponding request that arrives repeatedly directly returns the historical response result; the empty rollback means that when a Cancel request is received but there is no TRY_SUCCESS record in the branch ledger, the branch state is marked as EMPTY_CANCEL, and no actual Cancel call is executed; the anti-hanging means that when the branch state is already CANCEL_SUCCESS and a Try request arrives subsequently, the execution of the Try branch is rejected and the branch state is marked as HANGING_REJECTED.

[0007] In some embodiments, the extended field further includes attribute information for identifying whether a branch is a critical branch; the decision condition is: if all Try branches marked as critical branches exist in the set of successfully executed Try branches, the path is confirmed; otherwise, the path is canceled.

[0008] In some embodiments, the general Confirm node traverses the set of successfully executed Try branches and calls the Confirm operation of the corresponding participant one by one; the general Cancel node traverses the set of successfully executed Try branches in reverse order of the order in which each Try branch was executed or in a preset order and calls the Cancel operation of the corresponding participant one by one.

[0009] In some embodiments, the method further includes: the Try branch, Confirm node, and Cancel node are executed asynchronously and a retry strategy is configured; when the number of retries is exhausted, the task enters the dead letter queue; the operation and maintenance module supports querying dead letter tasks by process instance and moving dead letter tasks back to the executable queue for re-execution; during the recovery process, the branch transaction ledger and the global transaction status are updated synchronously.

[0010] In some embodiments, the way to query historical activity instances of the workflow engine is to filter by process instance ID (processInstanceId), activity ID (activityId), and completion status (finished) to construct a set of Try branches that have been successfully executed.

[0011] In some embodiments, the extended fields further include a payload variable and a failedJobRetryTimeCycle; the unified delegation node obtains business input parameters based on the payload variable and performs node-level retry control based on the failedJobRetryTimeCycle.

[0012] In some embodiments, the information recorded in the global transaction table includes: global transaction identifier xid, business identifier bizId, global transaction status and creation timestamp; the global transaction status includes at least TRYING, CONFIRMED, and CANCELED.

[0013] According to another aspect of this application, a distributed transaction orchestration and compensation system is provided to implement the distributed transaction orchestration and compensation method according to any of the above embodiments. The system includes: a process initiation module, used to generate a global transaction identifier xid and a business identifier bizId, write the global transaction identifier xid and the business identifier bizId into a process variable before starting a process instance, and initialize the global transaction state to TRYING in a global transaction table; a metadata parsing and routing module, used to configure extended fields containing at least a participant identifier (participant) and a branch identifier (branchId) in each Try branch, wherein during execution, a unified delegation node parses the extended fields and routes the Try branch to the corresponding participant based on the participant identifier (participant); and a transaction storage module, used to record request messages, response messages, current stage, status, retry count, error information, and other data for each Try branch. The system uses timestamps to create a branch transaction ledger with a global transaction identifier (xid) and a branch identifier (branchId) as the joint dimensions. A parallel triggering and status acquisition module is used to concurrently trigger the execution of multiple Try branches after the parallel gateway. It obtains the set of successfully executed Try branches by querying records with a successful stage status in the branch transaction ledger or by querying historical activity instances of the workflow engine. A general compensation module is used to enter the Confirm path when all key Try branches succeed, where the general Confirm node iterates through the set of successfully executed Try branches and calls the Confirm operation of the corresponding participant. When any key Try branch fails, times out, or is missing from the set of successfully executed Try branches, the system enters the Cancel path, where the general Cancel node iterates through the set of successfully executed Try branches and calls the Cancel operation of the corresponding participant.

[0014] In some embodiments, the general compensation module is further configured to perform unified state machine protection, which includes idempotent replay, empty rollback, and anti-hanging; the idempotent replay is to repeat the request and directly return the historical response when the Confirm or Cancel operation is successfully executed; the empty rollback is to mark the Cancel request as an empty rollback when no Try branch is successfully executed; the anti-hanging is to reject the execution of the Try branch and mark it as anti-hanging when a Try request arrives after the Cancel operation is executed.

[0015] According to another aspect of this application, an electronic device is provided, comprising: a processor; a memory storing executable instructions; wherein, when the executable instructions are executed by the processor, they implement the distributed transaction orchestration and compensation method according to any of the above embodiments.

[0016] According to another aspect of this application, a computer-readable storage medium is provided for storing a program that, when executed by a processor, implements the distributed transaction orchestration and compensation method according to any of the above embodiments.

[0017] According to another aspect of this application, a computer program product is provided, including a computer program that, when executed by a processor, implements the distributed transaction orchestration and compensation method according to any of the above embodiments.

[0018] The advantages of this application compared to the prior art may include: This application upgrades the orchestration logic of TCC transactions from hard-coded business code to configurable process definition by forwarding the control information of TCC transactions into the process definition metadata and combining it with the dynamic routing mechanism of unified delegate nodes. This reduces the development and maintenance costs of TCC transactions in parallel multi-service scenarios. Through persistent storage of branch transaction ledgers and dynamic construction of executed Try branch sets, the general Confirm / Cancel nodes can accurately drive compensation operations based on actual execution results. This set-driven mechanism effectively solves the problem of determining which branches need to be Confirmed and which need to be Canceled in parallel TCC scenarios, avoiding the omission or miscompensation problems caused by relying on the business side to maintain the execution list itself in traditional implementations.

[0019] It should be understood that the above general description and the following detailed description are exemplary and explanatory only, and do not limit this application. Attached Figure Description

[0020] The accompanying drawings, which are incorporated in and form part of this specification, illustrate embodiments consistent with this application and, together with the description, serve to explain the principles of this application. It is obvious that the drawings described below are merely some embodiments of this application, and those skilled in the art can obtain other drawings based on these drawings without any inventive effort.

[0021] Figure 1 A schematic diagram illustrating the steps of the distributed transaction orchestration and compensation method provided in this application embodiment; Figure 2 A schematic diagram of unified state machine protection in the distributed transaction orchestration and compensation method provided in the embodiments of this application; Figure 3 A schematic diagram illustrating the steps of a distributed transaction orchestration and compensation method provided in another embodiment of this application; Figure 4 A schematic diagram of the modules of the distributed transaction orchestration and compensation system provided in the embodiments of this application; Figure 5A schematic diagram illustrating a specific implementation example of the distributed transaction orchestration and compensation method provided in this application embodiment; Figure 6 This is a schematic diagram of the structure of an electronic device provided in an embodiment of this application. Detailed Implementation

[0022] Exemplary embodiments will now be described more fully with reference to the accompanying drawings. However, these exemplary embodiments can be implemented in many forms and should not be construed as limited to those described herein. Rather, these embodiments are provided to make this application more comprehensive and complete, and to fully convey the concept of the exemplary embodiments to those skilled in the art.

[0023] The accompanying drawings are merely illustrative of this application. The same reference numerals denote the same or similar parts, and therefore, repeated descriptions of them will be omitted. Some block diagrams shown in the drawings are functional entities and do not necessarily correspond to physically or logically independent entities. These functional entities can be implemented in software, in one or more hardware modules or integrated circuits, or in different network and / or processor devices and / or microcontroller devices. The processes shown in the drawings are merely illustrative and do not necessarily include all steps. For example, some steps can be decomposed, some steps can be combined or partially combined, and the actual execution order may change depending on the actual situation.

[0024] It should be noted that, unless otherwise specified, the embodiments of this application and the features in different embodiments can be combined with each other. All other embodiments obtained by those skilled in the art based on the embodiments of this application without inventive effort are within the scope of protection of this application.

[0025] Reference Figure 1 As shown in the embodiments of this application, the distributed transaction orchestration and compensation method may include the following steps.

[0026] S110, generate global transaction identifier xid and business identifier bizId, write global transaction identifier xid and business identifier bizId into process variables before starting process instance, and initialize global transaction status to TRYING in global transaction table.

[0027] The `xid` (global transaction identifier) ​​uniquely identifies a complete distributed transaction, spanning the Try, Confirm, and Cancel phases. It is the core index that links the global transaction table and the branch transaction table. The `bizId` (business identifier) ​​is a unique identifier at the business level, such as an order number or transaction serial number. It is used to associate distributed transactions with specific business scenarios, facilitating business-level queries, auditing, and problem localization.

[0028] Through the global transaction initialization steps (generating xid and bizId, writing them to process variables, and initializing the state to TRYING), a global transaction identifier xid is generated as a unique identifier for this distributed transaction, ensuring that the transaction can be uniquely traced at each stage of its lifecycle, including execution, compensation, and querying. A business identifier bizId is generated to associate the distributed transaction with specific business functions (such as orders or transactions), facilitating business-level queries and problem localization. Furthermore, before starting the process instance, xid and bizId are written to the workflow engine's process variables, allowing each node in the process definition to share the transaction context without explicitly passing the transaction identifier between service calls. The global transaction state is initialized to TRYING, marking that the transaction has entered the Try phase and providing a global state basis for subsequent decisions.

[0029] S120: Each Try branch is configured with an extended field that includes at least the participant identifier and the branch identifier. During execution, the unified delegation node parses the extended field and routes the Try branch to the corresponding participant based on the participant identifier.

[0030] A Try branch refers to the execution unit of the Try phase for each participant in a distributed transaction. Each Try branch corresponds to an independent service call (such as inventory locking, account freezing, or order creation), and is the basic granularity for transaction ledger recording and compensation operations. The participant identifier identifies the participating service in the distributed transaction (such as inventory service, account service, or order service). The framework routes to the corresponding service's Try / Confirm / Cancel implementation based on this identifier. The branchId is a unique identifier for each Try branch, typically generated by combining the participant identifier and the business identifier (such as inv_ORDER-123456), used to uniquely distinguish different branches within the global transaction.

[0031] By using metadata-driven Try execution steps (configuring participant and branchId extended fields, and unified delegation node parsing and routing), the participant and branchId are configured in the extended fields of the service nodes in the process definition. This decouples the routing information of Try branches from business logic. When adding participants or adjusting routes, only the process definition configuration needs to be modified without changing the business code, thus achieving configurable TCC (Try-Confirm-Cancel) transaction orchestration. Furthermore, the unified delegation node, as the unified entry point of the framework layer, parses the metadata in the extended fields and dynamically routes to the corresponding participant's Try implementation based on the participant, shielding the differences in service interfaces among participants and decoupling the process definition from the specific service implementation.

[0032] S130 records the request message, response message, current stage, status, number of retries, error message and timestamp for each Try branch, forming a branch transaction ledger with the global transaction identifier xid and the branch identifier branchId as the joint dimension.

[0033] By persisting the branch transaction log (recording request messages, response messages, stages, statuses, retry counts, error messages, and timestamps), a complete branch transaction log is established for each Try branch, forming a full execution record at the xid+branchId dimension. The log includes request messages (recording call parameters for easy problem reproduction and auditing), response messages (recording call results for confirming execution status), current stage (TRY / CONFIRM / CANCEL, marking the TCC stage the branch is in), status (marking the execution result status of the branch), retry counts (recording failure retry history to avoid infinite retries), error messages (recording the reasons for failure for easy problem localization), and timestamps (recording time nodes for each stage for performance analysis and timeout assessment). Furthermore, the persistent storage of the log provides a unified data foundation for subsequent queries of executed branch sets, decision-making, idempotent replay, empty rollback, anti-hanging, and anomaly recovery.

[0034] S140: After concurrently triggering the execution of multiple Try branches behind the parallel gateway, obtain the set of successfully executed Try branches by querying records with a successful stage status in the branch transaction log, or by querying historical activity instances of the workflow engine. Alternatively, after concurrently triggering the execution of multiple Try branches behind the parallel gateway, obtain the set of successfully executed Try branches by querying records with a successful stage status in the branch transaction log, or by querying historical activity instances of the workflow engine and confirming the TRY_SUCCESS status in conjunction with the branch transaction log.

[0035] By constructing a set of Try branches (concurrently triggering multiple Try branches and querying the ledger or historical activity instances to obtain a successful set), multiple Try branches are concurrently triggered after the parallel gateway. This fully leverages the parallel capabilities of the workflow engine to shorten the overall transaction processing time. The Try operations of each participant are executed in parallel, and the total time is approximately equal to the longest-running single Try branch, rather than the sum of the times of all branches. Furthermore, by querying records with a successful stage status in the branch transaction ledger or querying historical activity instances of the workflow engine, the set of successfully executed Try branches is dynamically obtained. This set serves as the basis for subsequent general Confirm or Cancel operations, ensuring that compensation operations only apply to branches that have actually been successfully executed, avoiding omissions (such as forgetting to compensate a successful branch) or erroneous operations (such as performing confirmation or cancellation on branches that have not been executed).

[0036] S150: When the decision conditions are met and all key Try branches succeed, the system enters the Confirm path, where the general Confirm node iterates through the set of successfully executed Try branches and calls the Confirm operation of the corresponding participant. When any key Try branch fails, times out, or is missing any key Try branch from the set of successfully executed Try branches, the system enters the Cancel path, where the general Cancel node iterates through the set of successfully executed Try branches and calls the Cancel operation of the corresponding participant.

[0037] The Confirm operation is a confirmation operation following a successful Try phase, converting a pre-operation (such as pre-deducting inventory or freezing funds) into a permanent, effective operation. The Cancel operation is a rollback operation when the Try phase fails or the transaction is cancelled, undoing the results of the pre-operation and releasing the occupied resources.

[0038] Through a generic Confirm / Cancel decision-making and execution process (determining the path based on the success status of key branches, with generic nodes traversing the set and calling the corresponding participants), the decision-making layer decides whether to enter the Confirm or Cancel path based on whether all key Try branches have succeeded. If all key branches succeed, the Confirm path is entered; if any key branch fails or times out, the Cancel path is entered. This decision-making mechanism ensures the atomicity of transactions is correctly guaranteed. Generic Confirm and Cancel nodes serve as unified compensation execution units at the framework layer, driving compensation operations based on the set of successfully executed Try branches, rather than implementing Confirm / Cancel orchestration logic separately for each participant. When the number of parallel Try branches changes dynamically, the compensation path does not require adding or modifying dedicated code; only the branch set in the ledger needs to be automatically adapted. Furthermore, the Confirm operation only confirms successfully executed Try branches, and the Cancel operation only cancels successfully executed Try branches. Both share the same executed set as input, ensuring that the coverage of confirmation and cancellation is completely consistent and accurate, neither omitting branches that need compensation nor mistakenly operating on unexecuted branches.

[0039] Therefore, this application upgrades the orchestration logic of TCC transactions from hard-coded business code to configurable process definition by forwarding the control information of TCC transactions into the process definition metadata and combining it with the dynamic routing mechanism of the unified delegate node. This reduces the development and maintenance costs of TCC transactions in parallel multi-service scenarios. Through the persistent storage of branch transaction ledgers and the dynamic construction of executed Try branch sets, the general Confirm / Cancel nodes can accurately drive compensation operations based on actual execution results. This set-driven mechanism effectively solves the problem of which branches need to be Confirmed and which need to be Canceled in parallel TCC scenarios, avoiding the omission or miscompensation problems caused by the reliance on the business side to maintain the execution list in traditional implementations.

[0040] Reference Figure 2 As shown, in some embodiments, the orchestration and compensation method for distributed transactions further includes unified state machine protection, which includes idempotent replay, null rollback, and anti-hanging. Idempotent replay means that when the branch state is already CONFIRM_SUCCESS or CANCEL_SUCCESS, duplicate requests directly return the historical response result. Null rollback means that when a Cancel request is received because there is no TRY_SUCCESS record in the branch ledger, the branch state is marked as EMPTY_CANCEL, and no actual Cancel call is executed. Anti-hanging means that when the branch state is already CANCEL_SUCCESS and a Try request subsequently arrives, the execution of the Try branch is rejected, and the branch state is marked as HANGING_REJECTED.

[0041] In this context, `TRY_INIT` represents the initial state of the Try branch, indicating that the branch has been created but the Try operation has not yet started. `TRY_SUCCESS` indicates that the Try branch has executed successfully, meaning the pre-operation (such as pre-deducting inventory or freezing funds) has been completed, and the branch is eligible to be Confirmed or Canceled. `TRY_FAILED` indicates that the Try branch has failed, meaning the pre-operation was unsuccessful, and the branch should not execute the Confirm operation. `CONFIRM_SUCCESS` indicates that the Confirm operation has executed successfully, meaning the pre-operation has become permanent, and the branch transaction has been finally confirmed. `CANCEL_SUCCESS` indicates that the Cancel operation has executed successfully, meaning the pre-operation has been undone, and the branch transaction has been rolled back. `EMPTY_CANCEL` is an empty rollback flag, indicating that the branch did not execute the Try (or the Try failed) but received a Cancel request; the state machine marks this state and ignores the Cancel request. `HANGING_REJECTED` is a flag to prevent hanging transactions, indicating that the branch has successfully Canceled but received a Try request; the state machine rejects the Try request to prevent hanging transactions. Idempotent replay ensures idempotency by directly returning the historical response result when the same request (Confirm or Cancel) arrives repeatedly, since the branch status is already CONFIRM_SUCCESS or CANCEL_SUCCESS, without repeating the business operation. Empty rollback occurs when a Cancel request is received before or after the Try phase has been executed. It only marks the status without actually invoking the Cancel operation of the participating parties, avoiding meaningless undoing of pre-operations that have not yet taken effect. Hanging prevention prevents data inconsistency caused by hanging transactions. If a Try request arrives after a Cancel operation has been successfully executed (due to network latency or other reasons), the Try request is rejected to prevent the reactivation of the undone transaction.

[0042] The seven branch states mentioned above cover the entire lifecycle of a TCC transaction branch from creation to final state, including the Try phase (TRY_INIT, TRY_SUCCESS, TRY_FAILED), the Confirm phase (CONFIRM_SUCCESS), the Cancel phase (CANCEL_SUCCESS), and the exception protection states (EMPTY_CANCEL, HANGING_REJECTED). The comprehensive state definition provides the branch transaction ledger with precise state recording capabilities, ensuring that each branch's current TCC phase and execution result can be clearly tracked. Furthermore, the state definition incorporates two exception protection states (EMPTY_CANCEL, HANGING_REJECTED), integrating distributed exception scenarios that traditionally require individual participants to handle into the framework's unified state management system, enabling exceptions to be recorded and audited.

[0043] By leveraging the idempotent replay rule (returning historical responses for duplicate requests when the branch status is already CONFIRM_SUCCESS or CANCEL_SUCCESS), when the same Confirm or Cancel request arrives repeatedly (potentially due to client retries caused by network timeouts, duplicate message consumption, etc.), the state machine directly returns the historical response result without calling the participating service again. This rule ensures the idempotency of operations at the framework level, avoids duplicate deductions (such as duplicate payments) caused by duplicate Confirms or business anomalies (such as duplicate inventory releases) caused by duplicate Cancels, and reduces the risk of duplicate execution in a distributed environment.

[0044] By utilizing the empty rollback rule (marking a Cancel request as EMPTY_CANCEL when there is no TRY_SUCCESS record), when a Cancel request is received even though there is no TRY_SUCCESS record in the branch ledger (i.e., the Try was not executed or failed), possibly due to a global Cancel triggered by a timeout or the Try request arriving out of order, the state machine marks the branch as EMPTY_CANCEL without actually invoking the Cancel operation of the participating party. This rule ensures that the Cancel operation only applies to branches where the Try has been successfully executed, avoiding meaningless undo operations when the Try failed (such as releasing never-locked inventory or unfreezing never-frozen funds). Simultaneously, the EMPTY_CANCEL status records this abnormal scenario for subsequent auditing and investigation.

[0045] By utilizing the anti-hanging rule (rejecting and marking subsequent Try requests as HANGING_REJECTED when a branch is already in CANCEL_SUCCESS), if a Try request arrives after the branch is already in CANCEL_SUCCESS (due to network latency causing the Try request to arrive after Cancel), the state machine rejects the Try execution and marks the branch state as HANGING_REJECTED. This rule prevents Try operations of canceled transactions from being activated by subsequent executions, avoiding the hanging transaction problem where the entire transaction has been rolled back but a participant's resources are still being relocked.

[0046] Therefore, by using a branch state machine to uniformly implement the three key protection capabilities in distributed transactions—idempotent replay, empty rollback, and anti-hanging—at the framework layer, each participant does not need to implement these protection logic independently. This reduces development complexity and avoids the risk of inconsistencies caused by different implementations by each participant, thereby improving the stability of TCC transactions in distributed abnormal scenarios.

[0047] In some embodiments, the extended field also includes attribute information for identifying whether a branch is a critical branch; the decision condition is: if all Try branches marked as critical branches exist in the set of successfully executed Try branches, proceed to the Confirm path; otherwise, proceed to the Cancel path.

[0048] A critical branch is a Try branch marked as critical by attribute information in an extended field. The success or failure of a critical branch directly determines the direction of the global transaction. If all critical branches succeed, the transaction proceeds to the Confirm path; if any critical branch fails, the transaction proceeds to the Cancel path. The failure of non-critical branches (such as auxiliary operations like points rewards or marketing campaigns) does not affect the final decision of the global transaction.

[0049] By extending the critical branch identifier attribute in the field, different Try branches can have different transaction weights. The success or failure of critical branches (such as core business operations like inventory deduction, fund deduction, and order generation) determines the final outcome of the transaction, while the failure of non-critical branches (such as auxiliary operations like points awarding, log recording, and marketing activities) does not affect the main transaction decision. This supports flexible degradation handling in flexible transaction scenarios, allowing some non-critical branches to fail while the main transaction can still be successfully committed, improving the system's fault tolerance and availability while ensuring the consistency of core business operations.

[0050] In some embodiments, the general Confirm node traverses the set of successfully executed Try branches and calls the Confirm operation of the corresponding participant one by one; the general Cancel node traverses the set of successfully executed Try branches in reverse order of the order in which the Try branches were executed or in a preset order and calls the Cancel operation of the corresponding participant one by one.

[0051] Reverse order refers to executing the Cancel operation in the reverse order of the successful execution order of each Try branch. For example, if the successful execution order of Try branches is A→B→C, then the reverse order Cancel is C→B→A. Reverse order Cancel is usually used to avoid resource dependency conflicts. If B's ​​Try depends on A's resources, then when canceling, B's resources should be released first, followed by A's resources. Preset order refers to the Cancel execution order specified by the user in advance. It is suitable for scenarios where there are clear requirements for the rollback order in the business (such as releasing the database connection first, then the distributed lock, and finally the memory cache).

[0052] The generic Confirm node iterates through the set of successfully executed Try branches and calls the Confirm operation one by one, ensuring that each successful Try branch is correctly confirmed without omission. The generic Cancel node iterates through the set in reverse order or a preset order and calls the Cancel operation one by one. Reverse-order Cancel avoids resource dependency conflicts. When resources have dependencies (such as B's Try depending on A's locking result), reverse-order release can prevent exceptions caused by improper release order, while preset Cancel supports customized rollback order by the business logic. In addition, the sequential compensation mode of calling each branch one by one ensures the stability and traceability of the compensation operation and avoids resource contention and state chaos that may be caused by parallel compensation.

[0053] In some embodiments, the orchestration and compensation method for distributed transactions further includes: the Try branch, Confirm node, and Cancel node are executed asynchronously and configured with a retry strategy; when the number of retries is exhausted, the task enters the dead letter queue; the operation and maintenance module supports querying dead letter tasks by process instance and moving the dead letter tasks back to the executable queue for re-execution; during the recovery process, the branch transaction ledger and the global transaction status are updated synchronously.

[0054] Asynchronous execution refers to the asynchronous execution of Try, Confirm, and Cancel nodes within the workflow engine. This means that node execution does not block the main workflow thread, and the execution result is obtained through callbacks or polling. Retry strategy refers to the automatic retry configuration (such as maximum number of retries, retry interval, etc.) after node execution failure, used to handle temporary faults (such as network jitter or temporary service unavailability). Dead letter queue refers to the queue of tasks that have failed to execute after exhausting their retries, awaiting intervention from operations personnel. Task retrieval refers to the operation of moving tasks from the dead letter queue back to the executable queue for re-execution, used to restart transaction progress after fault recovery.

[0055] By employing asynchronous execution and configuring automatic retry strategies through the Try, Confirm, and Cancel nodes, the framework automatically retryes tasks that fail due to temporary faults such as network jitter or service unavailability, enabling recovery without manual intervention and improving the system's self-healing capabilities in the face of transient failures. When the number of retries is exhausted, the task enters a dead-letter queue, avoiding the waste of system resources caused by infinite retries. The operations module supports querying dead-letter tasks by process instance and moving them back to the executable queue for re-execution, providing a standardized operation interface for manual intervention and resolving recovery issues in severe fault scenarios (such as database crashes or data anomalies) that require manual handling. Furthermore, by synchronously updating the branch transaction ledger and global transaction status during the recovery process, the process state on the process engine side is ensured to be consistent with the transaction state on the business side, avoiding inconsistencies caused by state fragmentation, such as the process deeming a success when the business has not actually taken effect, or the process deeming a failure when the business has actually taken effect.

[0056] Therefore, referring to Figure 3 As shown, the orchestration and compensation method for distributed transactions, after step S150, may further include: S160, unified state machine protection, including idempotent replay, empty rollback, and anti-hanging; S170, retry, dead letter, and recovery linkage, including asynchronous execution, entering the dead letter queue after retry exhaustion, operation and maintenance recovery, and synchronous updating of branch transaction ledger and global transaction status during the recovery process. Therefore, this application achieves idempotent replay, empty rollback, and anti-hanging at the framework layer through unified state machine protection, significantly reducing the risks of duplicate execution, erroneous rollback, and suspended transactions; it enhances transaction anomaly recovery capabilities and full-process observability through the linkage between the branch transaction ledger and the workflow engine's retry and dead letter recovery capabilities; it reduces the complexity of manual compensation by providing dead letter query, recovery, and retry control through the operation and maintenance recovery module; and it allows for the integration of new participants through process configuration and participant route registration, reducing business code modification and improving system scalability.

[0057] In some embodiments, the way to query historical activity instances of the workflow engine is as follows: filter by process instance identifier (processInstanceId), activity identifier (activityId), completion status (finished), and business success mark to construct a set of successfully executed Try branches; or, after querying historical activity instances, confirm by combining the TRY_SUCCESS status of the corresponding branch in the branch transaction ledger, and only include branches with a ledger status of TRY_SUCCESS into the set of successfully executed Try branches.

[0058] `processInstanceId` is a unique identifier for each process instance in the workflow engine, corresponding to a single distributed transaction execution. `activityId` is a unique identifier for each activity node (such as a service task or gateway) in the workflow engine. `finished` is used to filter completed node records in the workflow's historical activity instances.

[0059] By filtering historical activity instances of the workflow engine based on process instance ID (processInstanceId), activity ID (activityId), and completion status (finished), this approach provides an alternative to branch transaction ledger queries for constructing a set of successfully executed Try branches. This method leverages the workflow engine's own historical record capabilities, allowing for accurate acquisition of the executed node set even in extreme scenarios where ledger data is incomplete (e.g., queries before ledger records are stored or data loss due to faults). This improves system fault tolerance and data acquisition reliability, and can also serve as a backup or verification method for branch ledger queries.

[0060] In some embodiments, the extended fields also include a payload variable and a failedJobRetryTimeCycle; the unified delegate node obtains the business input parameters based on the payload variable and performs node-level retry control based on the failedJobRetryTimeCycle.

[0061] `payloadVariable` is the name of the variable that stores business input parameters in the process variables. The unified delegation node uses this variable name to retrieve specific business parameters (such as order amount, product quantity, user ID, etc.) from the process context and passes them to the participating service. `failedJobRetryTimeCycle` is a retry strategy parameter configured in the node's extended fields, defining the number of retries and the retry interval after a node execution failure.

[0062] The payloadVariable in the extended fields allows business input parameters for the Try branch to be dynamically obtained through process variables, eliminating the need to hardcode business parameters in the process definition. The same process definition can be reused for different business instances, with each instance passing different parameters through the process variable. The failedJobRetryTimeCycle strategy supports fine-grained configuration of the number of retries and the retry interval at the node level. Different nodes can be configured with differentiated strategies based on their business characteristics (e.g., more retries can be configured for idempotent services, while fewer retries can be configured for non-idempotent services), improving the flexibility of the retry mechanism and the efficiency of resource utilization.

[0063] In some embodiments, the information recorded in the global transaction table includes: global transaction identifier xid, business identifier bizId, global transaction status and creation timestamp; the global transaction status includes at least TRYING, CONFIRMED, and CANCELED.

[0064] The global transaction table records information such as xid, bizId, global transaction status, and creation timestamp, providing complete lifecycle management capabilities for global transactions. The xid allows association with all branch ledger records, the bizId supports business-level transaction queries and auditing, the global transaction status (TRYING, CONFIRMED, CANCELED) clearly marks the current stage of the transaction, and the creation timestamp supports timeout detection and performance analysis. The TRYING, CONFIRMED, and CANCELED states cover the entire process of a TCC transaction from initiation to completion, and the linkage mechanism between the global and branch states ensures consistency between the overall transaction and its branches.

[0065] This application also provides a distributed transaction orchestration and compensation system, which can be used to implement the distributed transaction orchestration and compensation methods described in any of the above embodiments. The features and principles of the distributed transaction orchestration and compensation methods described in any of the above embodiments can be applied to the following distributed transaction orchestration and compensation system embodiments. In the following embodiments, the features and principles already explained will not be repeated.

[0066] Reference Figure 4As shown in the embodiments of this application, the distributed transaction orchestration and compensation system 300 may include: a process initiation module 310, used to generate a global transaction identifier xid and a business identifier bizId, write the global transaction identifier xid and the business identifier bizId into the process variable before starting the process instance, and initialize the global transaction state to TRYING in the global transaction table; a metadata parsing and routing module 320, used to configure an extended field containing at least a participant identifier and a branch identifier branchId in each Try branch, and during execution, the unified delegation node parses the extended field and routes the Try branch to the corresponding participant based on the participant identifier; and a transaction storage module 330, used to record the request message, response message, current stage, status, retry count, error information, and timestamp for each Try branch, forming a system with the global transaction identifier xid as the identifier. The branch transaction ledger is a joint dimension with the branch identifier branchId; the parallel triggering and status acquisition module 340 is used to concurrently trigger the execution of multiple Try branches after the parallel gateway. It obtains the set of successfully executed Try branches by querying records with a successful stage status in the branch transaction ledger or querying historical activity instances of the workflow engine; the general compensation module 350 is used to enter the Confirm path when the decision conditions are met and all key Try branches are successful. The general Confirm node traverses and calls the Confirm operation of the corresponding participant according to the set of successfully executed Try branches; when any key Try branch fails, times out, or any key Try branch is missing from the set of successfully executed Try branches, it enters the Cancel path. The general Cancel node traverses and calls the Cancel operation of the corresponding participant according to the set of successfully executed Try branches.

[0067] Furthermore, the distributed transaction orchestration and compensation system may also include: a decision module, used to determine whether to enter the Confirm or Cancel path based on the branch status; and an operation and maintenance recovery module, used to provide dead letter query, retrieval, retry control, and audit logs.

[0068] This application upgrades the orchestration logic of TCC transactions from hard-coded business code to configurable process definition by forwarding the control information of TCC transactions into the process definition metadata and combining it with the dynamic routing mechanism of unified delegate nodes. This reduces the development and maintenance costs of TCC transactions in parallel multi-service scenarios. Through persistent storage of branch transaction ledgers and dynamic construction of executed Try branch sets, the general Confirm / Cancel nodes can accurately drive compensation operations based on actual execution results. This set-driven mechanism effectively solves the problem of determining which branches need to be Confirmed and which need to be Canceled in parallel TCC scenarios, avoiding the omission or miscompensation problems caused by relying on the business side to maintain the execution list itself in traditional implementations.

[0069] In some embodiments, the general compensation module 350 is also used to perform unified state machine protection, which includes idempotent replay, empty rollback, and anti-hanging; idempotent replay is to repeat the request and directly return the historical response when the Confirm or Cancel operation is successfully executed; empty rollback is to mark the Cancel request as empty rollback when no Try branch is successfully executed; anti-hanging is to reject the execution of the Try branch and mark it as anti-hanging when the Try request arrives after the Cancel operation is executed.

[0070] Idempotent replay ensures that duplicate requests do not produce side effects, null rollback ensures that unsuccessful tries are not invalidally undone, and anti-hanging ensures that canceled transactions are not reactivated. These three protection mechanisms are uniformly implemented by the framework and apply to all participants, avoiding the inconsistency risks of decentralized implementations by various participants and reducing the complexity for developers in handling distributed exception scenarios.

[0071] The following is combined with Figure 5 This describes a specific implementation of the present application.

[0072] The distributed transaction orchestration and compensation system proposed in this application is built on a workflow engine and mainly includes the following core components: Workflow Engine: Provides basic capabilities such as process definition parsing, process instance management, parallel gateway and exclusive gateway scheduling, historical activity instance querying, asynchronous task execution and retry, and dead-letter queue management. The workflow engine in this application can adopt open-source workflow engines such as Activiti and Camunda or a self-developed workflow engine. Process Definition (BPMN): Defines the TCC transaction execution process in a visual way, including node elements such as start event, Try service task, parallel gateway, exclusive gateway, general Confirm service task, general Cancel service task, and end event. Each service task node stores TCC control information (participant, branchId, payloadVariable, critical attribute, etc.) through extended fields. Unified Delegate Node: As the unified service task implementation of the framework layer, it is responsible for parsing the TCC metadata in the node extended fields, executing the corresponding TCC operation according to the stage parameters (TRY / CONFIRM / CANCEL), and completing the persistence of the branch ledger. Transaction storage: Maintains a global transaction table (recording xid, bizId, global status, and creation timestamp) and a branch transaction table (recording xid, branchId, participant, request message, response message, stage, status, retry count, error message, and timestamp). Operations and recovery module: Provides operations and maintenance interfaces such as dead-letter task query, task retrieval, retry control, and audit logs.

[0073] The following example illustrates a typical e-commerce ordering scenario, involving five stakeholders: inventory, account, order, points, and marketing (this is for illustrative purposes only and does not limit the scope of protection in this application).

[0074] S410, Process Definition and Node Configuration.

[0075] Define the BPMN process: Start → Parallel Gateway → [Inventory Try, Account Try, Order Try, Points Try, Marketing Try] → Exclusive Gateway → (All key Trys successful? Confirm link: Cancel link) → End. The configurations for each Try service node are as follows: Inventory Try node: participant=inventory, branchId=inv_${bizId}, payloadVariable=inventoryPayload, critical=true; Account Try node: participant=account, branchId=acc_${bizId}, payloadVariable=accountPayload, critical=true; Order Try node: participant=order, branchId=ord_${bizId}, payloadVariable=orderPayload, critical=true; Points Try node: participant=points, branchId=pts_${bizId}, payloadVariable=pointsPayload, critical=false; Marketing Try node: participant=promotion, branchId=pro_${bizId}, payloadVariable=promotionPayload, critical=false. The generic Confirm and generic Cancel nodes reuse the unified delegate node, and the execution mode is distinguished only by the stage parameter (CONFIRM / CANCEL).

[0076] S420, Global Transaction Initialization.

[0077] When a business application initiates a distributed transaction request, the system generates a global transaction identifier xid (e.g., GTX-20260816-001) and a business identifier bizId (e.g., ORDER-123456). Before starting the workflow process instance, the xid and bizId are written to the process variables, enabling all nodes in the process definition to access the transaction context information. Simultaneously, a record is inserted into the global transaction table: {xid:GTX-20260816-001,bizId:ORDER-123456,status:TRYING,createTime:2026-08-16,10:00:00}.

[0078] S430, Try branch parallel execution and ledger recording.

[0079] When the workflow engine reaches the parallel gateway, it concurrently triggers the execution of five Try branches. Each Try branch is handled by a unified delegation node, and the execution flow is as follows: a. Parse the extended fields of the current service task node to extract metadata such as participant, branchId, and payloadVariable; b. Obtain the business input parameters corresponding to payloadVariable from the process variables; c. Call the Try interface of the corresponding participant through service routing (such as service registration and discovery, RPC call) based on the participant; d. Record the Try execution result in the branch transaction ledger, including request message, response message, stage (TRY), status (TRY_SUCCESS or TRY_FAILED), number of retries (0), error message (if any), and timestamp. The ledger is stored using xid and branchId as a composite primary key.

[0080] Assume the execution results are as follows: Inventory Try: Success, ledger status TRY_SUCCESS; Account Try: Success, ledger status TRY_SUCCESS; Order Try: Success, ledger status TRY_SUCCESS; Points Try: Failure (timeout), ledger status TRY_FAILED; Marketing Try: Success, ledger status TRY_SUCCESS.

[0081] S440, Try branch set construction has been executed.

[0082] After all Try branches have been executed, the process enters the decision-making phase before the exclusive gateway. The system obtains the set of successfully executed Try branches using one of the following two methods: Method 1 (Ledger Query): Query the branch transaction ledger, filtering by xid=GTX-20260816-001 AND phase=TRY AND status=TRY_SUCCESS, to obtain the set of successfully executed Try branches. In this example, the query result is: {Inventory Try, Account Try, Order Try, Marketing Try}. Method 2 (Historical Query): Query historical activity instances of the workflow engine, filtering by process instance identifier (processInstanceId), activity identifier (activityId), completion status (finished), and business success marker, to construct the set of successfully executed Try branches; or, after retrieving historical activity instances, confirm by combining the TRY_SUCCESS status of the corresponding branch in the branch transaction ledger, only including branches with a ledger status of TRY_SUCCESS in the set of successfully executed Try branches. This method serves as a backup in extreme scenarios where ledger data is incomplete.

[0083] S450, Decision Making and Path Selection.

[0084] The decision module determines whether to proceed to the Confirm or Cancel path based on the success status of critical branches: a. Check if all Try branches (inventory, account, order) marked with critical=true exist in the set of successfully executed Try branches. b. In this example, all three critical branches succeeded, satisfying the condition for all critical Try successes, and proceed to the Confirm path. c. If the inventory Try fails (insufficient inventory), it proceeds to the Cancel path due to the missing critical branch. For points and marketing Try branches, since critical=false, their failure does not affect the global decision, supporting flexible degradation for non-core operations. For non-critical branches with TRY_FAILED, they are not included in the set of successfully executed Try branches, and neither Confirm nor Cancel is executed; their failure status is retained in the branch transaction log for auditing, and empty rollbacks and anti-hanging are still handled according to the unified state machine rules.

[0085] S460, General Confirm / Cancel Execution.

[0086] Confirm Path Execution (Example): a. The general Confirm node receives the set of successfully executed Try branches as input and iterates through each branch in the set. b. For each branch, based on the participant, it routes to the corresponding participant's Confirm interface to execute the Confirm operation: Inventory Confirm converts pre-deducted inventory to actual deduction, Account Confirm converts frozen balance to expenditure, Order Confirm changes the order status from "Pending Confirmation" to "Confirmed," and Marketing Confirm verifies coupon benefits. c. After each branch Confirm execution, the status of the corresponding record in the branch ledger is updated to CONFIRM_SUCCESS. d. After confirming that all branch Confirms have been successfully completed, the global transaction status is updated to CONFIRMED. e. Since the Points Try failed to execute and is not in the executed set, Points Confirm is not executed, which is in line with business expectations; no confirmation is needed for a failed Try. At the same time, the Points branch with TRY_FAILED does not execute Cancel, and its failure status is retained in the branch transaction ledger for auditing.

[0087] Cancel path execution (hypothetical scenario: insufficient inventory, entering Cancel): a. The general Cancel node receives the set of successfully executed Try branches (including account, order, and marketing Try branches, but excluding inventory Try branches) as input. b. Traverse the set in reverse order of the order in which the Try branches were successfully executed, or in a preset order: Marketing Cancel (first successful, last cancelled), Order Cancel, Account Cancel. c. For each branch, execute the Cancel operation according to the participant's route to the corresponding participant's Cancel interface: Marketing Cancel rolls back coupon benefits, Order Cancel changes the order status to "cancelled", Account Cancel unfreezes frozen funds. d. Inventory Try branches that were not successfully executed are not in the set, so inventory Cancel is not executed to avoid invalid release operations on unlocked inventory. e. After each branch Cancel is executed, update the status of the corresponding record in the branch ledger to CANCEL_SUCCESS. f. After confirming that all Cancel operations have been successfully completed, update the global transaction status to CANCELED.

[0088] S470, Implementation method of unified state machine protection.

[0089] During branch state transitions, before executing operations at each stage, the unified delegation node first checks the current branch state: a. Idempotent replay protection: When the branch state is CONFIRM_SUCCESS, duplicate Confirm requests directly return historical response results; when the branch state is CANCEL_SUCCESS, duplicate Cancel requests directly return historical response results. This avoids duplicate calls to participant services and prevents business side effects caused by repeated execution. b. Empty rollback protection: When there is no TRY_SUCCESS record in the branch ledger (e.g., branch state is TRY_INIT or TRY_FAILED), a received Cancel request is marked as EMPTY_CANCEL, and the participant's Cancel interface is not actually called. This solution avoids invalid undoing operations when a Try attempt fails. c. Hanging protection: When the branch state is CANCEL_SUCCESS, subsequent Try requests are rejected, and the branch state is marked as HANGING_REJECTED. This solution prevents delayed activation of Try operations for cancelled transactions, avoiding hanging transaction issues.

[0090] S480, anomaly recovery and maintenance.

[0091] Automatic Retry Recovery: Try, Confirm, and Cancel nodes are configured for asynchronous execution in the process definition, with node-level retry policies configured (e.g., a maximum of 3 retries and a 5-second retry interval). When a node fails, the workflow engine automatically retryes according to the configured policy. If the retry is successful, the process continues; if it still fails after all retries have been exhausted, the task enters the dead-letter queue. Manual Retrieval Recovery: Operations personnel can use the management interface of the operations module to query dead-letter tasks by process instance identifier and check the error information in the branch ledger to locate the cause of the failure. After troubleshooting and resolving the problem (e.g., repairing database connections, handling data anomalies), the dead-letter task is moved back from the dead-letter queue to the executable queue through the operations interface, triggering re-execution. During the recovery process, the workflow engine synchronously updates the branch ledger and the global transaction status to ensure that the state on the process engine side is completely consistent with the state on the transaction business side.

[0092] This implementation can be mapped to the following capability combinations: Process initiation capability: Generates xid and bizId before starting the process and initializes global transactions. Unified delegation node capability: Executes a unified entry point according to the TRY / CONFIRM / CANCEL stage, parses extended field metadata, and routes to the corresponding participants. Metadata parsing capability: Parses configuration information such as participant, branchId, payloadVariable, critical attribute, and failedJobRetryTimeCycle from the extended fields of BPMN service tasks. Decision-making capability: Determines the Confirm or Cancel path based on the set of successfully executed Try branches and key branch attributes in the branch ledger. Transaction storage capability: Persists the global transaction table and branch transaction table, supporting multi-dimensional queries by xid, bizId, branchId, etc. Engine history query capability: Supports filtering historical activity instances by conditions such as processInstanceId, activityId, and finished. Operation and maintenance interface capability: Provides dead-letter task query, task retrieval, retry control, and audit log functions.

[0093] This application also provides an electronic device, including a processor and a memory, wherein the memory stores executable instructions, and when the executable instructions are executed by the processor, the distributed transaction orchestration and compensation method described in any of the above embodiments is implemented.

[0094] Figure 6 This is a schematic diagram of the structure of the electronic device in the embodiments of this application, such as... Figure 6 As shown, the electronic device 600 is presented in the form of a general-purpose computing device. The components of the electronic device 600 include, but are not limited to: at least one processing unit 610, at least one storage unit 620, and a bus 630 connecting different platform components (including storage unit 620 and processing unit 610).

[0095] Storage unit 620 stores program code, which can be executed by processing unit 610, causing processing unit 610 to perform the steps of the distributed transaction orchestration and compensation method described in any of the above embodiments. Storage unit 620 may include a readable medium in the form of volatile storage units, such as random access memory units and / or cache storage units, and may further include read-only memory units. Storage unit 620 may also include programs / utilities having one or more program modules, such program modules including but not limited to: operating system, one or more application programs, other program modules, and program data, each or some combination of these examples may include an implementation of a network environment.

[0096] Bus 630 can represent one or more of several types of bus structures, including a memory cell bus or memory cell controller, a peripheral bus, a graphics acceleration port, a processing unit, or a local bus using any of the various bus structures.

[0097] Electronic device 600 can also communicate with one or more external devices, which may be one or more of the following: keyboard, pointing device, Bluetooth device, etc. These external devices enable users to interact and communicate with electronic device 600. Electronic device 600 can also communicate with one or more other computing devices, including routers and modems. This communication can be performed through input / output interfaces. Furthermore, electronic device 600 can also communicate with one or more networks via a network adapter. The network adapter can communicate with other modules of electronic device 600 via bus 630. It should be understood that, although not shown in the figures, other hardware and / or software modules can be used in conjunction with electronic device 600, including but not limited to: microcode, device drivers, redundant processing units, external disk drive arrays, RAID systems, tape drives, and data backup storage platforms.

[0098] This application also provides a computer-readable storage medium for storing a program that, when executed, implements the distributed transaction orchestration and compensation method described in any of the above embodiments.

[0099] The storage medium may be a portable compact disk read-only memory and include program code, and may run on a terminal device, such as a personal computer. However, the storage medium of this application is not limited to this; it may be any tangible medium that contains or stores a program that can be used by or in conjunction with an instruction execution system, apparatus, or device.

[0100] The storage medium may be any combination of one or more readable media. A readable medium may be a readable signal medium or a readable storage medium. A readable storage medium may be, for example,, but not limited to, an electrical, magnetic, optical, electromagnetic, infrared, or semiconductor system, apparatus, or device, or any combination thereof. More specific examples of readable storage media include, but are not limited to: electrical connections having one or more wires, portable disks, hard disks, random access memory, read-only memory, erasable programmable read-only memory, optical fiber, portable compact disk read-only memory, optical storage devices, magnetic storage devices, or any suitable combination thereof.

[0101] A readable signal medium may include a data signal propagated in baseband or as part of a carrier wave, carrying readable program code. This propagated data signal may take various forms, including but not limited to electromagnetic signals, optical signals, or any suitable combination thereof. The readable signal medium may also be any readable medium other than a readable storage medium, capable of transmitting, propagating, or transmitting a program for use by or in connection with an instruction execution system, apparatus, or device. The program code contained on the readable signal medium may be transmitted using any suitable medium, including but not limited to wireless, wired, optical fiber, RF, etc., or any suitable combination thereof.

[0102] Program code for performing the operations of this application can be written in any combination of one or more programming languages, including object-oriented programming languages ​​and conventional procedural programming languages. The program code can execute entirely on the user's computing device, partially on the user's computing device, as a standalone software package, partially on the user's computing device and partially on a remote computing device, or entirely on a remote computing device or server. In cases involving remote computing devices, the remote computing device can be connected to the user's computing device via any type of network, including a local area network (LAN) or a wide area network (WAN), or it can be connected to an external computing device, for example, via the Internet using an Internet service provider.

[0103] This application also provides a computer program product, including a computer program that, when executed by a processor, implements the distributed transaction orchestration and compensation method as described in any of the above embodiments.

[0104] Finally, it should be noted that the above description, in conjunction with specific preferred embodiments, provides a further detailed explanation of this application and should not be construed as limiting the specific implementation of this application to these descriptions. For those skilled in the art, various simple deductions or substitutions can be made without departing from the concept of this application, and all such modifications or substitutions should be considered within the scope of protection of this application.

Claims

1. A method for orchestrating and compensating distributed transactions, characterized in that, include: Generate a global transaction identifier xid and a business identifier bizId. Before starting the process instance, write the global transaction identifier xid and the business identifier bizId into the process variable, and initialize the global transaction status to TRYING in the global transaction table. Each Try branch is configured with an extended field that includes at least the participant identifier and the branch identifier. During execution, the unified delegation node parses the extended field and routes the Try branch to the corresponding participant based on the participant identifier. For each Try branch, record the request message, response message, current stage, status, number of retries, error message and timestamp to form a branch transaction ledger with the global transaction identifier xid and the branch identifier branchId as the joint dimension; After the parallel gateway, multiple Try branches are executed concurrently. The set of Try branches that have been successfully executed can be obtained by querying the records with a successful stage status in the branch transaction ledger or by querying the historical activity instances of the workflow engine. When the decision conditions are met and all key Try branches succeed, the system enters the Confirm path, where the general Confirm node iterates through the set of successfully executed Try branches and calls the Confirm operation of the corresponding participant. When any key Try branch fails, times out, or is missing any key Try branch from the set of successfully executed Try branches, the system enters the Cancel path, where the general Cancel node iterates through the set of successfully executed Try branches and calls the Cancel operation of the corresponding participant.

2. The method according to claim 1, characterized in that, The method also includes unified state machine protection, which includes idempotent replay, rollback, and anti-hanging. The idempotent replay means that when the branch status is already CONFIRM_SUCCESS or CANCEL_SUCCESS, the corresponding request that arrives repeatedly will directly return the historical response result. The empty rollback is as follows: when a Cancel request is received because there is no TRY_SUCCESS record in the branch ledger, the branch status is marked as EMPTY_CANCEL and no actual Cancel call is executed; The anti-hanging mechanism is as follows: when a branch is already in the state of CANCEL_SUCCESS and a Try request subsequently arrives, the execution of the Try branch is rejected and the branch state is marked as HANGING_REJECTED.

3. The method according to claim 1, characterized in that, The extended field also includes attribute information for identifying whether a branch is a critical branch; the decision condition is: if all Try branches marked as critical branches exist in the set of successfully executed Try branches, the path is to Confirm; otherwise, the path is to Cancel.

4. The method according to claim 1, characterized in that, The general Confirm node traverses the set of successfully executed Try branches and calls the Confirm operation of the corresponding participant one by one; the general Cancel node traverses the set of successfully executed Try branches in reverse order of their successful execution or in a preset order and calls the Cancel operation of the corresponding participant one by one.

5. The method according to claim 1, characterized in that, The method also includes: the Try branch, Confirm node, and Cancel node are executed asynchronously and configured with a retry strategy; when the number of retries is exhausted, the task enters the dead letter queue; the operation and maintenance module supports querying dead letter tasks by process instance and moving dead letter tasks back to the executable queue for re-execution; during the recovery process, the branch transaction ledger and the global transaction status are updated synchronously.

6. The method according to claim 1, characterized in that, The way to query historical activity instances in the workflow engine is to filter by process instance ID (processInstanceId), activity ID (activityId), and completion status (finished) to construct a set of Try branches that have been successfully executed.

7. The method according to claim 1, characterized in that, The extended fields also include a payload variable and a failedJobRetryTimeCycle; the unified delegation node obtains business input parameters based on the payload variable and executes node-level retry control based on the failedJobRetryTimeCycle.

8. The method according to claim 1, characterized in that, The information recorded in the global transaction table includes: global transaction identifier xid, business identifier bizId, global transaction status and creation timestamp; the global transaction status includes at least TRYING, CONFIRMED, and CANCELED.

9. A distributed transaction orchestration and compensation system, characterized in that, The system is used to implement the orchestration and compensation method for distributed transactions according to any one of claims 1 to 8, the system comprising: The process startup module is used to generate a global transaction identifier xid and a business identifier bizId. Before starting the process instance, the global transaction identifier xid and the business identifier bizId are written into the process variable, and the global transaction status is initialized to TRYING in the global transaction table. The metadata parsing and routing module is used to configure extended fields containing at least the participant identifier and the branch identifier in each Try branch. During execution, the unified delegation node parses the extended fields and routes the Try branch to the corresponding participant based on the participant identifier. The transaction storage module is used to record request messages, response messages, current stage, status, number of retries, error messages and timestamps for each Try branch, forming a branch transaction ledger with the global transaction identifier xid and the branch identifier branchId as the joint dimension. The parallel triggering and status acquisition module is used to concurrently trigger the execution of multiple Try branches after the parallel gateway. It obtains the set of successfully executed Try branches by querying the records with a successful stage status in the branch transaction ledger or by querying the historical activity instances of the workflow engine. The general compensation module is used to enter the Confirm path when the decision conditions are met and all key Try branches are successful. The general Confirm node then traverses the set of successfully executed Try branches and calls the Confirm operation of the corresponding participant. When any key Try branch fails, times out, or any key Try branch is missing from the set of successfully executed Try branches, the module enters the Cancel path. The general Cancel node then traverses the set of successfully executed Try branches and calls the Cancel operation of the corresponding participant.

10. The system according to claim 9, characterized in that, The general compensation module is also used to perform unified state machine protection, which includes idempotent replay, empty rollback, and anti-hanging. Idempotent replay means that when the Confirm or Cancel operation is successfully executed, the request is repeated and the historical response is returned directly. Empty rollback means that when a Cancel request is received without a successful Try branch, it is marked as an empty rollback. Anti-hanging means that when a Try request arrives after the Cancel operation is executed, the execution of the Try branch is rejected and anti-hanging is marked.

11. An electronic device, characterized in that, include: processor; A memory, wherein executable instructions are stored; When the executable instructions are executed by the processor, they implement the distributed transaction orchestration and compensation method according to any one of claims 1 to 8.

12. A computer-readable storage medium for storing a program, characterized in that, When the program is executed by the processor, it implements the distributed transaction orchestration and compensation method according to any one of claims 1 to 8.

13. A computer program product, comprising a computer program, characterized in that, When the computer program is executed by the processor, it implements the distributed transaction orchestration and compensation method according to any one of claims 1 to 8.