A distributed concurrency control method, system, device, and medium based on a multi-granularity hierarchical architecture.

By employing a multi-granularity hierarchical architecture and linkage mechanism, the problem of balancing lock granularity and system throughput in distributed systems is solved. This achieves a balance between data consistency and system throughput in high-concurrency scenarios, reduces development and operation complexity, and enhances the robustness and fault tolerance of the system.

CN122086900APending Publication Date: 2026-05-26CTRIP COMP TECH SHANGHAI
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
CTRIP COMP TECH SHANGHAI
Filing Date
2026-02-06
Publication Date
2026-05-26

AI Technical Summary

Technical Problem

In existing distributed systems, it is difficult to balance lock granularity and system throughput. Multi-level concurrency conflicts lack collaborative defense mechanisms, lock logic is highly coupled with business logic, and there is a lack of data layer fallback verification after distributed lock failure. These technologies are insufficient to meet the requirements of data consistency, high system throughput, and maintainability in enterprise-level high-concurrency scenarios.

Method used

A multi-granularity hierarchical architecture is adopted to construct a four-layer progressive funnel architecture: request level, business aggregation level, domain object level, and persistent storage level. Combined with a unified lock management framework, annotation-driven metadata lock key generation mechanism, dynamic TTL calculation, load-aware degradation strategy, and a linkage mechanism between 'two-judgment' state pre-verification and persistent layer consistency verification, distributed concurrency control is achieved.

Benefits of technology

While ensuring strong data consistency, it significantly improves system throughput in high-concurrency scenarios, reduces development and operation complexity, enhances robustness and fault tolerance, and prevents data overwrite risks under network jitter or resource overload conditions.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122086900A_ABST
    Figure CN122086900A_ABST
Patent Text Reader

Abstract

This invention provides a distributed concurrency control method, system, device, and medium based on a multi-granularity hierarchical architecture, applied in the fields of distributed transaction processing and high-concurrency data consistency assurance. The method and system include: receiving business requests and parsing out request dimension, business aggregation dimension, and domain object dimension identifiers; sequentially generating corresponding hierarchical distributed mutex lock keys; acquiring locks level by level according to granularity shrinkage order; and upon successful acquisition, performing state pre-verification, atomic modification, and final lock release. Through the above scheme, this invention can balance strong consistency and high throughput, effectively solving problems such as rigid single lock granularity, dirty writes caused by distributed lock timeout failure, tight coupling between lock logic and business logic, and lack of secondary state verification.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of computer distributed systems technology, and in particular to a distributed concurrency control method, system, device and medium based on a multi-granularity hierarchical architecture. Background Technology

[0002] In distributed systems, when multiple service instances concurrently access shared resources, concurrency control mechanisms must be employed to ensure data consistency. Existing technologies primarily employ solutions such as single distributed locks, database pessimistic locking, or optimistic locking. Single distributed locks rely on key-value storage systems or distributed coordination services to achieve mutual exclusion, but their lock granularity makes it difficult to balance performance and correctness. If the lock granularity is too coarse, such as using tenant or merchant identifiers as lock keys, all business operations within the same logical isolation unit are forced to be serialized, leading to a significant decrease in system throughput. If the lock granularity is too fine, such as using only document identifiers as lock keys, it cannot prevent business rule conflicts across documents, such as logical errors like allowing new documents to be added during daily closing and archiving. Database pessimistic locking locks data rows by locking the current read command, which can guarantee strong consistency, but it is prone to lock waiting and deadlocks, and has poor scalability. Optimistic locking achieves lock-free updates through version numbers or status bit verification, but retry overhead is high in high-conflict scenarios, and it lacks the ability to constrain state at the business semantic level. Furthermore, existing solutions generally suffer from tight coupling between lock logic and business logic. Developers need to manually construct lock keys, which can easily lead to lock failure due to missing fields or inconsistent naming. Additionally, most solutions fail to perform state pre-validation after acquiring the lock, making it impossible to identify situations where the business state has been changed by other threads during lock holding, thus posing a risk of duplicate execution or illegal state transitions.

[0003] The aforementioned deficiencies make it difficult for existing concurrency control mechanisms to meet the comprehensive requirements of strong data consistency, high system throughput, and maintainability in enterprise-level high-concurrency scenarios.

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

[0005] In view of this, the present invention provides a distributed concurrency control method, system, device, and medium based on a multi-granularity hierarchical architecture. It aims to solve the problems in existing technologies, such as the difficulty in balancing lock granularity and system throughput, the lack of collaborative defense mechanisms for multi-level concurrency conflicts, the high coupling between lock logic and business logic, and the lack of data layer fallback verification after distributed lock failure. By constructing a four-layer progressive funnel architecture—request-level, business aggregation-level, domain object-level, and persistent storage-level—and combining a unified lock management framework, an annotation-driven metadata lock key generation mechanism, dynamic TTL calculation, load-aware degradation strategies, and a linkage mechanism between "two-judgment" state pre-verification and persistent layer consistency verification, the system throughput in high-concurrency scenarios is significantly improved while ensuring strong data consistency. This also reduces development and maintenance complexity and enhances robustness and fault tolerance under extreme network jitter or resource overload conditions.

[0006] This invention provides a distributed concurrency control method based on a multi-granularity hierarchical architecture. The method is executed by an electronic device and includes the following steps: Receive business processing requests for the target transaction object, and parse the request dimension identifier, business aggregation dimension identifier, and domain object dimension identifier from the business processing request according to the pre-configured feature identifier extraction rules; Based on the request dimension identifier, business aggregation dimension identifier, and domain object dimension identifier, corresponding distributed mutex lock keys are generated for each level. Using the generated distributed mutex keys at each level, attempt to acquire the distributed mutex keys at each level in sequence according to the preset granularity shrinkage order; After successfully acquiring all preset levels of distributed mutex locks, perform the state pre-verification step: query the current state of the target transaction object and determine whether the current state meets the data consistency preconditions of the business processing request. If the state pre-verification step passes, the corresponding business logic is executed, and an atomic change operation is performed on the target transaction object in the persistent storage layer; the atomic change operation includes consistency verification based on data state and verification of the actual number of rows affected by the change operation; Release distributed mutexes at all levels when an atomic change operation is completed or when an exception occurs during an atomic change operation.

[0007] In some optional embodiments, the atomicity change operation specifically includes: Construct a database update command that includes state constraints; Execute the database update command and obtain the actual number of rows affected by the database. Determine whether the actual number of rows affected matches the expected number of rows; If the actual number of rows affected is greater than the expected maximum number of rows, or if the actual number of rows affected is inconsistent with the expected number of rows, then concurrency control is deemed to have failed and a transaction rollback is triggered.

[0008] In some optional embodiments, the step of parsing the identifier from the business processing request according to the pre-configured feature identifier extraction rules and generating the corresponding level of distributed mutex key specifically includes: Retrieve the lock key definition interface instance corresponding to the business processing request; Using at least one of reflection mechanism and metadata parsing technology, extract field values ​​corresponding to request dimension identifier, business aggregation dimension identifier and domain object dimension identifier respectively from the business processing request based on the lock key definition interface instance; The extracted field values ​​are sorted according to a preset lexicographical order; Using a preset separator, the hierarchy prefix, business type identifier, and sorted field values ​​are concatenated to generate a distributed mutex key.

[0009] In some optional embodiments, the step of sequentially attempting to acquire distributed mutex locks at each level is specifically configured as follows: A fast-fail strategy is adopted; if the acquisition of a distributed mutex at any level fails, the acquisition attempts of the distributed mutex at subsequent levels are immediately terminated, the state pre-verification step is not entered, and a response indicating that the concurrency processing has failed is returned to the caller.

[0010] In some optional embodiments, an exception rollback step is also included: If the state pre-verification step fails, or if an exception occurs during the execution of business logic, a compensation mechanism will be triggered. The compensation mechanism releases all currently held distributed mutexes in reverse order of the order in which they were acquired.

[0011] In some optional embodiments, the distributed mutex lock has an effective lifetime, which is not a fixed value but is dynamically set in the following ways: Obtain the historical average processing time for the business type to which the business processing request belongs; The effective survival time is calculated by adding a preset buffer time to the historical average processing time. When attempting to acquire a distributed mutex lock, the calculated effective lifetime is passed as a parameter to the distributed coordination mechanism.

[0012] In some optional embodiments, a degradation control step based on system load is also included: Real-time monitoring of computer system load metrics; When the load metric exceeds the preset threshold, the preset granularity shrinkage order is automatically adjusted, skipping the step of building a distributed mutex lock based on the request dimension identifier, and only performing locking operations based on the business aggregation dimension identifier and the domain object dimension identifier.

[0013] In some alternative embodiments, the distributed coordination mechanism is selected from one of the following group: Atomic setting instructions and expiration time mechanism based on key-value storage system; A temporary sequential node mechanism based on distributed coordination services.

