A real-time account balance calculation method and device based on a lock-free ring buffer, equipment, medium and product
By using a lock-free circular buffer and CAS atomic operations, the lock contention problem in account balance calculation under high concurrency scenarios is solved, achieving efficient transaction processing and regulatory auditing capabilities, and improving the system's throughput and response speed.
Patent Information
- Application Number
- CN202611453246.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-09-18
- Publication Date
- 2026-11-27
AI Technical Summary
Existing account balance calculation methods can lead to decreased system throughput and increased response latency due to lock contention in high-concurrency scenarios, potentially causing deadlocks and failing to meet the requirements of financial regulatory audits.
By employing a lock-free circular buffer and CAS atomic operations, transaction requests are transformed into event objects and written to the circular buffer. A single consumer thread updates the account balance and writes the data to the transaction log table in batches when a preset threshold or time window expires, thus avoiding database lock contention.
It achieves massive transaction processing per second in high-concurrency scenarios, meets financial regulatory audit requirements, maintains a stable response time in the millisecond range, and eliminates lock contention bottlenecks.
Smart Images

Figure CN123178418A_ABST
Abstract
Description
Technical Field
[0001] The present invention relates to the field of computer technology, and in particular to a method, apparatus, device, medium and product for calculating real-time account balance based on a lock-free circular buffer. Background Technology
[0002] Current account balance calculations largely rely on database row locks or table locks for concurrency safety. A typical approach is to execute the statement "UPDATE account SET balance = balance + amount WHERE id = ?" for each transaction. The database then locks the corresponding row record using SELECT FOR UPDATE, and releases the lock after the amount is increased or decreased. This method works well in low-concurrency scenarios, but as transaction volume increases, numerous requests compete for the same row lock, leading to a sharp drop in system throughput, a significant increase in response latency, and in severe cases, potentially causing database deadlocks. Summary of the Invention
[0003] This invention provides a method, apparatus, device, medium, and product for real-time account balance calculation based on a lock-free circular buffer, which can eliminate database lock contention, achieve massive transaction processing per second in high-concurrency scenarios, and meet financial regulatory audit requirements.
[0004] According to one aspect of the present invention, a method for calculating real-time account balances based on a lock-free circular buffer is provided, comprising: Receive transaction requests and convert them into event objects; the event objects contain the identifier, amount, event type, and event sequence number of each account corresponding to the transaction request; The event object is written to a pre-allocated circular buffer; the write operation is implemented by comparing and swapping atomic variables using CAS increment; the write operation is non-blocking. A single consumer thread retrieves events from the circular buffer, reads the memory snapshot of each account corresponding to the event, calculates the balance of each account, and updates the account balance through CAS atomic operations. When the number of events in the circular buffer exceeds a preset threshold, or when the time window expires, the events in the circular buffer are written to the append-only transaction log table in a batch.
[0005] According to another aspect of the present invention, a real-time account balance calculation apparatus based on a lock-free circular buffer is provided, the apparatus comprising: The receiving and conversion module is used to receive transaction requests and convert the transaction requests into event objects; the event objects contain the identifier, amount, event type, and event sequence number of each account corresponding to the transaction request; The first write module is used to write the event object into a pre-allocated circular buffer; the write operation is implemented by comparing and swapping atomic variables using CAS increment; the write operation is non-blocking. The read and calculate module is used to retrieve events from the circular buffer using a single consumer thread, read the memory snapshot of each account corresponding to the event, calculate the balance of each account, and update the account balance through CAS atomic operations; The second write module is used to write the events in the circular buffer into the append-only transaction log table in one batch when the number of events in the circular buffer exceeds a preset threshold, or when the time window expires.
[0006] According to another aspect of the present invention, an electronic device is provided, the electronic device comprising: At least one processor; and A memory communicatively connected to the at least one processor; wherein, The memory stores a computer program that can be executed by the at least one processor, which enables the at least one processor to perform the real-time account balance calculation method based on a lock-free circular buffer as described in any embodiment of the present invention.
[0007] According to another aspect of the present invention, a computer-readable storage medium is provided, the computer-readable storage medium storing computer instructions for causing a processor to execute and implement the real-time account balance calculation method based on a lock-free circular buffer as described in any embodiment of the present invention.
[0008] According to another aspect of the present invention, embodiments of the present invention also provide a computer program product, the computer program product including a computer program, which, when executed by a processor, implements the real-time account balance calculation method based on a lock-free circular buffer as described in any embodiment of the present invention.
[0009] This invention receives transaction requests and transforms them into event objects. Each event object contains the identifier, amount, event type, and event sequence number of each account corresponding to the transaction request. The event objects are written to a pre-allocated circular buffer. The write operation is implemented through atomic variable comparison and swapping (CAS) incrementing. The write operation is non-blocking. A single consumer thread retrieves events from the circular buffer, reads the memory snapshot of each account corresponding to the event, calculates the balance of each account, and updates the account balance through CAS atomic operations. When the number of events in the circular buffer exceeds a preset threshold, or when the time window expires, the events in the circular buffer are written to an append-only transaction log table in batches. This invention eliminates database lock contention, enabling high-concurrency scenarios with massive transaction processing per second while meeting financial regulatory audit requirements.
[0010] It should be understood that the description in this section is not intended to identify key or essential features of the embodiments of the present invention, nor is it intended to limit the scope of the invention. Other features of the invention will become readily apparent from the following description. Attached Figure Description
[0011] To more clearly illustrate the technical solutions of the embodiments of the present invention, the accompanying drawings used in the embodiments will be briefly introduced below. It should be understood that the following drawings only show some embodiments of the present invention and should not be regarded as a limitation on the scope. For those skilled in the art, other related drawings can be obtained based on these drawings without creative effort.
[0012] Figure 1 This is a flowchart of a real-time account balance calculation method based on a lock-free circular buffer, as described in an embodiment of the present invention. Figure 2 This is a schematic diagram of the structure of a real-time account balance calculation device based on a lock-free circular buffer according to an embodiment of the present invention; Figure 3 This is a schematic diagram of the structure of an electronic device that implements the real-time account balance calculation method based on a lock-free circular buffer according to an embodiment of the present invention. Detailed Implementation
[0013] To enable those skilled in the art to better understand the present invention, the technical solutions of the present invention will be clearly and completely described below with reference to the accompanying drawings of the embodiments of the present invention. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort should fall within the scope of protection of the present invention.
[0014] It should be noted that the terms "first," "second," etc., in the specification, claims, and accompanying drawings of this invention are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence. It should be understood that such data can be interchanged where appropriate so that the embodiments of the invention described herein can be implemented in orders other than those illustrated or described herein. Furthermore, the terms "comprising" and "having," and their derivatives, are intended to cover non-exclusive inclusion; for example, a process, method, system, product, or apparatus that comprises a series of steps or units is not necessarily limited to those steps or units explicitly listed, but may include other steps or units not explicitly listed or inherent to such processes, methods, products, or apparatus.
[0015] It is understood that before using the technical solutions disclosed in the various embodiments of this disclosure, users should be informed of the types, scope of use, and usage scenarios of the personal information involved in this disclosure in an appropriate manner in accordance with relevant laws and regulations, and user authorization should be obtained.
[0016] Example 1 The core flaws of existing technologies are as follows: Defect 1) Lock contention leads to a linear decrease in throughput: When the number of concurrent transactions increases from 100 / second to 10,000 / second, the waiting time for database row locks increases from milliseconds to seconds, and the system throughput decreases instead of increasing. During peak financial periods (such as the opening of trading days and the end-of-month settlement), lock waiting may account for more than 99% of the processing time.
[0017] Defect 2) Deadlock risk: When multiple accounts are involved in the transfer (such as transferring from account A to account B and from account B to account C at the same time), the inconsistent lock acquisition order may lead to circular waiting, triggering database deadlock detection and forced rollback, which will affect business continuity.
[0018] Defect 3) Query and update are mutually exclusive: Querying the balance also requires acquiring a lock or reading a committed data version, which slows down the query response during high-concurrency writes.
[0019] Defect 4) Insufficient audit granularity: The database only stores the final balance and cannot trace the impact of each transaction on the balance, which is not conducive to regulatory auditing.
[0020] This invention discloses a real-time account balance calculation method based on a lock-free ring buffer. This method transforms each transaction into a lightweight event object, which is written to a high-performance ring buffer in a non-blocking manner. It employs a single consumer thread model and utilizes CAS (Compare-And-Swap) CPU (Central Processing Unit) atomic instructions to update the memory balance snapshot, completely eliminating database row lock contention. Events are persisted to the transaction log table (acct_evt_log) through append-only batch INSERT statements, avoiding lock conflicts caused by UPDATE operations. Query requests directly read from the memory snapshot or Redis (Redis is an open-source, high-performance key-value database with in-memory storage and persistence support, commonly used for caching, message queues, real-time statistics, etc.), with a stable response time in the millisecond range. The system provides a dead-letter queue, compensation tasks, and a fault-tolerant recovery mechanism of snapshot + log replay to ensure the processing capacity of tens of thousands of transactions per second and complete change auditing capabilities in high-concurrency scenarios.
[0021] Figure 1 This is a flowchart illustrating a real-time account balance calculation method based on a lock-free circular buffer, as described in this embodiment of the invention. This embodiment is applicable to real-time account balance calculation based on a lock-free circular buffer. The method can be executed by the real-time account balance calculation device based on a lock-free circular buffer as described in this embodiment of the invention. This device can be implemented in software and / or hardware, such as... Figure 1 As shown, the method specifically includes the following steps: S101. Receive the transaction request and convert it into an event object.
[0022] For example, a transaction request may be a request for a financial transaction such as a deposit, withdrawal, or transfer initiated by a user on a smart terminal.
[0023] The event object includes the identifier (such as account ID), amount, event type (such as deposit, withdrawal or transfer) of each account corresponding to the transaction request, and event sequence number (the sequence number is globally unique).
[0024] Specifically, in this embodiment, transactions are event-based. After each transaction completes business verification (such as account status check and limit check) at the business layer, the database balance is not updated directly. Instead, a lightweight event object (containing account ID, transaction amount, event type (such as deposit, withdrawal or transfer)) is constructed, and a globally unique event sequence number is generated.
[0025] S102. Write the event object to the pre-allocated circular buffer.
[0026] As we know, a circular buffer is a fixed-size circular data structure that reuses memory space by having pointers at the beginning and end, thus achieving efficient data reading and writing.
[0027] The write operation is implemented by comparing and swapping atomic variables using CAS increment; the write operation is non-blocking.
[0028] As we know, CAS is an abbreviation for Compare-And-Swap. It is an atomic operation and the core mechanism for achieving lock-free concurrent programming. Compare-And-Swap is a CPU-level atomic instruction that does not involve operating system-level locks or context switching. Compared to the millisecond-level overhead of database row locks, CAS operations are completed in nanoseconds, resulting in a performance improvement of three orders of magnitude.
[0029] Specifically, the event object is written to a high-performance ring buffer. The write operation is non-blocking and completes in microseconds.
[0030] S103. Use a single consumer thread to retrieve events from the circular buffer, read the memory snapshot of each account corresponding to the event, calculate the balance of each account, and update the account balance through CAS atomic operations.
[0031] As we know, a single consumer thread is a thread model design in concurrent programming, meaning that only one thread in the system is responsible for reading and processing data from a shared buffer / queue, in contrast to the possibility of multiple producer threads. In this embodiment, it can also be referred to as a single consumer thread.
[0032] In this implementation, the account balance is updated using a single-consumer atomic update, and the circular buffer uses a single consumer thread model. Specifically, after retrieving an event from the circular buffer, the consumer thread reads the memory snapshot of the corresponding account and updates the balance using a CAS atomic operation. The core logic is: read the current snapshot → calculate the new balance → atomically compare and replace; if the CAS fails, it spins and retryes, without lock-free waiting. This process is entirely lock-free, ensuring pure CPU instruction-level concurrency safety.
[0033] In traditional solutions, lock contention is the root cause of performance bottlenecks under high concurrency. This invention eliminates lock contention fundamentally by converting transactions into events, moving update operations to memory, and replacing database locks with CAS (Compare-and-Swap). The circular buffer decouples the producer (business thread) and consumer (update thread), allowing producers to write without waiting and consumers to process data serially, thus avoiding concurrency conflicts.
[0034] S104. When the number of events in the circular buffer exceeds the preset threshold, or when the time window expires, write the events in the circular buffer into the append-only transaction log table in one batch.
[0035] The preset threshold can be a pre-set number of events based on actual needs or experience. When the cumulative events in the circular buffer reach this threshold, the events are written to the append-only transaction log table (acct_evt_log) in batches. This embodiment does not specifically limit the preset threshold and can be dynamically adjusted. Preferably, the preset threshold can be set to 1000 records.
[0036] The time window can be a pre-set time period based on actual needs or experience. Each time this time elapses, events are written in batches to the append-only transaction log table (acct_evt_log). This embodiment does not impose a specific limitation on the time window and can adjust it dynamically. Preferably, the time window can be set to 100 milliseconds.
[0037] In practice, events in the circular buffer are persisted in batches according to the set rules. For example, when the cumulative number of events reaches a preset threshold (e.g., 1000) or the time window expires (e.g., 100 milliseconds), the events are written to the append-only transaction log table (acct_evt_log) in one batch.
[0038] By merging 1000 events into a single batch INSERT, database I / O operations are reduced by 1000 times compared to the traditional approach of updating every transaction. Append-only writes avoid UPDATE operations, preventing database-level lock contention and fully leveraging the database's batch write optimizations. A scheduled task writes a memory snapshot to a persistent snapshot table (acct_snapshot) for rapid recovery.
[0039] This invention receives transaction requests and transforms them into event objects. Each event object contains the identifier, amount, event type, and event sequence number of each account corresponding to the transaction request. The event objects are written to a pre-allocated circular buffer. The write operation is implemented through atomic variable comparison and swapping (CAS) incrementing. The write operation is non-blocking. A single consumer thread retrieves events from the circular buffer, reads the memory snapshot of each account corresponding to the event, calculates the balance of each account, and updates the account balance through CAS atomic operations. When the number of events in the circular buffer exceeds a preset threshold, or when the time window expires, the events in the circular buffer are written to an append-only transaction log table in batches. This invention eliminates database lock contention, enabling high-concurrency scenarios with massive transaction processing per second while meeting financial regulatory audit requirements.
[0040] Optionally, the method further includes: Exceptions that fail to be processed are written to a dead-letter queue and reprocessed periodically by a background compensation task.
[0041] As we know, a dead-letter queue is a special queue used to store messages that cannot be processed normally.
[0042] In this embodiment, a fault tolerance and recovery mechanism is set up. Specifically, abnormal events that cause transaction processing failures (such as non-existent accounts or abnormal amounts) are written to a dead letter queue, which is periodically reprocessed by a background compensation task without blocking the main flow of data.
[0043] When the system restarts abnormally, the most recent persistent snapshot is loaded, all unwritten logs are replayed from the snapshot number backwards, and memory snapshots of all accounts are rebuilt.
[0044] As we know, a persistent snapshot is a static copy of the complete state data (account-related data in this embodiment) at a certain moment in memory, which is written to persistent storage (disk, SSD, database table) to form a checkpoint that can be retained for a long time.
[0045] Among them, the unwritten logs are log records that have been generated and entered into the memory buffer (a circular buffer in this embodiment), but have not yet been written to persistent storage (disk, database table).
[0046] In actual operation, when the system restarts abnormally, all account snapshots are restored from the most recent persistent snapshot and unwritten logs to ensure that no business data is lost.
[0047] Specifically, when the system restarts abnormally, the most recent persistent snapshot is loaded, and all unwritten logs are replayed from the snapshot number backwards to rebuild a complete memory snapshot. The entire process is completed in seconds, without any impact on the business.
[0048] Optionally, the circular buffer is implemented using a pre-allocated fixed array, with pointers to the producer and consumer managed by two atomic variables, respectively.
[0049] When the circular buffer is detected to be full, write operations are blocked and a failure message is returned (i.e., a message indicating a write failure), triggering a backpressure notification so that the upstream system can degrade or reject new requests to prevent memory overflow.
[0050] As we know, backpressure notification is a flow control mechanism used to send a slowdown or blocking signal to the upstream when the downstream processing capacity of the system is insufficient, in order to prevent data accumulation from causing memory overflow, latency spikes or system crashes.
[0051] The technical solution of this invention uses a dead-letter queue to ensure that abnormal events are not lost, snapshots and log replay to ensure that the system recovers within seconds after a restart, and backpressure notifications to ensure that the system does not overflow memory under high load. This three-layer fault-tolerance mechanism guarantees the high availability of the system.
[0052] Optionally, the method further includes: When a balance query request is received (where the balance query request can be a request to query the latest account balance): Read the memory snapshot of the target account to obtain the latest balance of the target account.
[0053] The target account is the account whose balance is to be queried. Preferably, the balance query request carries the identification information of the account whose balance is to be queried. The target account is determined based on the identification information, and then the latest balance of the target account is queried and displayed.
[0054] Specifically, when a balance query request is received, the system first reads a memory snapshot (lock-free read, nanosecond level) to obtain the latest balance of the target account.
[0055] If a memory miss occurs, the latest balance of the target account is retrieved from the Redis cache.
[0056] Specifically, if a memory miss occurs, i.e., the memory snapshot read fails, the latest balance of the target account is read from the Redis cache (millisecond level).
[0057] If the Redis cache misses, the latest balance of the target account is recovered from the most recent persistent snapshot and unwritten log replay.
[0058] Specifically, if a Redis cache miss occurs, meaning a Redis cache read fails, the system recovers from the most recent persistent snapshot and unwritten log replay to obtain the latest balance of the target account, with a response time consistently in the millisecond range.
[0059] Otherwise, return a query failure message.
[0060] Among them, the query failure message can be used to notify the user that the balance query failed.
[0061] Specifically, if all three levels of queries fail, a query failure message will be returned to the user, indicating that the query failed.
[0062] In this embodiment, the balance query first reads the memory snapshot (lock-free read), if the cache misses, it reads the Redis cache, and if the cache misses again, it recovers from the snapshot plus log replay. This three-level query architecture ensures that the query response time is stable at the millisecond level, unaffected by the write concurrency.
[0063] Optionally, events in the circular buffer can be written to the append-only transaction log table in a batch, including: Combine all events in the circular buffer into a single batch insert statement.
[0064] In this embodiment, a single batch insert statement can be, for example, an INSERT statement, which is used to insert new data into a database table.
[0065] Specifically, in batch persistence operations, multiple events are merged into a single batch INSERT statement, and the INSERTONLY operation avoids row lock contention.
[0066] Perform an append-only transaction log table insertion operation based on a single batch insert statement.
[0067] In the actual implementation, events can be persisted to the transaction log table (acct_evt_log) through append-only batch INSERT, avoiding lock conflicts caused by UPDATE operations.
[0068] In practice, the scheduled task periodically writes memory snapshots to a persistent snapshot table for rapid recovery. The snapshot table retains the most recent N versions (which can be set and dynamically adjusted as needed), supporting recovery by point in time.
[0069] Optionally, the event sequence number adopts a globally incrementing allocation mechanism to ensure that the processing order of events is consistent with the generation order.
[0070] When CAS updates, it checks the continuity of event sequence numbers. If a jump in event sequence number is detected, an exception alarm is triggered to prevent event loss.
[0071] As an exemplary description of an embodiment of the present invention, when processing a single transfer transaction, for example, in an application scenario where user A transfers 100 yuan to user B, and the system concurrency is 5000 TPS (Transactions Per Second), the following operations are performed based on the method of this embodiment: Step a) Business verification: Check whether the status of account A is normal and whether the balance is sufficient (≥100 yuan), and check whether the status of account B is normal, and then generate a globally unique event sequence number, such as seq=100001. Step b) Event publishing: Construct Event(A,-100,DEBIT,seq) and Event(B,+100,CREDIT,seq+1), and then write them to the Ring Buffer using CAS (completed in microseconds). Step c) Consumption processing: The consumer retrieves the two events, updates the snapshot of account A with CAS: balance:5000→4900, and updates the snapshot of account B with CAS: balance:3000→3100. Step d) Batch persistence: Once a batch of 1000 records is reached, batch INSERT to acct_evt_log, and finally commit the transaction to complete the persistence.
[0072] As an exemplary description of an embodiment of the present invention, in a high-concurrency scenario (10000 TPS), such as during a flash sale, the same account (account C) receives 1000 transactions per second. Traditional solution (database row lock): 1000 threads compete for the same row lock, average waiting time: 50~500ms, actual throughput: <500TPS (lock contention bottleneck). The solution of this embodiment (lock-free CAS): 1000 producer threads perform CAS writes to the Ring Buffer (non-blocking), a single consumer processes serially, CAS updates the snapshot of account C, and CAS failures are retries via spin (average retries <3 times), actual throughput: >50000TPS (limited by memory bandwidth), performance comparison: throughput increased by 100 times, response latency reduced from 50ms to <1ms.
[0073] As an exemplary description of an embodiment of the present invention, when the system abnormally restarts and recovers, such as in the scenario described as a sudden system crash during operation, and needs to be quickly restored to the state before the crash, the recovery process can be described as follows: 1. Read the most recent persistent snapshot (snapshot_time=2026-05-0612:00:00, balance_A=5000); 2. Scan all events after snapshot_seq (=5800) in acct_evt_log; 3. Replay events: -Event(seq=5801, account=A, amount=+200)→balance_A=5200 -Event(seq=5802, account=B, amount=-50)→balance_B=2950...; 4. Rebuild the memory snapshot, and the service is restored. Total recovery time: <3 seconds (replaying 1 million log entries).
[0074] The technical solution of this invention provides a lock-free, event-driven real-time account balance calculation method, which eliminates database lock contention and enables the processing of tens of thousands of transactions per second in high-concurrency scenarios while maintaining millisecond-level query response and complete change auditing capabilities.
[0075] Example 2 Figure 2 This is a schematic diagram of a real-time account balance calculation device based on a lock-free circular buffer, according to an embodiment of the present invention. This embodiment is applicable to real-time account balance calculation based on a lock-free circular buffer. The device can be implemented in software and / or hardware, and can be integrated into any device that provides real-time account balance calculation functionality based on a lock-free circular buffer, such as… Figure 2 As shown, the real-time account balance calculation device based on a lock-free circular buffer specifically includes: a receiving and conversion module 201, a first writing module 202, a reading and calculation module 203, and a second writing module 204.
[0076] The receiving and conversion module 201 is used to receive transaction requests and convert the transaction requests into event objects; the event objects include the identifier, amount, event type, and event sequence number of each account corresponding to the transaction request; The first writing module 202 is used to write the event object into a pre-allocated circular buffer; the writing operation is implemented by comparing and swapping atomic variables using CAS increment; the writing operation is non-blocking. The read and calculate module 203 is used to retrieve events from the circular buffer using a single consumer thread, read the memory snapshot of each account corresponding to the event, calculate the balance of each account, and update the account balance through CAS atomic operations; The second writing module 204 is used to write the events in the circular buffer into the append-only transaction log table in one batch when the number of events in the circular buffer is greater than a preset threshold, or when the time window expires.
[0077] Optionally, the device is further specifically used for: Exceptions that fail to be processed are written to a dead-letter queue and reprocessed periodically by a background compensation task. When the system restarts abnormally, the most recent persistent snapshot is loaded, all unwritten logs are replayed from the snapshot number backwards, and memory snapshots of all accounts are rebuilt.
[0078] Optionally, the circular buffer is implemented using a pre-allocated fixed array, and pointers to the producer and consumer are managed by two atomic variables respectively; When the circular buffer is detected to be full, the write operation is blocked and a failure message is returned, triggering a backpressure notification so that the upstream system can degrade or reject new requests.
[0079] Optionally, the device is further specifically used for: When a balance query request is received: Read the memory snapshot of the target account corresponding to the balance query to obtain the latest balance of the target account; If a memory miss occurs, the latest balance of the target account is retrieved from the Redis cache. If the Redis cache misses, the latest balance of the target account is recovered from the most recent persistent snapshot and unwritten log replay. Otherwise, return a query failure message.
[0080] Optionally, the second writing module 204 is specifically used for: Merge all events in the circular buffer into a single batch insert statement; The operation of inserting into the append-only transaction log table is performed based on the single batch insert statement.
[0081] Optionally, the event sequence number adopts a globally incrementing allocation mechanism to ensure that the processing order of events is consistent with the generation order; When CAS updates, it verifies the continuity of the event sequence number. If a jump in the event sequence number is detected, an abnormal alarm is triggered.
[0082] The above-mentioned product can execute the real-time account balance calculation method based on a lock-free circular buffer provided in any embodiment of the present invention, and has the corresponding functional modules and beneficial effects of the execution method.
[0083] Example 3 Figure 3A schematic diagram of an electronic device 30 that can be used to implement embodiments of the present invention is shown. The electronic device is intended to represent various forms of digital computers, such as laptop computers, desktop computers, workstations, personal digital assistants, servers, blade servers, mainframe computers, and other suitable computers. The electronic device can also represent various forms of mobile devices, such as personal digital processors, cellular phones, smartphones, wearable devices (e.g., helmets, glasses, watches, etc.), and other similar computing devices. The components shown herein, their connections and relationships, and their functions are merely illustrative and are not intended to limit the implementation of the invention described and / or claimed herein.
[0084] like Figure 3 As shown, the electronic device 30 includes at least one processor 31 and a memory, such as a read-only memory (ROM) 32 or a random access memory (RAM) 33, communicatively connected to the at least one processor 31. The memory stores computer programs executable by the at least one processor. The processor 31 can perform various appropriate actions and processes based on the computer program stored in the ROM 32 or loaded from storage unit 38 into the RAM 33. The RAM 33 can also store various programs and data required for the operation of the electronic device 30. The processor 31, ROM 32, and RAM 33 are interconnected via a bus 34. An input / output (I / O) interface 35 is also connected to the bus 34.
[0085] Multiple components in electronic device 30 are connected to I / O interface 35, including: input unit 36, such as keyboard, mouse, etc.; output unit 37, such as various types of monitors, speakers, etc.; storage unit 38, such as disk, optical disk, etc.; and communication unit 39, such as network card, modem, wireless transceiver, etc. Communication unit 39 allows electronic device 30 to exchange information / data with other devices through computer networks such as the Internet and / or various telecommunications networks.
[0086] Processor 31 can be a variety of general-purpose and / or special-purpose processing components with processing and computing capabilities. Some examples of processor 31 include, but are not limited to, a central processing unit (CPU), a graphics processing unit (GPU), various special-purpose artificial intelligence (AI) computing chips, various processors running machine learning model algorithms, a digital signal processor (DSP), and any suitable processor, controller, microcontroller, etc. Processor 31 executes the various methods and processes described above, such as a real-time account balance calculation method based on a lock-free circular buffer: Receive transaction requests and convert them into event objects; the event objects contain the identifier, amount, event type, and event sequence number of each account corresponding to the transaction request; The event object is written to a pre-allocated circular buffer; the write operation is implemented by comparing and swapping atomic variables using CAS increment; the write operation is non-blocking. A single consumer thread retrieves events from the circular buffer, reads the memory snapshot of each account corresponding to the event, calculates the balance of each account, and updates the account balance through CAS atomic operations. When the number of events in the circular buffer exceeds a preset threshold, or when the time window expires, the events in the circular buffer are written to the append-only transaction log table in a batch.
[0087] In some embodiments, the real-time account balance calculation method based on a lock-free circular buffer can be implemented as a computer program tangibly contained in a computer-readable storage medium, such as storage unit 38. In some embodiments, part or all of the computer program can be loaded and / or installed on electronic device 30 via ROM 32 and / or communication unit 39. When the computer program is loaded into RAM 33 and executed by processor 31, one or more steps of the real-time account balance calculation method based on a lock-free circular buffer described above can be performed. Alternatively, in other embodiments, processor 31 can be configured to perform the real-time account balance calculation method based on a lock-free circular buffer by any other suitable means (e.g., by means of firmware).
[0088] Various embodiments of the systems and techniques described above herein can be implemented in digital electronic circuit systems, integrated circuit systems, field-programmable gate arrays (FPGAs), application-specific integrated circuits (ASICs), application-specific standard products (ASSPs), systems-on-a-chip (SoCs), payload-programmable logic devices (CPLDs), computer hardware, firmware, software, and / or combinations thereof. These various embodiments may include implementations in one or more computer programs that can be executed and / or interpreted on a programmable system including at least one programmable processor, which may be a dedicated or general-purpose programmable processor, capable of receiving data and instructions from a storage system, at least one input device, and at least one output device, and transmitting data and instructions to the storage system, the at least one input device, and the at least one output device.
[0089] Computer programs used to implement the methods of the present invention may be written in any combination of one or more programming languages. These computer programs may be provided to a processor of a general-purpose computer, a special-purpose computer, or other programmable data processing device, such that when executed by the processor, the computer programs cause the functions / operations specified in the flowcharts and / or block diagrams to be performed. The computer programs may be executed entirely on a machine, partially on a machine, or as a standalone software package, partially on a machine and partially on a remote machine, or entirely on a remote machine or server.
[0090] In the context of this invention, a computer-readable storage medium can be a tangible medium that may contain or store a computer program for use by or in conjunction with an instruction execution system, apparatus, or device. A computer-readable storage medium may include, but is not limited to, electronic, magnetic, optical, electromagnetic, infrared, or semiconductor systems, apparatus, or devices, or any suitable combination thereof. Alternatively, a computer-readable storage medium may be a machine-readable signal medium. More specific examples of machine-readable storage media include electrical connections based on one or more wires, portable computer disks, hard disks, random access memory (RAM), read-only memory (ROM), erasable programmable read-only memory (EPROM or flash memory), optical fibers, portable compact disk read-only memory (CD-ROM), optical storage devices, magnetic storage devices, or any suitable combination thereof.
[0091] To provide interaction with a user, the systems and techniques described herein can be implemented on an electronic device having: a display device (e.g., a CRT (cathode ray tube) or LCD (liquid crystal display) monitor) for displaying information to the user; and a keyboard and pointing device (e.g., a mouse or trackball) through which the user provides input to the electronic device. Other types of devices can also be used to provide interaction with the user; for example, feedback provided to the user can be any form of sensory feedback (e.g., visual feedback, auditory feedback, or tactile feedback); and input from the user can be received in any form (including sound input, voice input, or tactile input).
[0092] The systems and technologies described herein can be implemented in computing systems that include backend components (e.g., as data servers), or middleware components (e.g., application servers), or frontend components (e.g., user computers with graphical user interfaces or web browsers through which users can interact with implementations of the systems and technologies described herein), or any combination of such backend, middleware, or frontend components. The components of the system can be interconnected via digital data communication of any form or medium (e.g., communication networks). Examples of communication networks include local area networks (LANs), wide area networks (WANs), blockchain networks, and the Internet.
[0093] A computing system can include clients and servers. Clients and servers are generally located far apart and typically interact through communication networks. The client-server relationship is created by computer programs running on the respective computers and having a client-server relationship with each other. The server can be a cloud server, also known as a cloud computing server or cloud host, which is a hosting product within the cloud computing service system to address the shortcomings of traditional physical hosts and VPS services, such as high management difficulty and weak business scalability.
[0094] In one embodiment, the present invention further includes a computer program product, which includes a computer program that, when executed by a processor, implements the real-time account balance calculation method based on a lock-free circular buffer according to any embodiment of the present invention.
[0095] In implementing the computer program product, computer program code for performing the operations of this invention can be written in one or more programming languages or a combination thereof. Programming languages include object-oriented programming languages such as Java, Smalltalk, and C++, as well as conventional procedural programming languages such as C or similar languages. The program code can be executed entirely on the user's computer, partially on the user's computer, as a standalone software package, partially on the user's computer and partially on a remote computer, or entirely on a remote computer or server. In cases involving remote computers, the remote computer can be connected to the user's computer via any type of network—including a local area network (LAN) or a wide area network (WAN)—or can be connected to an external computer (e.g., via the Internet using an Internet service provider).
[0096] It should be understood that the various forms of processes shown above can be used, with steps reordered, added, or deleted. For example, the steps described in this invention can be executed in parallel, sequentially, or in different orders, as long as the desired result of the technical solution of this invention can be achieved, and this is not limited herein.
[0097] The specific embodiments described above do not constitute a limitation on the scope of protection of this invention. Those skilled in the art should understand that various modifications, combinations, sub-combinations, and substitutions can be made according to design requirements and other factors. Any modifications, equivalent substitutions, and improvements made within the spirit and principles of this invention should be included within the scope of protection of this invention.
Claims
1. A method for calculating real-time account balances based on a lock-free circular buffer, characterized in that, include: Receive transaction requests and convert them into event objects; the event objects contain the identifier, amount, event type, and event sequence number of each account corresponding to the transaction request; The event object is written to a pre-allocated circular buffer; the write operation is implemented by comparing and swapping atomic variables using CAS increment; the write operation is non-blocking. A single consumer thread retrieves events from the circular buffer, reads the memory snapshot of each account corresponding to the event, calculates the balance of each account, and updates the account balance through CAS atomic operations. When the number of events in the circular buffer exceeds a preset threshold, or when the time window expires, the events in the circular buffer are written to the append-only transaction log table in a batch.
2. The method according to claim 1, characterized in that, Also includes: Exceptions that fail to be processed are written to a dead-letter queue and reprocessed periodically by a background compensation task. When the system restarts abnormally, the most recent persistent snapshot is loaded, all unwritten logs are replayed from the snapshot number backwards, and memory snapshots of all accounts are rebuilt.
3. The method according to claim 1, characterized in that, The circular buffer is implemented using a pre-allocated fixed array, and pointers to producers and consumers are managed by two atomic variables respectively. When the circular buffer is detected to be full, the write operation is blocked and a failure message is returned, triggering a backpressure notification so that the upstream system can degrade or reject new requests.
4. The method according to claim 1, characterized in that, Also includes: When a balance query request is received: Read the memory snapshot of the target account corresponding to the balance query to obtain the latest balance of the target account; If a memory miss occurs, the latest balance of the target account is retrieved from the Redis cache. If the Redis cache misses, the latest balance of the target account is recovered from the most recent persistent snapshot and unwritten log replay. Otherwise, return a query failure message.
5. The method according to claim 1, characterized in that, Write the events in the circular buffer to the append-only transaction log table in a batch, including: Merge all events in the circular buffer into a single batch insert statement; The operation of inserting into the append-only transaction log table is performed based on the single batch insert statement.
6. The method according to claim 1, characterized in that, The event sequence number adopts a globally incrementing allocation mechanism to ensure that the processing order of events is consistent with the generation order; When CAS updates, it verifies the continuity of the event sequence number. If a jump in the event sequence number is detected, an abnormal alarm is triggered.
7. A real-time account balance calculation device based on a lock-free circular buffer, characterized in that, include: The receiving and conversion module is used to receive transaction requests and convert the transaction requests into event objects; the event objects contain the identifier, amount, event type, and event sequence number of each account corresponding to the transaction request; The first write module is used to write the event object into a pre-allocated circular buffer; the write operation is implemented by comparing and swapping atomic variables using CAS increment; the write operation is non-blocking. The read and calculate module is used to retrieve events from the circular buffer using a single consumer thread, read the memory snapshot of each account corresponding to the event, calculate the balance of each account, and update the account balance through CAS atomic operations; The second write module is used to write the events in the circular buffer into the append-only transaction log table in one batch when the number of events in the circular buffer exceeds a preset threshold, or when the time window expires.
8. An electronic device, characterized in that, The electronic device includes: At least one processor; and A memory communicatively connected to the at least one processor; wherein, The memory stores a computer program that can be executed by the at least one processor, the computer program being executed by the at least one processor to enable the at least one processor to perform the real-time account balance calculation method based on a lock-free circular buffer as described in any one of claims 1-6.
9. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores computer instructions that cause a processor to execute the real-time account balance calculation method based on a lock-free circular buffer as described in any one of claims 1-6.
10. A computer program product, characterized in that, The method includes a computer program that, when executed by a processor, implements the real-time account balance calculation method based on a lock-free circular buffer according to any one of claims 1-6.
