October 26, 2026
REST API Design for Accounting Ledger: Guarantee of Transactional Integrity and Traceability.
Pedro Martins Trevisan; Lucas José de Souza
DOI: 10.22167/2675-6528-202601311
Article prepared by the ResumeAI tool, an artificial intelligence solution developed by the Pecege Institute focused on synthesis and writing.
Summary
The digitalization of the Brazilian financial sector has driven the demand for interfaces that act as single, immutable, and auditable sources of truth for accounting ledgers. It was observed that traditional CRUD-based software design proved inadequate for the demands of transactional integrity and traceability, given the destructive mutation of states and the consequent loss of audit history. A reference model for the design of REST APIs for accounting ledgers was proposed, aiming to ensure transactional integrity and traceability. The methodology employed exploratory and applied research, based on a systematic literature review and documentary analysis of market technical specifications, culminating in the development of an experimental prototype of an event-driven REST API. The architecture implemented Event Sourcing and CQRS patterns, with immutable event persistence in PostgreSQL and validation of transactional flows. The results indicated that the developed architecture ensured immutability through an event log and rigorously validated requirements such as double-entry bookkeeping and idempotency, satisfying auditability and historical integrity demands. The adoption of CQRS allowed for a reduction in the computational cost of frequent reads. It was concluded that the proposed model reconciled modern software engineering patterns with accounting rigor, providing practical guidelines for building resilient, transparent, and secure financial ecosystems, despite operational challenges related to architectural complexity and eventual consistency management.
Keywords: CQRS; Event Sourcing; Idempotence; Immutability; Double entries.
1. Introduction
Accounting, historically, is based on the ledger, or *ledger*, as a foundation for recording and verifying financial transactions. According to Berg et al. (2018), *ledgers* are essential infrastructures that allow for the validation and auditing of goods and assets, establishing trust in economic interactions. In Brazil, the digitalization of the financial sector, driven by milestones such as Open Finance and PIX, has accelerated the demand for application programming interfaces (APIs) that function as digital *ledgers*. However, traditional software design, based on CRUD (*Create, Read, Update, Delete*), proves intrinsically inadequate for these demands. Its update and delete operations are destructive, compromising traceability and transactional auditability by overwriting historical data. Pantelelis and Kalloniatis (2022) and Berg et al. (2018) converge in stating that the integrity of a digital *ledger* intrinsically depends on its immutability, something that the CRUD model cannot provide, resulting in loss of history and difficulty in regulatory compliance.
To mitigate these deficiencies and meet the requirements of integrity and traceability, the *Event Sourcing* pattern emerges as a robust solution. This approach differs from CRUD by recording all state changes as an immutable sequence of events, rather than just storing the current state. Each event represents a fact that occurred in the system, chronologically persisted in an event log. Such a mechanism ensures the complete preservation of the operation history, allowing for the deterministic reconstruction of any entity’s state at any point in time (Pantelelis and Kalloniatis, 2022). The immutability of events ensures a complete and unquestionable audit trail, fundamental for the financial domain, where verification and compliance are paramount.
Complementary to *Event Sourcing*, the *Command Query Responsibility Segregation* (CQRS) architecture optimizes performance and scalability in complex systems by segregating write (command) and read (query) responsibilities into distinct models and infrastructures. This separation allows for independent optimization: the command side focuses on validating and persisting immutable events, while the query side utilizes data projections optimized for fast reads (Palamakula, 2026). The synergy between *Event Sourcing* and CQRS reconciles historical integrity with query efficiency, a critical challenge in high-volume accounting *ledgers*. Additionally, building robust digital *ledgers* requires implementing transactional guarantees such as idempotency, which prevents duplicates (Goplani, 2023), and the double-entry bookkeeping principle, which ensures balance between debits and credits (Romney and Steinbart, 2018). However, the literature lacks consolidated guidelines for the practical application and integration of these patterns into a reference model for REST APIs in accounting *ledgers*, highlighting a gap in how to harmonize software engineering *best practices* with the intrinsic requirements of the accounting domain.
The relevance of this study for software engineering and the financial sector is justified by the need to align good development practices for systems with the rigorous standards of the market. By proposing an event-driven API architecture model, this work contributes practically and scientifically to the construction of more resilient, transparent, and auditable financial ecosystems, providing concrete guidelines for engineers and developers. Given the above, the general objective of this work is to propose a reference model for the design of REST APIs aimed at accounting *ledgers*, aiming to ensure transactional integrity and traceability. Specifically, it seeks to analyze the limitations of the conventional CRUD model, map event-driven architecture guidelines, and define functional and non-functional requirements for this type of application.
2. Material and Methods
The present research was classified as exploratory, with a qualitative approach and applied nature, with the purpose of proposing an innovative architectural solution for the financial ecosystem. The study specifically aimed at the development of a reference model for accounting *ledgers* Application Programming Interfaces (APIs), focusing on ensuring transactional integrity and traceability. This classification allowed for an in-depth investigation of technical and business requirements, aligning software engineering practices with the demands of the accounting domain, according to the need for a new paradigm for digital financial systems.
The study’s context was set within the scenario of the digitalization of the Brazilian financial sector, driven by initiatives such as Open Finance and PIX, which demand robust digital *ledgers*. Although the original TCC does not specify a physical location for the research execution, the focus remained on industrial applicability and market specifications. The scope period for the literature review was delimited between the years 2005 and 2026, covering the evolution of architectural and accounting standards. The main unit of analysis consisted of software architectural patterns and REST APIs, specifically in their application to accounting ledger systems.
The research execution was structured in four main and sequential phases, designed to comprehensively address the overall objective. Initially, a systematic literature review was conducted for theoretical grounding. Subsequently, a technical *benchmarking* was carried out, through documentary market research, to identify industry standards. The subsequent phases involved the modeling of the proposed solution’s design and, finally, the development of an experimental prototype. This multifaceted approach allowed for the construction of a solid reference model, validated by both theory and practice.
The first phase consisted of a systematic literature review, with the objective of exploring the intersection between software engineering and accounting systems. Searches were conducted in the Google Scholar academic database, prioritizing materials that established connections between architectural patterns and the compliance required in financial systems. The temporal scope for publications was defined between 2005 and 2026, covering from the initial milestones of patterns such as *Event Sourcing* and CQRS. The search terms were organized into thematic groupings, including “Event Sourcing”, “CQRS”, “REST API”, “Event-driven architecture”, “ledger”, “idempotency”, and “double entry”.
The screening of articles followed a funnel method, starting with the pre-selection of sixteen publications based on reading their titles and abstracts. Inclusion criteria prioritized works that addressed distributed systems and event-driven architectures applied to financial and transactional contexts. In contrast, articles that strictly focused on infrastructure or database optimization, without relevance to the application layer or financial systems, were excluded. After this careful analysis, the most promising studies were selected to support the project and provide the essential theoretical foundations for the technical modeling of the solution.
The second phase of the research involved a documentary survey and technical *benchmarking*, with the purpose of aligning the proposed model with real industry standards. The sample for this phase included a detailed analysis of consolidated financial API specifications, from companies such as Stripe and Woovi. Additionally, technical and regulatory manuals from Open Finance were examined. This analysis sought to identify implementation patterns for non-functional requirements, such as the use of HTTP verbs, idempotency key implementation mechanisms to prevent duplication, and *payload* formatting, ensuring the required atomicity in data input.
The third and fourth phases of the research comprised the modeling and development of an experimental prototype of an event-driven REST API. The modeling of the *endpoints* and data contracts were formalized following the OpenAPI standard, ensuring clarity and interoperability. The technical development used tools from the Node.js ecosystem, employing the TypeScript language for implementation. The prototype architecture implemented the separation of responsibilities through the CQRS pattern, and the persistence of immutable events was carried out in a PostgreSQL relational database, leveraging its robust ACID transaction support to ensure data integrity.
The validation of the experimental prototype was carried out by executing simulated transactional flows, such as deposit and transfer operations. This procedure aimed to verify the functionality and adherence of the proposed model to the integrity and traceability requirements. During validation, it was analyzed whether the sequence of recorded events allowed for the faithful reconstruction of the consolidated account balances and whether the system guaranteed the auditability required by the financial sector. This practical step was crucial to demonstrate the viability and effectiveness of the event-driven architecture in building accounting *ledgers*.
Regarding ethical procedures, the present work, due to being an exploratory and applied research in software engineering, did not involve direct participation of human beings or collection of sensitive data. Therefore, submission to a research ethics committee was not necessary. As for the methodological limitations intrinsic to the research process, the original term paper did not explicitly state them, focusing on the characteristics and challenges of the proposed architecture. The research focused on the proposition and validation of a technical model, without the intention of generalizing results to all application contexts.
3. Results and Discussion
The analysis of the results obtained with the experimental prototype allowed a deep understanding that the construction of an API for an event-driven accounting *ledger* requires a set of functional and non-functional requirements that significantly differ from those typically associated with conventional APIs operating with direct state mutation, based on the CRUD (Create, Read, Update, Delete) paradigm. This distinction is crucial, as financial systems demand a level of integrity and traceability that the CRUD model, due to its data-destructive nature, cannot intrinsically provide. The research demonstrated that immutability and auditability are non-negotiable pillars for the reliability of a digital *ledger*.
Regarding functional requirements, the prototype highlighted the imperative for the system to be capable of immutably recording financial events. This means that once a transaction is recorded, it cannot be altered or deleted, ensuring historical integrity. Additionally, the prior validation of complex business rules, such as balance availability before a transfer or compliance with transaction limits, proved essential for preventing inconsistencies at the entry point. The rigorous application of the double-entry bookkeeping principle, where each debit must correspond to an equivalent credit, was a central functional requirement, ensuring accounting balance. The prevention of transactional duplications, through idempotency mechanisms, also proved fundamental for system robustness, preventing accidental resubmissions of requests from resulting in multiple executions of the same operation. Finally, the ability to reconstruct account balances and histories by reprocessing the sequence of persisted events was validated, proving the auditability and resilience of the model.
The practical validation of these functional requirements was carried out through the simulation of transactional flows, such as deposits and transfers. In these scenarios, the operation was only consolidated in the *ledger* after verifying the availability of balance in the originating account and the perfect balancing between debit and credit values. This process demonstrated that the proposed architecture not only records transactions but also validates them semantically, ensuring that the system’s state is always consistent and reflects accounting reality. The immutability of events, in turn, ensures that the history of all operations is preserved, allowing any audit to reconstruct the state of an account at any point in time, a capability that is inherently compromised in CRUD systems due to data overwriting.
Regarding non-functional requirements, the results highlighted that the main differential of the proposed architecture lies in its intrinsic capability to satisfy critical demands for immutability, auditability, traceability, and historical integrity. The replacement of destructive balance updates with an event-based, “append-only” persistence radically transforms how data is handled. The system not only preserves the final effect of an operation but also its original intent, the context in which it occurred, and its temporal chaining. This characteristic is of utmost importance for the accounting domain, as it elevates auditing from a reactive and external process to an intrinsic property of the architecture, eliminating the dependence on auxiliary mechanisms that are often susceptible to inconsistencies. As discussed by Romney and Steinbart (2018) and Susanto et al. (2023), integrity and traceability are fundamental in digital accounting systems, and the event-driven architecture addresses these needs more robustly than traditional models. The ability to have a complete and immutable record of all state changes is a pillar for trust and regulatory compliance in the financial sector.
The adoption of the CQRS (Command Query Responsibility Segregation) pattern in the experimental prototype proved to be a crucial enabler for performance and scalability optimization, especially in frequent read operations. By segregating write (Command) and read (Query) responsibilities, the model allowed queries to be directed to optimized and deterministic data projections, significantly reducing the computational cost associated with reconstructing the state from the event stream on every read request. This decoupling is a notable advantage in systems with high query demand, where performance is a critical factor. However, this approach introduces an inherent “trade-off” in eventual consistency between write and read operations, an aspect widely debated in the literature of distributed architectures (Fowler, 2005; Vernon, 2013). Eventual consistency implies that there may be a small delay between the moment an event is recorded and the moment its read projections are updated, which requires careful consideration in the design of financial systems where immediate consistency is a requirement.
The findings obtained robustly converge with the reviewed literature, reinforcing the premise that architectural models exclusively centered on the current state are structurally insufficient for systems that need to operate as an unquestionable accounting source of truth. The critical analysis of the prototype, however, also highlighted that substantial gains in auditability and integrity do not come without costs. The event-driven and CQRS architecture, while powerful, entails greater architectural complexity, a significantly larger data storage volume, and the need for complementary mechanisms, such as *snapshots*, to preserve efficiency in long-term scenarios. Kleppmann (2017) emphasizes that mitigating the costs of reprocessing events is a challenge in event-based systems, and *snapshots* are an effective strategy for capturing the consolidated state at specific points in time, reducing the need to reprocess the entire event chain for current state queries.
The combination of Event Sourcing and CQRS, therefore, constitutes a technically adequate and powerful approach for the design of *ledger* APIs, provided that its adoption is accompanied by explicit and well-defined strategies for managing eventual consistency, event evolution (schema evolution), and operational scalability. The additional complexity introduced by these patterns requires a development team with greater technical maturity and careful planning for the system’s infrastructure and governance. Figure 1 illustrates the proposed architecture, highlighting the separation between command (write) and query (read) flows, and the centrality of the *event store* as the single source of truth.
Source: Original research results
Figure 1. Event Sourcing and CQRS-based Ledger API Architecture
The architecture presented in Figure 1 details how users interact with the *ledger* API. Write operations (Command) undergo rigorous business rule validation before the generation of an immutable event. This event is then persisted in the *event store*, which acts as the single, immutable source of truth, operating on an “append-only” model. In parallel, read operations (Query) are routed to read projections, which are asynchronously fed by events from the *event store*. These projections reside in databases or tables optimized for fast queries, ensuring that read operations do not impact the performance of write operations and vice versa. This asynchronous flow is fundamental to the system’s scalability and resilience, allowing different data models to be optimized for their respective purposes.
### Application of “Event Sourcing” as an accounting record mechanism
The analysis of the results obtained in the experimental prototype evidenced that the adoption of the “Event Sourcing” pattern transcends a mere architectural choice, representing a fundamental redefinition of the very nature of the information persisted in a *ledger* API. In contrast to traditional models that store only the current state of entities, Event Sourcing establishes that the primary source of truth for the system must be the chronological sequence of immutable events that describe the evolution of this state over time, as per Fowler’s original conception (2005). This approach is intrinsically aligned with accounting philosophy, where each transaction is an event that alters the financial state of an entity, and the history of these transactions is as important as the current balance.
This approach proved to be fully consistent with the conceptual definition of “ledger” found in the literature, where records are not mere static data, but rather structured representations of ownership relations and transactions that shape an economic system (Berg et al., 2018). A *ledger*, in this sense, is a mechanism that records, validates, and tracks economic relations, ensuring the verifiability and auditability of transactions. The implementation of Event Sourcing in the prototype brings software engineering closer to this theoretical definition, by ensuring that each change in the system corresponds to an explicit, verifiable, and traceable event, transforming data recording into a log of immutable accounting facts.
In practice, the developed model applied Event Sourcing by replacing direct state updates with an “append-only” persistence. This means that, instead of modifying an existing record, each validated operation generates a new immutable event that is appended to the history. Thus, operations such as deposits and transfers cease to be treated as simple balance mutations and become independent accounting facts, containing all the necessary information for their future interpretation. This result demonstrates a fundamental shift: the account balance ceases to be the primary source of truth and becomes a derived projection from the sequence of recorded events, a concept that Kleppmann (2017) explores in his discussion on log-oriented systems. The practical implication is that the integrity of the balance is guaranteed by the integrity of the sequence of events that generated it, rather than by the mutability of a single balance field.
From the perspective of functional requirements, Event Sourcing directly enabled the implementation of essential accounting domain properties, such as transaction immutability, complete historical traceability, and the ability to deterministically reconstruct the system state. By reprocessing persisted events, it becomes possible to accurately reproduce the balance of any account at any point in time. This meets the rigorous audit and reconciliation demands typical of financial systems, as highlighted by Romney and Steinbart (2018). For financial institutions, this translates into increased data confidence, facilitated regulatory compliance, and the ability to respond quickly to fraud investigations or inconsistencies.
Furthermore, the prototype analysis demonstrated that the event-driven model allows the implementation of correction mechanisms without loss of history. Unlike CRUD-based approaches, where data can be overwritten or deleted, the correction of inconsistencies in Event Sourcing occurs through the issuance of new compensatory events. These events, such as chargebacks or adjustments, are recorded as part of the historical sequence, fully preserving the original record and maintaining complete auditability. This behavior is perfectly aligned with traditional accounting practices, which use chargebacks and adjustments to correct errors without erasing history, as described in the accounting systems literature (Susanto et al., 2023). The ability to track each correction and its reason is an invaluable benefit for transparency and compliance.
However, the application of Event Sourcing also revealed important limitations that must be carefully managed. The main challenge identified is related to the continuous growth of data volume, as all events must be preserved indefinitely. This behavior can significantly impact both storage costs and the performance of operations that rely on reconstructing the state from long chains of events. To mitigate the computational cost of reprocessing, it becomes necessary to adopt complementary strategies, such as the use of periodic *snapshots*, which are checkpoints of the consolidated state (Kleppmann, 2017). Without these strategies, reconstructing historical states can become prohibitively slow and expensive in large-scale systems.
Another critical aspect identified refers to the need for extreme rigor in event modeling. As events constitute the system’s source of truth, any error or ambiguity in their definition can compromise the future interpretation of data and the integrity of the *ledger*. This implies that data modeling is no longer solely oriented by database structures but requires a deep understanding of the business domain, focusing on the semantics of events. Vernon (2013) emphasizes the importance of robust domain modeling for event-driven architectures, where events should be information-rich and reflect business intentions clearly and unequivocally. The evolution of the event *schema* over time is also a complex challenge, requiring versioning and data migration strategies to ensure backward compatibility and the ability to reprocess old events with new rules.
Thus, it is concluded that Event Sourcing proved to be a highly suitable approach for building a *ledger* API, as it aligns technical implementation with the fundamental principles of accounting systems, ensuring immutability and auditability. However, its adoption implies a significant increase in architectural and operational complexity, requiring additional mechanisms for performance management, event versioning, and rigorous data model governance. The decision to implement Event Sourcing should be weighed against the benefits of integrity and traceability versus the costs of complexity and infrastructure, being more justifiable in domains where compliance and auditability are paramount requirements.
### Application of “CQRS” in the separation between writing and reading
The application of the CQRS (Command Query Responsibility Segregation) pattern was analyzed as an essential complement to the Event Sourcing-based model, optimizing the system’s performance and scalability. As described by Fowler (2005) and Vernon (2013), CQRS proposes the explicit separation between write (commands) and read (queries) responsibilities, allowing each to be optimized according to its specific characteristics. In an accounting *ledger*, write operations (entries, transfers) require high integrity and rigorous validation, while read operations (balance inquiries, statements, reports) demand high performance and flexibility for different types of data aggregation.
This model aligns perfectly with the function of APIs in modern financial systems, which act as intermediaries between different applications and are responsible for making data available in a structured and efficient way (Susanto et al., 2023). By separating reading and writing, the *ledger* API offers greater flexibility in how data is exposed. This allows for the creation of multiple specialized projections for different use cases, such as management reports, operational *dashboards*, or specific balance queries, each optimized for its respective access pattern and performance. This flexibility is crucial in a diverse financial ecosystem, where different *stakeholders* may have distinct query needs.
From the perspective of functional requirements, CQRS has significantly contributed to the organization of the transactional flow, ensuring that critical write operations are isolated and treated with greater rigor. This reduces the risk of inconsistencies and facilitates the application of complex business rules, especially in a ledger context where transaction integrity is fundamental (Vernon, 2013). The command layer can focus exclusively on validating and persisting events, while the query layer can focus on fast data delivery, without the overhead of processing business rules. This separation of concerns simplifies the development and maintenance of each part of the system, allowing teams to specialize in optimizing each flow independently.
From the perspective of non-functional requirements, the main observed benefit was the substantial performance improvement in read operations. By using pre-processed and query-optimized projections, the system avoids the need to reconstruct the state from the event chain for each query, which would significantly reduce computational cost. Furthermore, the model allows for independent scalability between read and write layers, a fundamental characteristic in modern distributed systems (Kleppmann, 2017). For example, it is possible to horizontally scale read instances to support a large volume of queries without affecting write processing capacity, and vice versa. This scalability flexibility is a competitive differentiator for financial systems that need to handle demand peaks on both sides.
However, the adoption of CQRS introduces an important “trade-off” related to data consistency: eventual consistency. As read projections are updated asynchronously from events, there may be a time interval in which the queried data does not immediately reflect the system’s most recent state. This model, widely discussed in the literature, is a necessary compromise to achieve scalability and performance in distributed systems (Kleppmann, 2017). For an accounting *ledger*, this means that, although the final state is always consistent after processing all events, an immediate query after a transaction may not reflect the most up-to-date balance. Managing this eventual consistency requires developers and users to understand its implications and design the system to handle them, for example, by informing the user about the asynchronous nature of the update or by using notification mechanisms to indicate when projections are updated.
Another relevant point concerns the increase in architectural complexity. The need to maintain projection *pipelines*, event synchronization mechanisms, and multiple data models (one for writing and another for reading) requires greater implementation and maintenance effort. Compared to the CRUD model, which presents a simpler and more direct structure, the CQRS approach demands greater effort in development, maintenance, and technical governance (Vernon, 2013). This includes the need to manage the evolution of projection *schemas*, ensure the resilience of event *pipelines*, and monitor the latency between the *event store* and read projections. However, the results indicate that this cost is justifiable in domains where the integrity and traceability of transactions are more relevant than structural simplicity, as is the case with financial systems.
Thus, it is concluded that CQRS, when combined with Event Sourcing, constitutes an essential element for building an efficient and scalable *ledger* API. While Event Sourcing ensures data integrity and traceability through an immutable event log, CQRS enables its practical use, allowing the system to simultaneously meet the demands of transactional consistency and query performance. The synergy between these two patterns allows for the construction of a robust system that can handle the complexities of the financial domain, offering high availability, scalability, and an auditable source of truth.
### Transactional Guarantees in a Ledger System
The analysis of the results obtained with the experimental prototype showed that the construction of a *ledger* API requires the implementation of transactional guarantees substantially more rigorous than those normally observed in systems based on CRUD operations. While in these systems consistency is often limited to the integrity of the state stored in a database, in financial systems it is imperative to ensure that each operation is semantically correct, unique, complete, and auditable over time (Kleppmann, 2017). Failure in any of these guarantees can lead to serious financial inconsistencies, monetary losses, and regulatory problems.
In this context, transactional guarantees are not restricted to the classic properties of atomicity and consistency at the database level (ACID), but extend to the preservation of fundamental invariants of the accounting domain. The *ledger*, as a source of truth, requires all transactions to maintain mandatory structural properties, such as value conservation and perfect balance between debits and credits. As discussed by Berg et al. (2018), *ledgers* play the role of recording and validating economic relationships, so that any inconsistency compromises not only an isolated record, but the global integrity of the entire financial system. The violation of an accounting invariant can have cascading effects, compromising trust in the system as a whole.
In the proposed model, these guarantees are achieved through the combination of three main mechanisms. Firstly, pre-write validations are responsible for ensuring that business rules and accounting invariants are respected before the persistence of any event. This includes balance checks, transaction limits, and compliance with the double-entry bookkeeping principle. Secondly, the immutable persistence of events, a characteristic of Event Sourcing, guarantees complete traceability and auditability of operations, as no record is overwritten or deleted. Each event is a historical fact that can be consulted and reprocessed at any time. Thirdly, duplicate control mechanisms, such as idempotency, prevent side effects arising from reprocessing or communication failures in distributed environments, ensuring that an operation is executed exactly once.
Furthermore, it was observed that, in event-driven architectures, the notion of transaction transcends the traditional concept of a database transaction. An operation can only be considered valid when, in addition to being persisted, it respects the invariant rules of the domain, ensuring system consistency throughout the entire event chain. In this sense, as argued by Vernon (2013), consistency must be treated as a property of the domain model, not just the persistence layer. This means that business logic must be robust enough to guarantee consistency, even in the face of infrastructure or communication failures. The responsibility for data integrity is shifted to the application, which must ensure that the events generated and processed keep the *ledger* in a valid state.
### Idempotence as a mechanism for preventing duplication
The prototype analysis demonstrated that idempotency is a requirement of extreme importance for building reliable financial APIs, especially in distributed environments subject to communication failures and request retries. In practical terms, an idempotent operation is one that can be executed multiple times without altering the final result beyond the first execution. This is vital in systems where requests may be resent due to *timeouts*, network failures, or client errors, and where the duplication of operations can have serious financial consequences, such as duplicate charges or undue transfers.
In the context of the *ledger* API, idempotency has proven fundamental to avoid transaction duplication, one of the most critical problems in financial systems. As discussed by Kleppmann (2017), ensuring that an operation occurs exactly once in distributed systems is a complex challenge, and idempotency is one of the most effective strategies to mitigate this problem. Without idempotency, a simple resubmission of a payment request, for example, could result in two charges to the customer, generating accounting inconsistencies and user dissatisfaction.
To mitigate this risk, the proposed model considers the use of unique transaction identifiers, allowing each operation to be unequivocally recognized by the system. Thus, upon receiving a request that has already been processed with the same identifier, the system is capable of identifying its duplication and avoiding the generation of new events or the re-execution of business logic. This ensures that the *ledger*’s state remains consistent, regardless of how many times the request is sent. Practical implementation generally involves storing the idempotency identifier along with the result of the operation’s first execution, allowing subsequent requests with the same identifier to return the original result without reprocessing.
A widely adopted practical example in the industry is the strategy used by companies like Stripe, which implements idempotency through an HTTP header called “Idempotency-Key”. In this model, the client generates a unique identifier, usually a UUID (Universally Unique Identifier), and sends it along with the request. The server, in turn, temporarily stores this identifier associated with the operation’s result. If the same request is resent with the same key, the system returns the previously recorded response, without re-executing the operation, thus ensuring non-duplication of transactions. Goplani (2023) discusses the importance of verifying idempotency in REST API clients to ensure the robustness of integrations.
From a theoretical perspective, this mechanism reflects an approach widely discussed in the literature of distributed systems, where idempotence is used to tolerate communication failures and duplicate requests. In real-world scenarios, the loss of responses or network failures can lead clients to resend requests, which, without control mechanisms, can result in unwanted side effects. Ramalingam and Vaswani (2013) explore fault tolerance via idempotence, demonstrating how it simplifies the construction of resilient systems. Idempotence not only ensures correctness under repeated requests but also allows for the construction of fault-tolerant systems without the need for complex distributed coordination, by associating each operation with a unique identifier and recording its effects, ensuring that multiple executions, even in scenarios with process failures or duplicate messages, have the same observable effect as a single execution.
From the perspective of functional requirements, idempotency ensures the uniqueness of transactions and the predictability of API behavior, which is fundamental for user trust and the integrity of the *ledger*. From the perspective of non-functional requirements, it contributes to the system’s reliability and resilience, especially in scenarios of high concurrency or network instability, where the probability of resends and failures is higher. The implementation of idempotency, therefore, is an essential investment in the robustness and trustworthiness of any financial API.
### Double-entry principle
The results obtained showed that the adoption of the double-entry principle constitutes one of the central elements for ensuring the structural integrity of a *ledger* API. This principle, a pillar of accounting since the 15th century, establishes that every financial transaction must be recorded through equivalent debit and credit entries, ensuring the system’s balance and the maintenance of accounting consistency (Romney and Steinbart, 2018). In practical terms, this means that the sum of all debits must equal the sum of all credits for each transaction, ensuring that the total value of the *ledger* remains unchanged, merely redistributed among accounts.
From a theoretical perspective, this model can be understood as an invariance constraint applied to the system, where the sum of debits must necessarily correspond to the sum of credits for each transaction. Such a property acts as a fundamental control mechanism, ensuring that the state of the *ledger* remains consistent over time. The violation of this invariant indicates an accounting error, which may result from human error, system failure, or attempted fraud. The rigorous application of double-entry bookkeeping is, therefore, an essential safeguard against the corruption of financial data and a pillar for auditability.
In the proposed model, the application of this principle was incorporated directly into the transaction validation logic in the command layer. Before any event is persisted, the system checks if the sum of debits is equivalent to the sum of credits. This prior validation prevents the recording of unbalanced operations, ensuring the semantic integrity of the stored data. By enforcing this rule at the entry point, the system prevents the propagation of inconsistencies and guarantees that only valid and balanced transactions are recorded in the *event store*. This is particularly important in a high-concurrency environment, where multiple transactions may be occurring simultaneously.
However, as discussed in the literature, the double-entry model, although essential, is not sufficient on its own to eliminate all operational inconsistencies. Even with accounting and regulatory rigor, there is still room for errors, human failures, and fraud, especially in complex and distributed scenarios (Faccia; Mosteanu, 2019). For example, a transaction may be correctly balanced but involve wrong accounts or incorrect amounts due to a data entry error. Furthermore, the absence of native cross-checking mechanisms between records maintained by different entities is noteworthy, which may require additional external reconciliation processes. The double-entry principle ensures the internal consistency of a transaction, but not its correctness in relation to the external world or other systems.
In this context, the incorporation of automatic validations at the time of writing, as proposed in this work, acts as an additional layer of assurance, reducing the probability of inconsistencies and strengthening the system’s reliability. By enforcing the balance between debits and credits at the application level, the system not only reproduces the classic accounting principle but also adapts it to the demands of distributed and high-concurrency environments, where immediate validation is crucial. This programmatic approach to the double-entry bookkeeping principle ensures that accounting integrity is an intrinsic property of the API, not just a convention to be followed.
Finally, this approach aligns with the function of *ledgers* as instruments for organizing, verifying, and tracing economic relationships (Berg et al., 2018), ensuring that each transaction preserves the global coherence of the system and can be audited deterministically. The combination of Event Sourcing with rigorous validation of double-entry bookkeeping creates a system where accounting integrity is guaranteed by design, offering a high degree of trust and compliance for the financial sector.
### Discussion and critical analysis of the model
When comparing the proposed model, based on Event Sourcing and CQRS, with the traditional CRUD-based architecture, a substantial and multifaceted gain is observed in terms of data traceability, integrity, and immutability. The adoption of the Event Sourcing pattern transforms the API into a trustworthy ledger, where the final state of an account is not stored directly, but rather derived deterministically from the sequence of historical events recorded. This fundamental characteristic enables the concept of audit by design, where traceability does not depend on external mechanisms or secondary logs, but is intrinsically incorporated into the system’s structure (Fowler, 2005; Berg et al., 2018). In a CRUD system, auditing is often a reactive process dependent on application logs that may be incomplete or inconsistent, whereas in the proposed model, the *event store* itself serves as the audit log.
From a positive perspective, this approach represents a significant evolution compared to traditional models, especially in financial domains, where data reliability and verifiability are essential and non-negotiable requirements. The ability to reconstruct the system’s state at any point in time allows not only for more precise and detailed audits but also for in-depth retrospective analyses and forensic investigations, considerably expanding the informational value of the application. For example, in cases of disputes or fraud, the ability to exactly reproduce the sequence of events that led to a certain state is invaluable. Furthermore, event-based modeling promotes transparency and traceability of operations, reducing the risk of hidden inconsistencies and increasing stakeholders’ confidence in the system.
However, the critical analysis of the model also reveals relevant operational challenges that must be carefully managed. One of the main points of attention is related to the introduction of the concept of eventual consistency, arising from the application of the CQRS pattern. As read operations are decoupled from write operations and fed by asynchronous projections, there may be a time interval in which the queried data does not reflect the most recent state of the system. As discussed by Kleppmann (2017), this type of consistency is common in distributed systems and represents a necessary “trade-off” between performance, scalability, and immediate data accuracy. For an accounting *ledger*, this requires users and client systems to understand this characteristic and be designed to handle it, for example, by accepting that a statement may not show the last transaction in real-time, but ensuring that the final state will be consistent.
Another relevant aspect refers to the increase in architectural complexity. The joint implementation of Event Sourcing and CQRS requires the definition of multiple components, such as the *event store*, projection *pipelines*, event versioning mechanisms, and synchronization strategies. Compared to the CRUD model, which presents a simpler and more direct structure, this approach demands greater effort in development, maintenance, and technical governance (Vernon, 2013). Complexity manifests in the need to manage the evolution of the event *schema*, ensure the resilience of event processing *pipelines*, and monitor the latency and health of multiple distributed components. This implies the need for teams with greater software engineering maturity and the adoption of robust DevOps practices.
Additionally, the impact on infrastructure is noteworthy. The cumulative storage pattern of Event Sourcing, based on the continuous persistence of immutable events, implies a progressive growth in data volume over time. Unlike traditional systems, where only the current state is maintained, the need to preserve the entire history can result in high storage and processing costs. This scenario demands the adoption of complementary strategies, such as the use of *snapshots*, which consist of periodically capturing the consolidated state to reduce the cost of reconstructing the system from long event sequences (Kleppmann, 2017). Besides *snapshots*, historical data management may involve archiving, compression, and storage *tiering* strategies to optimize costs without compromising auditability.
Despite these limitations and challenges, the results indicate that the benefits of the proposed architecture outweigh its challenges in contexts where integrity, auditability, and traceability are critical and non-negotiable requirements. While the CRUD model proves adequate for applications with lower historical control requirements and less transactional complexity, the approach based on Event Sourcing and CQRS is more appropriate for systems that act as a financial source of truth, where accuracy and immutability are paramount. The choice of architecture, therefore, should be guided by the application domain and its specific requirements.
Thus, it is concluded that the adoption of this architecture should be guided by the application domain. In financial, regulated, or auditable scenarios, the gains in reliability and transparency justify the increase in complexity and operational costs. The ability to guarantee historical integrity, auditability by design, and fault resilience compensates for the additional investment in development and infrastructure. On the other hand, in less critical systems, where the loss of history or eventual consistency do not represent significant risks, the adoption of these standards may represent an excess of unnecessary engineering, increasing costs and complexity without proportional benefit. Therefore, the main contribution of the proposed model lies in providing clear guidelines for the conscious application of these practices, aligning architectural decisions with the real system requirements and promoting a design of financial APIs that are more resilient, transparent, and secure.
4. Conclusion
It is concluded that the objective was achieved by proposing a reference model for the design of REST APIs for accounting *ledgers*, aiming to ensure transactional integrity and traceability. The study demonstrated the insufficiency of the CRUD model for this domain, given its data-destructive nature, and validated the effectiveness of the architecture based on Event Sourcing and CQRS. This approach allowed the creation of a system where the immutability of events and the rigorous application of transactional guarantees, such as idempotence and the double-entry bookkeeping principle, ensure auditability by design and deterministic reconstruction of the financial history. The separation between writing and reading, provided by CQRS, optimized performance and scalability, consolidating a robust model for digital financial ecosystems.
However, the implementation of this architecture revealed significant operational challenges. The architectural complexity is high, requiring greater technical maturity from development teams. The introduction of eventual consistency, inherent to CQRS, demands careful management and understanding from client systems. Furthermore, the cumulative storage of events in Event Sourcing implies continuous data volume growth, necessitating strategies such as *snapshots* to optimize long-term costs and performance. For future studies, empirical evaluation of the performance and scalability of this model in production environments is suggested, as well as the exploration of advanced mechanisms for event *schema* evolution and latency mitigation in eventual consistency scenarios.
Bibliographic References
Berg, C.; Davidson, S.; Potts, J. 2018. Ledgers. Ledger 2: 55-64.
Faccia, A.; Mosteanu, N.R. 2019. Accounting and blockchain technology: from double-entry to triple-entry. The Business and Management Review 10(2): 108-116.
Fowler, Μ. 2005. Event Sourcing. Disponível em: <https://martinfowler.com/eaaDev/EventSourcing.html>. Acesso em: 10 abr. 2026.
GOPLANI, B. K. APIdemic: Verifying Idempotency of REST API Clients. 2023.
Kleppmann, M. 2017. Designing Data-Intensive Applications. O’Reilly Media, Sebastopol, CA, USA.
Palamakula, S.N. 2026. Unified event-sourced CQRS architecture for continuous compliance monitoring and automated regulatory reporting. International Journal on Science and Technology 17(1): 1-6.
Pantelelis, M.; Kalloniatis, C. 2022. Mapping CRUD to events Towards an object to event-sourcing framework. In.: Panhellenic Conference on Informatics, 2022, Atenas, Grécia. Anais… p. 1-6.
RAMALINGAM, G.; VASWANI, K. Fault Tolerance via Idempotence. 2013.
Romney, M.; Steinbart, P. 2018. Accounting Information Systems. 14ed. Pearson, London, UK.
Susanto et al., 2023 [Referência completa não encontrada no documento original]
Vernon, V. 2013. Implementing Domain-Driven Design. Addison-Wesley, Boston, MA, USA.
Article originating from the Final Course Work of the Specialization in Software Engineering of the MBA USP/Esalq
To learn more about the course, click here and access the MBX Academy platform