[0014] In some optional embodiments, the persistence layer consistency check is selected from one of the following groups: Optimistic locking mechanism: When executing a data update command, it compares whether at least one of the data version number and timestamp fields has changed; State machine constraint mechanism: When executing a data update instruction, the previous state is used as part of the update condition; Pessimistic row locking mechanism: Before executing business logic, the target data row is locked using the current read lock command of the database.

[0015] In some alternative embodiments, the method is implemented using the template method design pattern, including: Define a lock key definition interface to encapsulate feature identifier extraction rules; Define a business callback interface to encapsulate business logic and state pre-validation steps; When executing the method, the implementation instances of the lock key definition interface and the business callback interface are injected into the template method of the lock management framework. The template method drives the execution of the process, which includes the steps of receiving business processing requests for the target transaction object and releasing the distributed mutex locks at each level.

[0016] In some optional embodiments, the preset granularity shrinkage order is specifically configured as follows: First level: Request dimension-based locking, used to prevent repeated replay of the same business processing request; The second level: locking based on business aggregation dimension identifiers, used to achieve serialization within the scope of logical isolation units; The third level: Domain object dimension-based locking, used to prevent concurrent race conditions targeting specific data entities.

[0017] In some optional embodiments, the following features are characterized: The business aggregation dimension identifier corresponds to at least one of the tenant identifier and merchant identifier in a multi-tenant system; The target transaction object corresponds to at least one of the resource change document and the inventory record; The persistent storage layer corresponds to a relational database that supports transactions.

[0018] This invention provides a distributed concurrent control system based on a multi-granularity hierarchical architecture, comprising: The request parsing module is used to receive business processing requests for the target transaction object and use pre-configured feature extraction rules to parse the request dimension identifier, business aggregation dimension identifier, and domain object dimension identifier from the business processing request. The lock management module is used to generate distributed mutex lock keys at each level based on feature identification extraction rules, and to use the distributed mutex lock keys to attempt to acquire distributed mutex locks at each level in a predetermined granularity shrinkage order through a distributed coordination mechanism. The logic control module is used to perform a state pre-verification step after the lock management module successfully acquires all preset levels of distributed mutex locks. That is, to query the current state of the target transaction object and determine whether the current state meets the preconditions for data consistency. The transaction execution module is used to execute the corresponding business logic after the state pre-verification step passes, and to perform atomic change operations including consistency verification on the target transaction object in the persistent storage layer. After the atomic change operation is completed, the lock management module is triggered to release the distributed mutex locks at each level.

[0019] This invention provides an electronic device, including a memory, a processor, and a computer program stored in the memory and executable on the processor. When the processor executes the computer program, it implements the method described above.

[0020] This invention provides a computer-readable storage medium storing a computer program thereon, which, when executed by a processor, implements the method described above.

[0021] It should be understood that the above general description and the following detailed description are exemplary and explanatory only, and are not intended to limit the invention.

[0022] The distributed concurrency control method, system, device, and medium based on a multi-granularity hierarchical architecture of the present invention have the following beneficial effects: This invention achieves a balance between strong data consistency and system throughput in high-concurrency scenarios through the synergy of a four-layer funnel-shaped lock architecture and a unified lock management framework. The progressively shrinking lock granularity at the request layer, business aggregation layer, and domain object layer effectively intercepts invalid contention traffic; state pre-verification and persistence layer consistency verification provide dual protection, eliminating the risk of data overwriting caused by network partitions, GC pauses, or lock timeouts; the template method design pattern and metadata-driven lock-key generation mechanism significantly reduce development coupling and human error rates, improving system robustness and maintainability. Attached Figure Description

[0023] Other features, objects, and advantages of the invention will become more apparent from the following detailed description of non-limiting embodiments with reference to the accompanying drawings.

[0024] Figure 1 This is a flowchart of a distributed concurrency control method based on a multi-granularity hierarchical architecture according to an embodiment of the present invention; Figure 2 This is a flowchart of an embodiment of optimistic locking and the verification of the number of affected rows according to the present invention; Figure 3 This is a data flow diagram of an embodiment of the automatic lock key generation mechanism of the present invention; Figure 4 This is a flowchart of the execution of a pessimistic lock with a "two-way judgment" mechanism according to an embodiment of the present invention; Figure 5 This is a schematic diagram of the structure of a distributed concurrent control system based on a multi-granularity hierarchical architecture according to an embodiment of the present invention. Detailed Implementation

[0025] 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 the examples set forth herein; rather, they are provided so that the invention will be more comprehensive and complete, and will fully convey the concept of the exemplary embodiments to those skilled in the art. The described features, structures, or characteristics may be combined in any suitable manner in one or more embodiments.

[0026] Furthermore, the accompanying drawings are merely illustrative of the invention and are not necessarily drawn to scale. The same reference numerals in the drawings 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 systems and / or microcontroller systems.

[0027] The flowchart shown in the attached diagram is merely an illustrative example and does not necessarily include all steps. For example, some steps may be broken down, while others may be combined or partially combined. Therefore, the actual execution order may change depending on the specific circumstances.

[0028] In distributed systems, ensuring data consistency under high concurrency relies on the orderly control of access to shared resources. Essentially, this involves setting mutual exclusion boundaries at different abstraction levels, transforming global competition into locally controllable, serialized execution paths. The request dimension identifies the uniqueness of a single operation from the client's perspective; the business aggregation dimension reflects cross-entity business rule constraints within logically isolated units; and the domain object dimension characterizes the atomic change requirements of specific data entities. These three dimensions together constitute a progressive granularity relationship from the outside in, enabling the system to intercept duplicate requests at extremely low cost at the traffic entry point, prevent concurrent interference violating macro-rules at the business logic layer, and ensure the competitive safety of specific operations at the entity layer. This layered mutual exclusion mechanism, combined with state pre-verification, ensures that the system verifies the current state of the data after acquiring the lock, thus avoiding logical errors caused by the state being updated by other threads during lock holding. Furthermore, the synergistic use of distributed coordination mechanisms and the atomicity capabilities of persistent storage layers leverages middleware for coarse-grained coordination across nodes while relying on the database's own ACID properties to guarantee final data consistency, forming a multi-level defense system. Consequently, the system can significantly improve throughput while maintaining strong consistency, avoiding performance bottlenecks or management failures caused by single-lock granularity, and still possesses a fallback data security capability in the face of anomalies such as network partitions and GC pauses.

[0029] The distributed concurrency control method based on a multi-granularity hierarchical architecture provided in this embodiment of the invention is executed by an electronic device and includes the following steps: Step S100: Receive a business processing request for the target transaction object, and use the pre-configured feature extraction rules in the lock management framework to parse the request dimension identifier, business aggregation dimension identifier, and domain object dimension identifier from the business processing request. In one embodiment, the business processing request is an operation request to submit an invoice application, and the target transaction object is the invoice application document; the request dimension identifier is a unique request identifier bound to the current HTTP or RPC call, the business aggregation dimension identifier is the tenant ID or merchant ID, and the domain object dimension identifier is the invoice document ID or payment application ID. In other optional implementations, the business processing request may also correspond to scenarios such as inventory deduction, account balance update, or financial archiving, and correspondingly, the dimension identifiers are mapped to SKU codes, account group numbers, or daily settlement batch numbers, respectively.

[0030] Step S200: Based on the feature identification extraction rules, distributed mutex keys for the corresponding levels are generated using request dimension identifiers, business aggregation dimension identifiers, and domain object dimension identifiers, respectively. In this embodiment, for ease of describing the architecture layering, the distributed mutex key built based on the request dimension identifier is defined as the control means of the request layer; the distributed mutex key built based on the business aggregation dimension identifier is defined as the control means of the business aggregation layer; and the distributed mutex key built based on the domain object dimension identifier is defined as the control means of the domain object layer. The atomic change operations subsequently performed in the persistent storage layer constitute the final line of defense of the persistent storage layer. Based on the above definitions, keys for the corresponding levels are generated. In one embodiment, each level of lock key adopts a unified namespace structure, comprising three parts: a level marker, a business type label, and an identifier value, such as "lock:level:request:submit_invoice:uuid-abc123", "lock:level:business:tenant:8888", and "lock:level:domain:invoice:INV-20240001". In other optional implementations, the lock key format can be adapted to the naming constraints of different middleware. For example, in a ZooKeeper-based implementation, the level marker is represented as a path segment, such as " / locks / request / submit_invoice / uuid-abc123".

[0031] Step S300: Utilizing distributed mutex keys, a distributed coordination mechanism is used to sequentially attempt to acquire distributed mutex locks at each level according to a preset granularity contraction order. In this preset granularity contraction order, successfully acquiring the distributed mutex lock at the previous level is a prerequisite for attempting to acquire the distributed mutex lock at the current level. In one embodiment, the granularity contraction order is a three-layer progressive structure: the first layer corresponds to the request dimension and is used to intercept duplicate traffic; the second layer corresponds to the business aggregation dimension and is used to isolate concurrent interference at the tenant or merchant level; the last layer corresponds to the domain object dimension and is used to ensure the atomicity of specific entity operations. In other optional implementations, the granularity contraction order can be dynamically adjusted, for example, skipping a certain level according to runtime strategies, or expanding to a four-layer structure in a specific business context, adding a data access channel dimension as a supplementary control layer.

