Sobes.tech
Junior — Middle

How to ensure data consistency if updates happen simultaneously in two accounts?

sobes.tech AI

Answer from AI

To ensure data consistency during concurrent updates in two accounts, several approaches can be used:

  1. Transactions and locks — if data is stored in a database, transactions with an isolation level that prevents conflicting updates (e.g., SERIALIZABLE or REPEATABLE READ) are applied. Record-level locks can also be used so that one process waits for another to finish.

  2. Optimistic locking — a version (e.g., a version or timestamp field) is stored in the data. When updating, it checks that the version has not changed since reading. If it has changed, the operation is rolled back or retried.

  3. Use of distributed transactions — if data is distributed, protocols like two-phase commit (2PC) or other consistency mechanisms are used.

  4. Eventual consistency and conflict resolution — in high-load systems, temporary inconsistency can be allowed, and logic for merging changes can be implemented.

Example of optimistic locking in Java using JPA:

@Entity
public class Account {
    @Id
    private Long id;

    @Version
    private Long version; // field for optimistic locking

    private BigDecimal balance;

    // getters and setters
}

// When updating:
@Transactional
public void updateAccountBalance(Long accountId, BigDecimal amount) {
    Account account = entityManager.find(Account.class, accountId);
    account.setBalance(account.getBalance().add(amount));
    // on commit, if the version has changed, an OptimisticLockException will be thrown
}
How to ensure data consistency if updates happen… - sobes.tech