> ## Documentation Index
> Fetch the complete documentation index at: https://alan-ramirez-dev.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# ⚖️ ACID Consistency and Concurrency

> Transactional isolation strategies and protection against Race Conditions.

The transactional engine simulates high-fidelity Fintech operations. By handling monetary balances and currency exchanges, the system cannot afford numerical inconsistencies or data loss caused by simultaneous requests (Race Conditions).

To resolve this, the architecture relies heavily on **ACID** properties through the use of persistence-level locks in the relational database.

## 🔒 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.

```java theme={null}
// Lock definition in PortafolioRepository.java
@Repository
public interface PortafolioRepository extends JpaRepository<Portafolio, Long> {

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("SELECT p FROM Portafolio p WHERE p.usuarioId = :usuarioId")
    Optional<Portafolio> findByUsuarioIdForUpdate(@Param("usuarioId") Long usuarioId);
}
```

## 🧮 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 the `RoundingMode.HALF_UP` constant (symmetric rounding to the nearest value), ensuring the platform's accounting precision.

```java theme={null}
// Conversion logic in PortafolioService.java
BigDecimal nuevoBalanceMxn = portafolio.getBalanceMxn().subtract(montoMxn);
portafolio.setBalanceMxn(nuevoBalanceMxn);

BigDecimal usdcComprados = montoMxn.divide(tipoCambio, 4, RoundingMode.HALF_UP);
BigDecimal nuevoBalanceUsdc = portafolio.getBalanceUsdc().add(usdcComprados);
portafolio.setBalanceUsdc(nuevoBalanceUsdc);
```