[0032] Step S400: After successfully acquiring all preset levels of distributed mutex locks, perform a state pre-verification step: query the current state of the target transaction object and determine whether the current state meets the data consistency preconditions of the business processing request. In one embodiment, state pre-verification is completed by reading the latest snapshot of the transaction object in the persistent storage layer. The preconditions include at least one of the following: the range of state bit values, version number matching relationship, or business flow constraints; for example, modification operations are prohibited for documents in the "archived" state, or updates are refused for records whose version number is not equal to the expected value. In some other optional implementations, state pre-verification can be combined with a caching layer for preliminary filtering, only querying the persistent storage layer when the cache misses or the verification fails, in order to reduce database access pressure.

[0033] Step S500: If the state pre-verification step passes, the corresponding business logic is executed, and an atomic change operation is performed on the target transaction object in the persistent storage layer. The atomic change operation not only includes consistency verification based on data state but also mandates a verification step on the actual number of rows affected by the change operation. Specifically, the system receives the number of affected rows returned after the database executes the update instruction, compares it with the expected number of modified rows, and uses this as the final confirmation of successful concurrency control. In one embodiment, the business logic includes invoice information verification, tax rate calculation, and invoicing rule matching; the atomic change operation is encapsulated through a database transaction, and a state verification clause is embedded in the SQL statement to ensure that the update is only performed when the data meets the preconditions. In other optional implementations, the atomic change operation can also be implemented using conditional CAS instructions, timestamp comparison, or row lock hints (such as SELECT … FOR UPDATE), depending on the capabilities of the underlying storage engine and the consistency model requirements.

[0034] Step S600: Release the distributed mutex locks at each level when the atomic change operation is completed or when an exception occurs during the atomic change operation. In one embodiment, lock release is performed in the reverse order of acquisition, i.e., first release the domain object dimension lock, then release the business aggregation dimension lock, and finally release the request dimension lock, to avoid lock resource residue due to partial failure. In other optional implementations, lock release can be asynchronously triggered by an independent cleanup coroutine, or rely on the session timeout automatic recycling mechanism of the distributed coordination service as a fallback guarantee.

[0035] The technical features involved in the above steps form a closely coordinated working relationship: Steps S100 and S200 jointly realize the automation and context awareness of lock key generation, making the definition of lock resources free from hard coding and possessing business semantic readability; Step S300 constructs a "funnel-shaped" traffic filtering path through a hierarchical dependency mechanism, intercepting high-frequency, low-risk repetitive requests at the system edge, significantly reducing the lock contention intensity at the data layer; Step S400's state pre-verification, as a connecting link, reconfirms the validity of the business state while holding the distributed lock, compensating for the semantic uncertainty caused by network partitions or client anomalies in the distributed lock; Steps S500 and S600 form a closed-loop defense system through the eventual consistency guarantee of the persistence layer and deterministic lock lifecycle management. This multi-level, multi-stage, and multi-mechanism coupled design collaboratively solves the root contradictions in existing technologies, such as the difficulty in balancing lock granularity and system throughput, decentralized and error-prone lock management, and data overwriting caused by state drift in concurrent states, thereby supporting higher-scale concurrent transaction processing without sacrificing strong consistency.

[0036] Through the above solution, this embodiment can achieve fine-grained and phased concurrency control of transaction objects in a distributed environment, improve the overall throughput of the system while ensuring strong data consistency; at the same time, it reduces the cognitive load and error probability of developers in the implementation of concurrency logic, and enhances the observability and operational controllability of the system.

[0037] In one specific implementation, based on the above embodiments, the lock key definition interface instance is a class object that implements the LockKeyCallback interface. This interface declares the generateKey() method, whose default implementation logic is encapsulated in the framework base class. The data structure corresponding to the business processing request is a Java type request parameter object. The fields of this object are annotated with @LockKey(level = Level.XXX, sortOrder = N), where the Level enumeration value is REQUEST, BUSINESS, or DOMAIN, and sortOrder is a non-negative integer. First, the framework uses Java reflection to traverse all declared fields of the request parameter object and filters out all fields annotated with @LockKey. Specifically, the filtered fields are grouped by the level attribute to form three independent field sets: request dimension field set, business aggregation dimension field set, and domain object dimension field set. Then, for each field set, the sortOrder of each field is used to... The values ​​are sorted in ascending order; if multiple fields have the same `sortOrder`, they are further sorted lexicographically by field name; then, for each group of sorted fields, their getter methods are called sequentially to obtain the runtime field values, and these values ​​are converted into string representations; finally, for each group of field values, a colon (:) is used as a separator to concatenate them, with a hierarchical prefix string added before each group, such as "lock:req:", "lock:biz:", and "lock:dom:", and a business type identifier is appended, provided by the `type` attribute of the lock type enumeration `RequestLockKeyEnum`, to generate the final lock key; for example, when the request object contains `@LockKey(level = Level.DOMAIN, sortOrder = 0) privateString invoiceType = "TAX_INVOICE";` and `@LockKey(level = Level.DOMAIN, sortOrder = 1) private String serialNumber = "202310010001";` At that time, the generated domain layer lock key is "lock:dom:submit_invoice_and_payment.TAX_INVOICE:202310010001".

[0038] In other alternative implementations, field value extraction does not rely on annotations but uses external metadata configuration files such as YAML or JSON to define field paths and hierarchical mappings; the sorting strategy can be replaced by the order of field declarations instead of the `sortOrder` attribute value; the separator can be replaced by a period (.) or an underscore (_); the hierarchical prefix is ​​configurable and supports runtime injection from the context; the business type identifier can also be explicitly passed in by the caller or automatically deduced by extracting the simple class name of the request class through reflection.

[0039] Through the above solution, this embodiment can achieve complete decoupling between the lock key generation logic and the business parameter structure, avoid hard-coded concatenation logic, and ensure that business parameters with the same semantics generate deterministic lock keys under different call paths. At the same time, the reflection and annotation-driven design allows new business scenarios to take effect simply by adjusting field annotations, without modifying the lock management code, which significantly improves maintainability and scalability.

[0040] like Figure 2 As shown, in step S500, when an atomic change operation is performed to the persistent storage layer, the transaction execution module first initiates a database transaction and constructs a database update instruction containing strict state constraints such as version number matching or specific state bit judgments. Subsequently, the module executes the database update instruction and synchronously obtains the actual number of affected rows returned after the database execution as a key verification basis. The system executes a three-level judgment logic for the actual number of affected rows: First, it checks if the actual number of affected rows is equal to zero. If it is, it indicates that the target data has been modified by other concurrent processes between the state pre-verification and the current update operation, causing the optimistic locking precondition to fail. In this case, it is judged as a concurrent conflict, the database transaction is rolled back, the process ends, and a failure response is returned. Second, it checks if the actual number of affected rows is greater than the expected maximum number of rows. In a typical document update scenario, the expected value is usually 1. If it is greater than the expected value, it indicates that the WHERE condition of the update instruction may have an abnormally broad risk. To prevent accidental updates of a large amount of data (i.e., to prevent table flushing), the system triggers a safety circuit breaker mechanism, forcibly rolls back the database transaction, records a high-level security alarm, and returns a failure response. Finally, only when the actual number of affected rows is strictly equal to the expected number of rows is the atomic change operation judged to be successfully completed, and then the database transaction is committed, the entire business processing flow is completed, and a success response is returned.

[0041] In one specific implementation, based on the above embodiments, the state pre-verification step calls the read interface of the persistent storage layer through the transaction execution module. First, it initiates a current-read query to the relational database, the target of which is the primary key record corresponding to the current business processing request. This query operation does not lock or start a new transaction, but only obtains the latest committed snapshot data of the target transaction object in the persistent storage layer in read-only mode. Then, at least one piece of state verification data for consistency determination is extracted from the snapshot data. The state verification data includes the version number field (version), timestamp field (updated_at), status enumeration field (status), or any combination thereof explicitly defined in the database table. Next, the extracted state verification data is compared item by item with the data consistency preconditions carried in the business processing request. The preconditions are injected by the business callback interface during the initialization phase and encapsulated in the execution context in the form of structured parameters. If all the state verification data participating in the comparison are consistent with the preconditions, the state pre-verification step is deemed to have passed; if any state verification data does not match the corresponding precondition, the state pre-verification step is deemed to have failed.

[0042] In some other alternative implementations, the extraction of status verification data can be accomplished based on a real-time synchronized copy provided by a database view, materialized log table, or change data capture (CDC) channel; the comparison logic can be configured to support fuzzy matching modes, such as allowing the timestamp field to float within a preset tolerance window, or enabling compatibility mapping rules for the status field (such as treating "PROCESSING" and "IN_PROGRESS" as equivalent).

