Senior
Practical task: design a money transfer system between accounts with the requirements: 1000 transactions/sec, transactional correctness, synchronous API.
sobes.tech AI
Answer from AI
For a money transfer system between accounts with requirements of 1000 transactions per second, transactional correctness, and a synchronous API, the following approach can be designed:
-
Architecture:
- Use a relational database supporting transactions (e.g., PostgreSQL).
- Implement the API in Java using Spring Boot.
-
Transactional correctness:
- Each transfer operation is a single database transaction that:
- Checks the sender's balance.
- Deducts the amount from the sender's account.
- Credits the amount to the receiver's account.
- Use transaction isolation levels (e.g., SERIALIZABLE or REPEATABLE READ) to prevent race conditions.
- Each transfer operation is a single database transaction that:
-
Handling concurrent requests:
- To prevent deadlocks and race conditions, use account locks in a specific order (e.g., by account ID).
-
Performance:
- Use a connection pool to the database.
- Optimize queries and indexes.
- Horizontally scale API services.
-
Sample code (simplified):
@Transactional
public void transferMoney(Long fromAccountId, Long toAccountId, BigDecimal amount) {
Account from = accountRepository.findByIdForUpdate(fromAccountId);
Account to = accountRepository.findByIdForUpdate(toAccountId);
if (from.getBalance().compareTo(amount) < 0) {
throw new InsufficientFundsException();
}
from.setBalance(from.getBalance().subtract(amount));
to.setBalance(to.getBalance().add(amount));
accountRepository.save(from);
accountRepository.save(to);
}
The findByIdForUpdate method uses an SQL query with SELECT ... FOR UPDATE to lock the rows.
This approach ensures atomicity and consistency of operations under high load and a synchronous API.