🔒 Pessimistic Locking
When two processes attempt to modify the same user’s balance at the same time (for example, a simultaneous capital injection and USDC purchase), a traditional approach could cause a “dirty read” or a lost update. The API mitigates this risk by implementing a Pessimistic Write Lock (PESSIMISTIC_WRITE) through Spring Data JPA. This instructs PostgreSQL to execute a SELECT ... FOR UPDATE clause, freezing the user’s row in the database until the current HTTP transaction completely finishes.
🧮 High Precision Arithmetic (BigDecimal)
The second pillar of consistency in the financial engine is strict control over numerical calculation. Primitive floating-point data types (float or double) are not suitable for accounting applications due to the binary rounding errors inherent in their memory representation.
To guarantee that not a single cent is lost during currency conversions, all business logic operates with BigDecimal using the scale and integrity required at the database level (precision = 19, scale = 4).
🏦 Strict Banking Rounding
During the exchange operation (MXN to USDC Swap), the engine calculates the asset division by applying theRoundingMode.HALF_UP constant (symmetric rounding to the nearest value), ensuring the platform’s accounting precision.