[0043] Through the above scheme, this embodiment can ensure that the actual persistent state of the data is finally confirmed while holding a distributed mutex lock, thereby eliminating the consistency risk caused by state changes caused by other paths not controlled by this lock during the lock holding period; at the same time, this mechanism does not rely on the semantic integrity of the lock itself, but pushes the verification responsibility down to the storage layer facts, so that the reliability boundary of concurrency control can be clearly defined and verified.

[0044] To generate deterministic distributed lock keys, this embodiment employs an automated generation strategy based on reflection and lexicographical ordering. The specific execution flow of this strategy is as follows: Figure 3As shown in the diagram. First, the lock management module receives the business request object to be processed as input. Then, it uses reflection, a mechanism provided by the programming language, to examine the object's class definition, traversing and extracting the key fields involved in the lock key construction and their current values. To eliminate lock key differences caused by different field declaration orders in the code, the system forcibly arranges all extracted fields in lexicographical order (AZ) of field names. Subsequently, according to pre-configured rules, a specific separator (e.g., a colon ":") is used to concatenate the current level's prefix identifier (e.g., "lock:biz"), the business type identifier, and the sorted field values ​​into a string. The final concatenated string is the unique distributed mutex lock key corresponding to that level. This mechanism ensures that as long as the key business data of the input object is the same, the generated lock key remains consistent regardless of which application node it resides in, effectively avoiding concurrency control failures caused by inconsistent lock keys.

[0045] In one specific implementation, based on the above embodiments, when the state pre-verification step determines that the current state does not meet the data consistency precondition, the logic control module further performs an idempotency discrimination operation: First, it extracts the business completion identifier field from the latest persistent data. The business completion identifier field includes, but is not limited to, at least one of the following: status bit (status), result code (result_code), finished timestamp (finished_at), and transaction trace ID (trace_id); then, it matches the value of the business completion identifier field with a preset completed semantic pattern, which is defined as: status bit equal to SUCCESS, or result_code equal to "0000", or finished_at is not empty and earlier than the current system time, or trace_id exists in the archived transaction log table; if any match is true, it is determined that the business processing request has been successfully executed; then, it constructs an idempotent response result that completely corresponds to the original request parameters. The idempotent response result includes complete snapshot data of the original business document and a deterministic response header, such as HTTP 200 OK, Idempotent-Result: If the condition is true, the transaction will return directly to the caller, skipping all subsequent business logic execution, atomic change operations, and lock release processes. If none of the completed semantic patterns match, a StateConflictException will be thrown. This exception carries the current actual state value, expected preconditions, and failure reason code. The transaction execution module will capture the exception and terminate the current processing flow.

[0046] In some other alternative implementations, the logic for determining the completed semantic pattern can be configured to be dynamically loaded based on a rule engine that supports JSON-formatted conditional expression DSLs, such as {"operator": "eq", "field": "status", "value": "SUCCESS"}; or, the construction method for the idempotent response result can be replaced by retrieving the historical response serialization body by key from a read-only cache (such as Redis) and deserializing it; or, the source of the business completion identifier field can be extended to the consumption confirmation record of the message queue, the global transaction status table of a distributed transaction coordinator such as Seata, or the event tracing snapshot provided by an external auditing service.

[0047] In one specific implementation, when the second-order check detects that an invoice application already exists, the system does not directly throw an exception. Instead, it calls a pre-defined idempotent compensation callback function. This function performs a read-only query, retrieves the detailed information of the submitted invoice from the database, and encapsulates it into a response format identical to the initial successful submission, returning it to the client. This mechanism ensures that the upstream system obtains the expected result during retries without being aware of concurrency conflicts.

[0048] Through the above solution, this embodiment can accurately distinguish between two different types of failure scenarios, namely "duplicate submission" and "illegal concurrent modification," after the state pre-verification fails. It implements a zero-overhead idempotent response for the former, avoiding redundant calculations and storage writes, and significantly reducing system resource consumption and database pressure in high-concurrency retry scenarios. At the same time, through the structured and configurable completed semantic pattern definition, the idempotent determination logic has business customizability and operational observability, and can adapt to the state semantic evolution of different domain models without modifying the framework code.

[0049] In one specific implementation, the step of sequentially attempting to acquire distributed mutex locks at each level is configured to employ a fail-fast strategy: when the lock management module initiates lock acquisition requests sequentially according to a preset granularity shrinkage order, it first attempts to acquire the first-level lock; if this acquisition operation returns a failure signal, the lock management module immediately terminates all subsequent lock acquisition attempts, does not perform state pre-verification steps, and does not call any business callback interfaces, but directly constructs a concurrent processing failure response and returns it to the caller; specifically, this failure signal is generated by the distributed coordination mechanism when atomicity setting conditions are not met, such as Redis's SETNX command returning 0, or ZooKeeper's createEphemeralNode. When a NodeExistsException is thrown, synchronous feedback is provided. Then, the lock management module maps the signal to a predefined exception type, including but not limited to DuplicateRequestException for first-level failure, SystemBusyException for second-level failure, and ResourceContentionException for third-level failure, and encapsulates it into a standardized error code and description information, which is output through a unified response channel. Then, throughout the entire process, the lock management module does not maintain any intermediate state cache, nor does it perform retry or fallback logic, ensuring that there is only one network round trip and local exception construction overhead between the lock acquisition failure and the response return.

[0050] In other alternative implementations, the criteria for determining the fast-fail strategy can be expanded to include response latency based on a timeout threshold: the lock management module sets an independent waiting timeout for each level of lock acquisition operation; if a successful confirmation response is not received from the distributed coordination mechanism within this time, the acquisition is considered a failure and the subsequent process is terminated immediately; alternatively, the fast-fail behavior can be dynamically enabled or disabled through a configuration switch, with its configuration items stored in a centralized configuration service and supporting runtime hot updates; or, the failure response can be constructed in a way that adapts to different communication protocols, for example, returning a 423 Locked status code in an HTTP scenario and throwing a specific subclass of ApplicationRuntimeException in an RPC scenario.

[0051] Through the above scheme, this embodiment can ensure that the system has deterministic low-latency characteristics in intercepting invalid requests in high-concurrency competition scenarios, avoiding the waste of computing resources and the accumulation of response delays caused by continuing to perform redundant verification and resource reservation operations after some lock acquisition failures. At the same time, since it does not enter the state pre-verification and business execution stage, it eliminates the potential risk of consistency misjudgment caused by residual state checks after lock failure, and improves the overall predictability and observability of the concurrency control path.

[0052] like Figure 4 As shown, in step S300, the system uses the generated distributed mutex keys at each level to attempt to acquire the distributed mutex locks at each level in a preset granularity shrinkage order, such as first the request layer, then the business aggregation layer, and finally the domain object layer. This embodiment employs a fail-fast strategy at this stage. If the acquisition of any distributed mutex lock at any level fails, for example due to timeout or being held by another process, the system immediately terminates the acquisition attempt for subsequent levels of locks, skips the subsequent state pre-verification steps, and directly returns a concurrency processing failure response to the caller, thereby ending the current processing flow. Only after successfully acquiring distributed mutex locks at all preset levels does the process enter the safe critical section and execute step S400.

[0053] Step S400 is the execution of state pre-verification, also known as the two-step judgment mechanism. In this step, the logic control module queries the latest state of the target transaction object from the persistent storage layer and determines whether the current state meets the data consistency preconditions of the business processing request, such as comparing version numbers for consistency or checking whether the status bits allow execution. Based on the result of the state pre-verification, the system executes differentiated branch logic: if the state pre-verification passes, it indicates that the request is valid and the current data snapshot allows the operation, and the process then proceeds to step S500 to execute the corresponding business logic and atomic changes; if the state pre-verification fails, the system further analyzes the reason for the inconsistency, especially when the current state indicates that the business processing request corresponding to the request dimension has been successfully executed in the past, such as when the document status has been shown as completed. In this case, the system enters the idempotent response processing branch, constructs a response result consistent with the first successful execution, and returns it directly without repeating the business logic and atomic change operations in step S500, thereby achieving idempotency control of the interface.

[0054] In one specific implementation, based on the above embodiments, when the state pre-verification step fails or an exception occurs during the execution of business logic, the lock management framework triggers a compensation mechanism. This compensation mechanism is configured to release all currently successfully held distributed mutexes in reverse order of the order in which they were acquired. Specifically, if the system has successfully acquired three locks—the request layer lock, the business aggregation layer lock, and the domain object layer lock—then, when an exception occurs, the unlocking interface of the distributed coordination service is first called to release the domain object layer lock, then the business aggregation layer lock, and finally the request layer lock. This reverse-order release process is encapsulated in a unified lock lifecycle manager. Furthermore, this is ensured through try-finally structures or AOP around advice, guaranteeing that regardless of whether the business logic is completed, whether the validation passes, or whether the exception is caught, as long as a lock at a certain level has been successfully held, its release operation is included in the compensation path. In some other optional implementations, the reverse release action can be driven by an independent lock state snapshot module. This module records the currently held lock level sequence and corresponding lock key after successful locking, and performs a rollback based on the snapshot when an exception is thrown. Alternatively, the reverse release logic is integrated into the transaction context propagation mechanism and linked with the database transaction rollback hook, synchronously triggering the lock release process when the transaction is marked for rollback.

