Sobes.tech
Senior

Concurrent access to an account: how to avoid losing operations during simultaneous debits and credits?

sobes.tech AI

Answer from AI

To avoid losing operations during concurrent access to an account (for example, simultaneous debiting and crediting), it is necessary to ensure the atomicity and consistency of updates. Main approaches:

  • Using transactions with locks: In Java with a database, you can use transactions with the isolation level SERIALIZABLE or PESSIMISTIC LOCKING (for example, SELECT ... FOR UPDATE) to guarantee sequential access to the account record.

  • Optimistic locking: Add a version field to the table (version), and when updating, check that the version has not changed. If it has changed, repeat the operation.

  • Using atomic database operations: For example, SQL queries like UPDATE accounts SET balance = balance + ? WHERE id = ? ensure that changes are applied correctly without data loss.

  • **In Java, you can use synchronized or ReentrantLock for in-memory access synchronization, but this only works within a single application instance. For distributed systems, it is better to use database locks or external systems (e.g., Redis).

Example of atomic balance update in SQL:

BEGIN TRANSACTION;
UPDATE accounts SET balance = balance - 100 WHERE id = 1 AND balance >= 100;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;

If the balance is insufficient, the operation will rollback, preventing loss of funds.

In Java with JPA, you can use:

@Transactional
public void transfer(Long fromId, Long toId, BigDecimal amount) {
    Account from = entityManager.find(Account.class, fromId, LockModeType.PESSIMISTIC_WRITE);
    Account to = entityManager.find(Account.class, toId, LockModeType.PESSIMISTIC_WRITE);
    if (from.getBalance().compareTo(amount) < 0) {
        throw new InsufficientFundsException();
    }
    from.setBalance(from.getBalance().subtract(amount));
    to.setBalance(to.getBalance().add(amount));
}

This approach prevents race conditions and operation loss.

Concurrent access to an account: how to avoid losing… - sobes.tech