[0055] Through the above scheme, this embodiment can ensure that when any execution branch is interrupted, the occupied distributed coordination resources are returned in a timely and deterministic manner, avoiding long-term blocking of subsequent requests or system-level deadlock due to lock residue; at the same time, the reverse release strategy is strictly symmetrical with the locking order, making the lock holding boundary clear and traceable, reducing the risk of inconsistent lock states in a distributed environment, and improving the reliability and observability of the concurrency control mechanism in abnormal scenarios.

[0056] In one specific implementation, the effective time-to-live (TTL) of the distributed mutex lock is determined dynamically rather than using a preset fixed value. Effective time-to-live = Historical average processing time × (1 + fluctuation coefficient) + preset buffer time. Specifically, before initiating a locking request, the lock management module first queries the system monitoring service for the historical average processing time μ corresponding to the current business type. This historical average processing time is statistically analyzed in real time based on the completion time of similar requests within a sliding time window, such as the last 10 minutes, and reported to the unified indicator center by the monitoring agent component with millisecond-level precision. Then, the lock management module multiplies this historical average processing time by a preset fluctuation coefficient σ (in one embodiment, σ is 0.2), and then adds a reserved buffer time Δ (in one embodiment, Δ is 500 milliseconds) to obtain the basic calculation result. Next, this result is compared with the system-set minimum lock duration T (in one embodiment, T is 300 milliseconds), and the larger of the two values ​​is taken as the final TTL value. Finally, when calling the locking interface of the distributed coordination mechanism, this TTL value is passed as a timeout parameter, for example, as the EX parameter in Redis's SETNX instruction, and as a reference for session timeout in ZooKeeper's createEphemeralNode call.

[0057] In some other alternative implementations, the historical average processing time can be replaced with a weighted moving average, where recent requests have a higher weight than historical requests; the fluctuation coefficient σ can be configured to different values ​​according to the business type, for example, 0.5 for long-time tasks such as reporting and 0.1 for short-time tasks such as status query; the buffer time Δ can be replaced with the percentile of the most recent Full GC duration (e.g., P95) obtained from JVM GC log analysis; the minimum lock duration T can be set differently according to the lock level, for example, T is 100 milliseconds for request layer locks and 500 milliseconds for domain layer locks, to adapt to the different tolerances for response latency at each level.

[0058] By employing the above solution, this embodiment addresses the technical contradiction of a fixed timeout being either too short in long-tail business scenarios, leading to premature lock release and potential concurrency issues, or too long in short-tail business scenarios, resulting in resource waste and reduced throughput. This embodiment tightly couples the lifecycle of the distributed mutex lock with the actual business execution characteristics, avoiding both concurrency conflicts caused by premature lock release due to an excessively short fixed TTL and long-term resource blocking and reduced system throughput due to an excessively long fixed TTL. Furthermore, its adaptive nature allows for automatic adjustment of the lock lifecycle in scenarios such as system load changes, code performance optimization, or data growth, without requiring manual configuration intervention.

[0059] In one specific implementation, a load monitoring agent module is also configured. This module periodically collects runtime metrics and outputs them to the logic control module. The load monitoring agent module is configured to read the average CPU load rate, JVM heap memory usage, and active thread count of the thread pool from the operating system kernel interface every second, and calculate a weighted average using a sliding time window (window length of 60 seconds) as the current load metric. Before executing the funnel-shaped locking process each time, the logic control module first calls this load indicator and compares it with the preset degradation threshold. Compare; when determining At this time, the logic control module dynamically rewrites the lock level configuration strategy for this request, changing the original three-level lock sequence. Replace with a second-level lock sequence This skips the parsing, key generation, and distributed lock acquisition operations for request dimension identifiers; specifically, the logic control module marks `skipRequestLevelLock = true` during the context initialization phase, and directly enters the lock key generation stage for business aggregation dimension identifiers based on this mark in the funnel-shaped locking steps; (Degradation threshold) The configuration is injected by the configuration center at system startup, with a default value of 0.85, and supports runtime hot updates. It should be understood that skipping request-layer locks does not mean abandoning concurrency control, but rather strategically tightening defenses. Under high load, the system prioritizes protecting the business aggregation layer, preventing cross-tenant interference, and the domain object layer to prevent data corruption, while temporarily tolerating a small number of duplicate requests entering the business processing stage, subsequently using a unique index or idempotency check at the database layer as a fallback.

[0060] In other alternative implementations, load metrics may include at least one of the following: Redis connection pool wait queue length, database master TPS drop rate, or HTTP gateway 5xx error rate; the degradation judgment logic may be replaced with an adaptive threshold algorithm based on exponential moving average (EMA), where the threshold is dynamically adjusted according to historical load trends; the operation of skipping request level locks can also be implemented by setting conditional branches within the lock management module, i.e., when the skipRequestLevelLock flag is detected to be true, the lock management module does not perform any reflection extraction and key concatenation operations on the input request dimension identifier field, and does not initiate any communication with the distributed coordination service. The relevant SETNX or createEphemeralNode calls.

[0061] Through the above solution, this embodiment can automatically shrink the concurrency control defense line under sudden high load scenarios, reduce one network round trip and lock resource contention of distributed coordination service, thereby reducing the overall request latency and increasing the system throughput limit; at the same time, since the locks of the business aggregation layer and the domain object layer remain intact and the data consistency constraints are not weakened, the system can still prevent cross-tenant interference and entity-level race conditions in the degraded state.

[0062] In one specific implementation, the distributed coordination mechanism is implemented as an atomic set-value command and expiration time mechanism based on a key-value storage system. First, the lock management module calls the Redis client to execute the `SET key value NXEX ttl` command, where `key` is a distributed mutex key of a certain level generated by feature extraction rules, `value` is a unique client identifier (e.g., a combination of UUID and thread ID), `NX` ensures that the set is successful only if the key does not exist, and `EX ttl` specifies the time-to-live (TTL) of the lock key, calculated using the above embodiment. Specifically, if the command returns `OK`, the lock acquisition at that level is considered successful; if it returns `nil`, the acquisition fails, and subsequent lock attempts are terminated. This mechanism relies on the atomicity guarantee of the `SET` command in Redis single-node or cluster mode, does not introduce additional Watch-Multi transaction overhead, and is suitable for high-throughput, low-latency scenarios.

[0063] In some alternative implementations, the distributed coordination mechanism is implemented as a temporary sequential node mechanism based on the distributed coordination service. Specifically, the lock management module creates child nodes with the EPHEMERAL_SEQUENTIAL flag under a preset lock root path, such as / locks / domain / invoice-9999, with the node name format lock-0000000001, through the ZooKeeper client. Then, the client reads all child nodes under this path and sorts them in ascending order of sequence number, determining whether its own created node has the smallest sequence number; if so, the lock is successfully acquired; if not, it listens for the deletion event of the node with the previous sequence number and re-executes the judgment logic after the listener is triggered. This mechanism naturally supports automatic cleanup of session expiration and is suitable for business scenarios with higher requirements for strong consistency and tolerance for slightly higher latency.

[0064] Through the above solution, this embodiment can be compatible with the native capabilities of mainstream distributed infrastructures, and flexibly adapt to the selection of coordination services in different deployment environments without changing the upper-layer concurrency control logic. At the same time, both mechanisms can guarantee the mutual exclusion, reentrancy (verified by the client's unique identifier), and automatic release capability of the lock, avoiding deadlocks caused by abnormal client exits, and improving the robustness and maintainability of the system in complex network environments.

[0065] In one specific implementation, persistence layer consistency verification is achieved by executing conditional atomic update instructions in the database. Specifically, before calling the database driver to execute the UPDATE statement, the transaction execution module first obtains the current version identifier or previous business status bit of the target transaction object from the status pre-verification step and embeds it as a constraint condition in the WHERE clause of the SQL. Then, the transaction execution module constructs and submits the parameterized SQL statement, wherein the constraint condition includes at least one of the following forms: (i) an exact equality comparison of the version field, or a timestamp range comparison of the last_modified_time field; (ii) matching of enumerated values ​​of the status field, such as limiting status = 'INIT'; (iii) after executing the SELECT ... FOR UPDATE statement on the target data row to complete the current read lock, the subsequent change operation is executed. When executing the update command, the database engine only actually affects the corresponding row and returns the number of affected rows if the data row that meets all constraints exists and has not been modified by other concurrent transactions. The transaction execution module then captures and parses the number of affected rows returned by the database. If the value is zero, it determines that the persistence layer verification has failed and throws an OptimisticLockingFailureException or StateTransitionViolationException. If the value is greater than the expected maximum number of rows, the anti-table-flip protection mechanism is triggered, the current transaction is rolled back, and the audit log is recorded.

[0066] Subsequently, the transaction execution module obtains the actual number of affected rows returned by the database after the SQL statement is executed, and performs the following three-level judgment logic: (1) Optimistic locking failure judgment: If the actual number of affected rows is 0, it indicates that the WHERE clause did not hit any records due to version number mismatch or state not meeting the preconditions. At this time, it is judged as a concurrent conflict and throws OptimisticLockingFailureException; (2) Security defense judgment to prevent table flushing: If the actual number of affected rows is greater than the expected maximum number of rows, for example, it is expected that only 1 document will be modified, but N documents are returned, indicating that there may be defects in the WHERE condition, such as missing primary key constraints. At this time, the circuit breaker mechanism is triggered, the transaction is forced to roll back and a security alert is recorded; (3) Success judgment: Only when the actual number of affected rows is strictly equal to the expected number of rows, usually 1, is the atomic change judged to be successful and the transaction is allowed to be committed. Through the above verification, the system builds the last line of defense at the database level and completely eliminates the risk of 'dirty write'.

[0067] In other alternative implementations, the optimistic locking mechanism can use a timestamp field instead of a version number field for state comparison, where the timestamp field is defined as a BIGINT type and automatically generated by the database as a monotonically increasing logical clock value; the state machine constraint mechanism can be extended to multi-state joint verification, such as simultaneously verifying status IN ('INIT', 'PENDING') and retry_count 3; the pessimistic row locking mechanism can be further configured to use the SELECT ... FOR UPDATESKIP LOCKED syntax to avoid blocking due to waiting for locks, or in the case of database sharding and table partitioning, combine the logical table name and the physical sharding key to generate a deterministic lock hint to ensure local consistency of cross-shard operations.

[0068] Through the above solution, this embodiment enables the persistence layer consistency verification to adapt to various database capability models and business semantic constraints. Without relying on external coordination services, it utilizes the native ACID characteristics of the storage engine to form a reliable last line of defense. Compared with the prior art, this embodiment supports lightweight state transition control, is compatible with strong consistency scenarios with strict version management, and takes into account throughput performance and anomaly traceability under high concurrency.

[0069] In one specific implementation, the lock management framework employs the template method design pattern to achieve unified orchestration and scheduling of concurrent control flows. The framework defines an abstract lock execution template class, `LockTemplate`, which encapsulates a complete control flow skeleton, including key generation, multi-level locking attempts, state pre-verification, business logic execution, persistence layer consistency verification, and lock release. This template class does not directly implement any specific business logic or identifier extraction logic; instead, it completes behavior customization through two injectable interface instances: one is the `LockKeyDefinitionCallback` interface, whose implementation class is responsible for extracting and constructing key pairs at each level according to preset rules based on the metadata structure of the business request object; the other is the `BusinessCallback` interface, whose implementation class provides the `check()` method for executing state pre-verification logic and the `execute()` method for encapsulating actual business calculations and change preparation operations.

[0070] Specifically, when the system receives a business processing request, the framework first creates a `LockTemplate` instance and passes in a user-provided `LockKeyDefinitionCallback` implementation instance, such as `InvoiceRequestLockKeyCallback`, and a `BusinessCallback` implementation instance, such as `SubmitInvoiceBusinessCallback`, as constructor parameters. Then, during the execution of the template method, the framework calls the `LockKeyDefinitionCallback.generateKeys()` method to acquire three sets of lock keys, and then sequentially calls `BusinessCallback.check()` and `BusinessCallback.execute()` to complete status verification and business execution. All callback methods run within a unified execution context maintained by the template, which carries request parameters, lock holding status, transaction boundary information, and exception propagation mechanisms. The lifecycle of the template method is strictly controlled by the framework, ensuring that the reverse lock release logic defined in the `finally` block is executed unconditionally regardless of whether the business logic throws an exception.

[0071] In other alternative implementations, the template method can be implemented based on different programming paradigms: in an aspect-oriented programming (AOP) environment, the LockTemplate flow can be abstracted as around advice and triggered by annotations such as @DistributedLock; in a functional programming style, LockTemplate can be represented as a higher-order function that receives KeyGeneratorFunction and BusinessFunction as parameters; in a microservice gateway layer integration scenario, the template can be deployed as a standalone middleware component that receives standardized lock request protocol bodies via gRPC or HTTP and returns structured execution results and error codes.

[0072] Through the above solution, this embodiment can completely decouple the concurrency control process skeleton from business semantics, so that developers only need to focus on domain-related lock key definition rules and state verification logic, without having to repeatedly write infrastructure code such as locking order, timeout handling, and exception rollback; at the same time, since the template method has a stable abstraction layer and a clear interface contract, different business modules can reuse the same execution engine, significantly improving code consistency and maintainability.

[0073] In one specific implementation, the preset granularity shrinkage order is specifically configured as a three-level progressive locking process: First, a first-level distributed mutex lock is generated and attempted to be acquired based on the request dimension identifier; then, only after the first-level lock is successfully acquired, a second-level distributed mutex lock is generated and attempted to be acquired based on the business aggregation dimension identifier; next, only after the second-level lock is successfully acquired, a third-level distributed mutex lock is generated and attempted to be acquired based on the domain object dimension identifier.

[0074] Specifically, the key format of the first-level lock is lock:req:{request_id}, where {request_id} is taken from a globally unique request identifier generated by the client or injected by the gateway in the business processing request. Its TTL is set to no more than 500 milliseconds, which is used to intercept momentary duplicate requests caused by network retransmission, front-end duplicate submission or proxy layer retry. This level of lock does not undertake business semantic isolation function, but only serves as a traffic cleaning barrier.

[0075] The key format for the second-level lock is lock:biz:{tenant_id}.{hotel_id}, where {tenant_id} and {hotel_id} are the tenant logical unit and business entity belonging unit identifiers parsed from the request context, respectively. They are connected by a dot and participate in hash sharding to ensure that all requests for the same tenant-hotel combination are routed to the same distributed lock service instance. The TTL of this level of lock is dynamically calculated based on the historical call frequency and average response time of the business aggregation dimension. It is used to achieve necessary serialization within the logical isolation boundary of the tenant or merchant level to prevent operations across documents but belonging to the same business domain from violating macro constraints (such as "new documents are prohibited during daily settlement").

[0076] The key format for the third-level lock is lock:dom:{invoice_id} or lock:dom:{payment_application_id}, where {invoice_id} or {payment_application_id} is the primary key of the specific domain object to be operated on. This level of lock is directly bound to the lifecycle of the data entity, with granularity precise to a single transactional resource. It is used to block concurrent modification races on the same domain object and ensure the atomicity and traceability of state transitions.

[0077] In other alternative implementations, the first-level lock can use a time-window-based Bloom filter instead of a distributed lock to reduce the QPS pressure on Redis under high concurrency; the identifier combination of the second-level lock can be expanded to {tenant_id}.{region_id}.{service_type} to support fine-grained isolation for multiple regions and service types; the third-level lock can also automatically derive the associated lock set based on the domain model relationship. For example, when updating a payment application, a read lock can be simultaneously added to the settlement batch ID to which it belongs, thereby achieving implicit consistency protection without explicitly exposing the coupling relationship.

[0078] Through the above solution, this embodiment can achieve orthogonal decoupling and orderly coordination of request replay protection, business domain isolation and entity-level race condition control. When facing concurrent pressure from different sources, different scales and different semantic levels, the system always deploys the lightest-weight verification in advance, thereby significantly improving the invalid contention interception rate and lock resource utilization without increasing the burden on the storage layer.

[0079] In one specific implementation, based on the above embodiments, the business aggregation dimension identifier is configured as at least one of a tenant identifier (Tenant ID) or a merchant identifier (Merchant ID) extracted from the multi-tenant system operating environment. Specifically, when the system is deployed on a SaaS-based hotel settlement platform, the HTTP header carried by the request context contains the X-Tenant-ID: t-7890 field, and the lock management framework obtains the tenant identifier by parsing this header. When a business call occurs between multiple independent operating entities under the same tenant, the system further extracts merchantId: 45678 from the RPC call parameters as the merchant identifier and combines it with the tenant identifier to form a composite business aggregation key, such as lock:biz:t-7890:merchant-45678. This composite key is used for the generation and acquisition of distributed mutex locks at the second level (Business Aggregation Level).

[0080] The target transaction object is instantiated as at least one of a resource change document or an inventory record. Specifically, in the invoice submission scenario, the target transaction object is an invoice document to be processed, whose structure includes invoiceId, status, tenantId, merchantId, and skuCode fields. In the inventory deduction scenario, the target transaction object is an inventory record at the SKU level, whose primary key is composed of warehouseId, skuCode, and lotNumber. Both types of objects are mapped to corresponding data tables in a relational database and are accessed through a JDBC connection pool in the transaction execution module.

[0081] The persistent storage layer is implemented as a relational database that supports ACID transactions. Specifically, a MySQL 8.0 cluster is used as the underlying storage, with the master node enabled at the READ-COMMITTED isolation level and configured with innodb_lock_wait_timeout=50 to adapt to the distributed lock timeout strategy. All write operations involving the target transaction object are encapsulated within the database transaction declared by the @Transactional annotation, ensuring that atomic change instructions (such as UPDATE statements with version numbers or UPDATE statements with state machine constraints) are committed or rolled back within a single transaction context. In the database table structure, the invoice_document table contains a version INT NOT NULL DEFAULT 0 field for optimistic lock verification, and the inventory_record table contains a status ENUM('AVAILABLE', 'LOCKED', 'ALLOCATED') NOTNULL field for state machine constraint verification.

[0082] In other alternative implementations, the business aggregation dimension identifier may also be derived from the organization ID, channel ID, or line of business ID; the target transaction object may also correspond to account balance records, financial documents, performance task orders, or order performance status snapshots; the relational database may also be replaced with PostgreSQL 14 (with the SERIALIZABLE isolation level enabled and pessimistic row locking implemented with SELECT ... FOR UPDATESKIP LOCKED), or Oracle Database 19c (using the DBMS_LOCK package and the VERSION column to implement a hybrid locking mechanism).

[0083] Through the above scheme, this embodiment can strictly align the business aggregation dimension identifier with the logical isolation boundary in the multi-tenant architecture, so that the second-level lock naturally has the concurrent isolation capability of tenant / merchant level; at the same time, it limits the target transaction object to entity type with clear business semantics and structured persistent form, and relies on the mature relational database transaction mechanism to achieve eventual consistency guarantee, thereby ensuring the feasibility and verifiability of the layered concurrency control model in the enterprise-level production environment without introducing additional middleware dependencies.

[0084] In a comprehensive implementation, the distributed concurrency control method based on a multi-granularity hierarchical architecture of the present invention is applied to the invoice submission scenario of a hotel settlement system to solve the technical problems of multi-level concurrency conflicts and data consistency. In this implementation, the electronic device receives an invoice submission request for a specific hotel. The request parsing module first parses the request, extracting a reference identifier from the request parameters as a request dimension identifier. This reference identifier is generated by the client and has global uniqueness, used to anchor a single click behavior. The merchant identifier and company identifier in the request parameters are extracted as business aggregation dimension identifiers. The merchant identifier and company identifier together define the isolation unit of business logic, i.e., a specific hotel under a specific merchant. The invoice document identifier in the request parameters is extracted as a domain object dimension identifier. This identifier points to a unique invoice document entity in the persistent storage layer.

[0085] Subsequently, based on the parsed identifiers, the lock management module uses reflection in conjunction with a lexicographical sorting strategy to sequentially generate and acquire three layers of distributed mutex locks. Specifically, the system generates and acquires a first-layer request lock based on a reference identifier; if acquisition fails, duplicate requests are blocked. It then generates and acquires a second-layer business lock based on a combination of merchant and company identifiers to ensure that business operations for the hotel are serialized within logically isolated units. Finally, it generates and acquires a third-layer domain lock based on an invoice identifier to prevent concurrent state modifications to the invoice.

[0086] After successfully acquiring all three layers of locks, the logic control module enters the security critical section to perform a state pre-verification, querying the current status and version number of the invoice document entity in the database.

[0087] If the query results show that the current status has changed to "submitted", the system triggers idempotent processing logic, calls the preset idempotent compensation callback function to read the submitted invoice details from the database, and constructs a response result consistent with the initial successful submission, without performing subsequent change operations.

[0088] If the query results show that the current state meets the data consistency prerequisite, the transaction execution module starts a database transaction, executes an update instruction containing version number constraints, and obtains the actual number of rows affected after the database executes the update instruction. The system performs three levels of verification on the actual number of rows affected: If the actual number of rows affected is exactly equal to the expected number of rows, then the atomic change is considered successful and the transaction is committed. If the actual number of rows affected is zero, it is determined that concurrent modification occurred between the pre-verification and update, the transaction is rolled back and a concurrency conflict error is returned; If the actual number of rows affected is greater than the expected number of rows, the update conditions are determined to be abnormal or there is a risk of table flushing. The transaction is then forcibly rolled back and a security log is recorded.

[0089] Finally, regardless of whether the transaction is committed or rolled back, the system strictly releases all held distributed mutex locks in reverse order of domain lock, business lock, and request lock, thus ending the current processing flow.

[0090] This invention also provides a distributed concurrent control system based on a multi-granularity hierarchical architecture, such as... Figure 5 As shown, the system includes: The request parsing module M100 receives business processing requests for a target transaction object. In one embodiment, the business processing request is an HTTP POST request or an RPC call message, and its payload is a serialized Java object such as SubmitInvoiceRequest. This module obtains the original request object instance through deserialization. Subsequently, this module calls pre-configured feature extraction rules to perform a reflection scan on the request object, identify fields annotated with @LockKey(level = Level.REQUEST), @LockKey(level = Level.BUSINESS), and @LockKey(level = Level.DOMAIN), and extract their runtime values ​​as request dimension identifiers (e.g., requestId = "req-20240510-abc123"), business aggregation dimension identifiers (e.g., tenantId = "t-8888"), and domain object dimension identifiers (e.g., invoiceId = "inv-9999"), respectively. In other optional embodiments, the feature extraction rules can also be implemented using JSON path expressions such as... .header.requestId, The `.body.tenantId` identifier is extracted from the structured message body or automatically obtained through Spring MVC's `@PathVariable` / `@RequestParam` metadata binding. In another embodiment, to simplify development, the system does not rely on explicit annotations. The key generation module scans all non-empty fields of the request object using reflection, directly arranging them lexicographically by field name, and then uses reflection to retrieve the field values ​​for concatenation. This approach is suitable for business objects with simple field structures, eliminating the need to intrude into business code by adding annotations.

[0091] The lock management module M200 is used to generate distributed mutex lock keys at each level based on request dimension identifiers, business aggregation dimension identifiers, and domain object dimension identifiers. It then uses these lock keys to attempt to acquire locks in a preset order through a distributed coordination mechanism. In one embodiment, the module generates three sets of lock keys by concatenating the hierarchical prefixes `lock:req:`, `lock:biz:`, and `lock:dom:` with their corresponding identifiers, such as `lock:req:req-20240510-abc123`, `lock:biz:t-8888`, and `lock:dom:inv-9999`. The distributed coordination mechanism uses the Redis `SETNX` command with the `EX` option to achieve atomic locking with TTL. After the lock keys are generated, the module sequentially calls `tryLock(key, ttl, ...` The TimeUnit.SECONDS interface is used, and the request to acquire the next level lock is only initiated after the current level lock is successfully acquired; in some other optional implementations, the distributed coordination mechanism is replaced by ZooKeeper's temporary sequential node creation and minimum node competition mechanism, or Etcd's Compare-and-Swap (CAS) lease mechanism; the preset granularity shrinkage order is fixed as: first level (request dimension) → second level (business aggregation dimension) → third level (domain object dimension).

[0092] In traditional development, lock keys are typically manually concatenated by developers, such as `String key = "lock:" + id;`. This approach is problematic when the field order is inconsistent; for example, A might be concatenated as `tenant+user` while B is concatenated as `user+tenant`, leading to different lock keys for the same resource and causing the lock to become invalid. This embodiment uses reflection combined with lexicographical ordering to enforce the physical arrangement of fields, fundamentally eliminating lock escape problems caused by differences in coding habits.

[0093] The logic control module M300 is used to trigger the state pre-verification step after the lock management module M200 successfully acquires all three layers of distributed mutex locks. In one embodiment, this module calls the injected BusinessCallback.check() method, which constructs an SQL query statement SELECT status, version FROM invoice WHERE id = ?, reads the target transaction object from the main database, such as the latest persistent status of the invoice record, and compares whether the status field is equal to INIT and whether the version field is equal to the expected version number carried in the request context. If either condition is not met, the pre-verification is deemed to have failed. In some other optional implementations, the state verification data source can be extended to a caching layer, such as a status snapshot cached in Redis with the key invoice:status:inv-9999, and the source database is retrieved when the cache is not hit. The comparison logic also supports compound conditions, such as (status IN ('INIT', 'PENDING')) AND (modified_time ?).

[0094] The transaction execution module M400 is used to execute business logic after the state pre-verification passes, and to perform atomic change operations including consistency checks in the persistent storage layer. In one embodiment, the module calls BusinessCallback.execute() to complete non-persistent logic such as invoice amount calculation and approval flow triggering, and then starts a database transaction to execute an update statement with optimistic locking constraints: UPDATE invoice SET status = 'SUBMITTED', amount = ?, version = version + 1 WHERE id = ? AND version = ?. Before the transaction is committed, the module checks the number of affected rows returned by the SQL execution. If it is 0, an OptimisticLockingFailureException is thrown; if it is 1, the transaction is committed. In some other optional implementations, consistency checks are replaced with state machine-constrained SQL: UPDATE invoice SET status = 'SUBMITTED' WHERE id = ? AND status = 'INIT'; or replaced with database pessimistic row locks: SELECT FROM invoice WHERE id = ? FOR UPDATE is executed at the beginning of the transaction.

[0095] The four modules mentioned above are coupled through a standardized interface: the three types of identifiers output by the request parsing module M100 are injected as key-value pairs into the unified execution context; the lock management module M200 reads the identifiers from this context and generates a lock key, and the locking result is fed back to the logic control module M300 in the form of a Boolean signal; the logic control module M300 issues an execution instruction or a termination signal to the transaction execution module M400 based on the pre-verification result; after completing the atomic change, the transaction execution module M400 notifies the lock management module M200 to enter the release process through a callback, and the latter calls the unlock() interface in reverse order of lock:dom:→lock:biz:→lock:req: to release the lock.

[0096] These technical features work together to form a closed-loop, layered concurrency control chain: the request parsing module M100 maps business semantics to structured identifiers, providing the input basis for subsequent layered locking; the lock management module M200 generates deterministic and reproducible lock keys based on this input, and filters out a large amount of invalid contention traffic at the system entry point through a funnel-style step-by-step locking strategy; the logic control module M300 performs state pre-verification while holding all locks, ensuring that business rule checks occur within a strongly consistent critical section, avoiding state drift caused by network latency or lock timeout; the transaction execution module M400 anchors the final data changes to the database ACID guarantees and ensures that optimistic locking has not been bypassed by verifying the number of affected rows. This collaborative approach addresses the fundamental contradictions in existing technologies: the conflict between lock granularity and performance, reliability and consistency, management complexity and code coupling, and the lack of a "double-judgment" defense mechanism. Four-layer identifier resolution and layered lock key generation enable dynamic adaptation of lock granularity; a funnel-shaped locking sequence and reverse release mechanism ensures controllability and predictability of resource usage; dual verification of state pre-verification and persistence layer provides redundant protection, compensating for the inherent weak consistency defects of distributed coordination middleware; and the loosely coupled interface-based design between modules completely separates the lock logic from the business code, eliminating the maintenance risks and human errors associated with hard-coded lock keys.

[0097] Through the above solution, this embodiment can achieve synergistic optimization of strong data consistency and system throughput in high-concurrency scenarios: the request layer and business aggregation layer complete lightweight interception within milliseconds, reducing the pressure on the data layer by more than 90% of invalid requests; the domain object layer accurately locks business entities to avoid excessive serialization; the persistent storage layer relies on the database's native mechanism to ensure linear consistency is still met in extreme cases; at the same time, the unified modular architecture significantly reduces the cognitive load and implementation cost of developers in concurrency control, and improves the overall robustness and evolvability of the system.

[0098] This invention provides an electronic device, including a memory, a processor, and a computer program stored in the memory and executable on the processor. The electronic device includes: One or more processors; One or more memories on which computer program instructions are stored; The processor is configured to execute computer program instructions, and when the processor executes the computer program, it implements the distributed concurrency control method based on a multi-granularity hierarchical architecture as described in any of the above embodiments.

[0099] Through the above solution, this embodiment can build a distributed transaction control system with adaptive concurrency control capabilities on a general-purpose server hardware platform in a modular and configurable manner. Compared with the prior art, this embodiment significantly improves the success rate of processing legitimate business requests per unit time without adding dedicated middleware; reduces the proportion of thread blocking caused by unreasonable lock granularity; reduces runtime errors caused by manually splicing lock keys; and maintains link availability under sudden traffic surges through dynamic TTL and load-aware degradation mechanisms, thereby achieving a Pareto optimal balance between throughput and consistency in complex enterprise-level business scenarios.

[0100] This invention provides a computer-readable storage medium storing a computer program that, when executed by a processor, implements the distributed concurrency control method based on a multi-granularity hierarchical architecture as described above.

[0101] Through the above solution, this embodiment can build configurable, scalable, and verifiable distributed concurrency control capabilities in a software-defined manner. Without modifying the underlying infrastructure, it can significantly reduce the risk of data anomalies caused by lock misuse and improve the system's stable throughput and end-to-end transaction success rate in typical high-load scenarios such as flash sales, daily settlements, and batch invoicing.

[0102] The above description, in conjunction with specific preferred embodiments, provides a further detailed explanation of the present invention. It should not be construed that the specific implementation of the present invention is limited to these descriptions. For those skilled in the art, various simple deductions or substitutions can be made without departing from the concept of the present invention, and all such modifications and substitutions should be considered within the scope of protection of the present invention.

Claims

1. A distributed concurrency control method based on a multi-granularity hierarchical architecture, characterized in that, The method is performed by an electronic device and includes the following steps: Receive a business processing request for a target transaction object, and parse the request dimension identifier, business aggregation dimension identifier, and domain object dimension identifier from the business processing request according to the pre-configured feature identifier extraction rules; Based on the request dimension identifier, the business aggregation dimension identifier, and the domain object dimension identifier, corresponding distributed mutex lock keys are generated for each level. Using the generated distributed mutex keys at each level, attempt to acquire the distributed mutex keys at each level in sequence according to the preset granularity shrinkage order; After successfully acquiring all the distributed mutex locks at the preset levels, the state pre-verification step is performed: query the current state of the target transaction object and determine whether the current state meets the data consistency precondition of the business processing request; If the state pre-verification step passes, the corresponding business logic is executed, and an atomic change operation is performed on the target transaction object in the persistent storage layer; the atomic change operation includes consistency verification based on data state and verification of the actual number of rows affected by the change operation; When the atomic change operation is completed or when an exception occurs during the atomic change operation, the distributed mutexes at each level are released.

2. The method according to claim 1, characterized in that, The atomicity change operation specifically includes: Construct a database update command that includes state constraints; Execute the database update command and obtain the actual number of rows affected returned by the database; Determine whether the actual number of rows affected is consistent with the expected number of rows; If the actual number of rows affected is greater than the expected maximum number of rows, or if the actual number of rows affected is inconsistent with the expected number of rows, then concurrency control is deemed to have failed and a transaction rollback is triggered.

3. The method according to claim 1, characterized in that, The step of parsing the identifier from the business processing request according to the pre-configured feature identifier extraction rules and generating the corresponding level of distributed mutex key specifically includes: Obtain the lock key definition interface instance corresponding to the business processing request; Using at least one of reflection mechanism and metadata parsing technology, extract field values ​​corresponding to the request dimension identifier, the business aggregation dimension identifier and the domain object dimension identifier respectively from the business processing request based on the lock key definition interface instance; The extracted field values ​​are sorted according to a preset lexicographical order; Using a preset separator, the hierarchical prefix, business type identifier, and sorted field values ​​are concatenated to generate the distributed mutex key.

4. The method according to claim 1, characterized in that, The state pre-verification step specifically includes: Read the latest persistent data of the target transaction object from the persistent storage layer; compare the version identifier or status bit in the latest persistent data with the preconditions in the business processing request; If the comparison results are inconsistent, the state pre-verification step is determined to have failed, and it is further determined whether the current state indicates that the business processing request has been executed. If the determination has already been executed, then an idempotent response result is constructed and returned directly, without executing the subsequent business logic and atomic change operation.

5. The method according to claim 1, characterized in that, The specific configuration for the step of sequentially attempting to acquire distributed mutex locks at each level is as follows: A fast-fail strategy is adopted; if the acquisition of the distributed mutex lock at any level fails, the acquisition attempts of the distributed mutex lock at subsequent levels are immediately terminated, the state pre-verification step is not entered, and a concurrency processing failure response is returned to the caller.

6. The method according to claim 1, characterized in that, It also includes an exception rollback step: If the state pre-verification step fails, or if an exception occurs during the execution of the business logic, a compensation mechanism is triggered. The compensation mechanism releases all currently held distributed mutexes in reverse order of the order in which they were acquired.

7. The method according to claim 1, characterized in that, The distributed mutex lock has a valid lifetime, which is not a fixed value, but is dynamically set in the following way: Obtain the historical average processing time for the business type to which the business processing request belongs; The effective survival time is calculated by adding a preset buffer time to the historical average processing time. When attempting to acquire the distributed mutex lock, the calculated effective lifetime is passed as a parameter to the distributed coordination mechanism.

8. A distributed concurrent control system based on a multi-granularity hierarchical architecture, characterized in that, include: The request parsing module is used to receive business processing requests for target transaction objects and use pre-configured feature extraction rules to parse the request dimension identifier, business aggregation dimension identifier, and domain object dimension identifier from the business processing requests. The lock management module is used to generate distributed mutex lock keys at each level based on the feature identification extraction rules, and to use the distributed mutex lock keys to attempt to acquire distributed mutex locks at each level in a predetermined granularity shrinkage order through a distributed coordination mechanism. The logic control module is used to perform a state pre-verification step after the lock management module successfully acquires all the distributed mutex locks of the preset level, that is, to query the current state of the target transaction object and determine whether the current state meets the data consistency precondition. The transaction execution module is used to execute the corresponding business logic after the state pre-verification step passes, and to perform an atomic change operation containing consistency verification on the target transaction object in the persistent storage layer, and to verify the actual number of rows affected by the change operation, and to trigger lock release when the operation is completed or an exception occurs.

9. An electronic device comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, characterized in that, When the processor executes the computer program, it implements the method as described in any one of claims 1 to 7.

10. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by a processor, it implements the method as described in any one of claims 1 to 7.