Your account has ₹1,000. Two payments go out at the exact same moment: ₹500 and ₹300. You'd expect ₹200 left. The bank's database says ₹700.
Nobody hacked anything. Two transfers read the same old balance, each saved its own answer, and the second save wiped out the first. That's called a lost update, and the cure is a database transaction that makes the second transfer wait its turn.
Let's watch it go wrong, then watch the same scene done safely.
The code that looks fine
Here's a withdraw method you'll find in a lot of first Spring Boot projects:
public void withdraw(Long id, BigDecimal amount) {
Account acc = accounts.findById(id).orElseThrow(); // 1. read
acc.setBalance(acc.getBalance().subtract(amount)); // 2. work it out in Java
accounts.save(acc); // 3. write
}
Read, subtract, save. Run it once and it's perfect. Run it twice at the same time and things get interesting.
Watch the money disappear
Transfer A wants to send ₹500. Transfer B wants to send ₹300. They arrive together.
Step by step:
- A reads the balance: ₹1,000.
- B reads the balance: still ₹1,000, because A hasn't saved anything yet.
- A saves 1,000 − 500 = ₹500.
- B saves 1,000 − 300 = ₹700.
B never saw A's change. It did its maths on a number that was already out of date, and then wrote over A's result. The ₹500 payment went out, but the balance never went down by ₹500. The bank just lost money.
This is a race condition: the result depends on who gets there first. Run the same two transfers again and they may come out right, because the timing is different. That's why these bugs pass every test on your laptop and show up on a busy day.
💡 This is exactly the kind of thing you practise in the Spring Boot course on DevTrail. You write the transactional code yourself and run it right in your browser, with nothing to install.
The fix: one at a time, for this row
The problem is the gap between "read" and "write". Someone else can sneak in there. So we close the gap.
Look at the second half of the animation. This time Transfer A locks the row while it reads. In SQL that's SELECT ... FOR UPDATE. It means: "I'm reading this row because I'm about to change it. Nobody else touches it until I'm done."
Now:
- A locks and reads ₹1,000.
- B asks for the same row and has to wait.
- A saves ₹500 and commits. The lock is released.
- B finally reads, and gets the fresh value: ₹500.
- B saves 500 − 300 = ₹200. ✓
B waited a few milliseconds. In exchange, the balance is right.
The Spring Boot version
Two small changes. Tell the repository to lock the row, and wrap the method in a transaction so the lock is held from the read all the way to the commit:
public interface AccountRepository extends JpaRepository<Account, Long> {
@Lock(LockModeType.PESSIMISTIC_WRITE) // SELECT ... FOR UPDATE
@Query("select a from Account a where a.id = :id")
Optional<Account> findByIdForUpdate(@Param("id") Long id);
}
@Service
public class TransferService {
private final AccountRepository accounts;
public TransferService(AccountRepository accounts) {
this.accounts = accounts;
}
@Transactional
public void withdraw(Long id, BigDecimal amount) {
Account acc = accounts.findByIdForUpdate(id).orElseThrow();
if (acc.getBalance().compareTo(amount) < 0) {
throw new IllegalStateException("Not enough money");
}
acc.setBalance(acc.getBalance().subtract(amount));
// No save() needed: the change is written when the transaction commits.
}
}
What @Transactional gives you here:
- All or nothing. If anything throws, the whole thing rolls back. No half-finished transfers.
- The lock lives as long as the transaction. A row lock is let go on commit or rollback. That's why the transaction has to cover both the read and the write.
There's an even shorter fix when the logic is this simple: let the database do the maths in one statement, like update Account a set a.balance = a.balance - :amt where a.id = :id and a.balance >= :amt (with @Modifying on the query method). The database locks the row while it updates it, so a second update waits and then works on the new value. If it returns 0 rows, there wasn't enough money.
"Can't I just raise the isolation level?"
Good question. Every transaction runs at an isolation level, which decides how much it can see of other transactions that are running at the same time. The SQL standard defines four. Here's which classic problems each one blocks:
| Isolation level | Dirty read | Non-repeatable read | Phantom read |
|---|---|---|---|
| Read Uncommitted | can happen | can happen | can happen |
| Read Committed | blocked | can happen | can happen |
| Repeatable Read | blocked | blocked | can happen (by the standard) |
| Serializable | blocked | blocked | blocked |
In plain words:
- Dirty read: you see another transaction's change before it's committed, and it may still be rolled back.
- Non-repeatable read: you read the same row twice and get two different values.
- Phantom read: you run the same search twice and new rows have appeared.
In Spring you pick a level with @Transactional(isolation = Isolation.REPEATABLE_READ). If you don't, you get the database's default: Read Committed in PostgreSQL, Repeatable Read in MySQL (InnoDB).
Now the catch: the lost update isn't in that table, and each database handles it in its own way.
- At Read Committed (PostgreSQL's default), our read-then-save code loses money. Each read sees committed data, but nothing stops B from saving over A.
- In PostgreSQL, Repeatable Read does notice. The second transfer fails with a serialization error ("could not serialize access due to concurrent update"), and your code has to retry it.
- In MySQL, Repeatable Read (its default) does not stop it for this code. A plain
SELECTreads an old snapshot, so B still does its maths on ₹1,000. - Serializable prevents it everywhere, but some transactions will be rejected and need a retry, and it costs more under load.
So a higher isolation level can help, but how it helps depends on your database. A row lock or an atomic UPDATE says exactly what you mean and behaves the same on both. That's why they're the usual first fix.
Not just databases
The same race happens inside a single Java program. Two threads doing count++, or both adding to the same ArrayList or HashMap, can step on each other in exactly the same way: read, change, write, overwrite. Normal collections like these are not safe to change from several threads at once. Use ConcurrentHashMap, AtomicInteger, or a lock.
The mistake almost everyone makes: calling it from the same class
You add @Transactional, it works in one place, and then you write this:
@Service
public class TransferService {
public void payRent(Long id) {
withdraw(id, new BigDecimal("500")); // 🚨 no transaction here
}
@Transactional
public void withdraw(Long id, BigDecimal amount) { ... }
}
Spring doesn't add transactions by changing your class. It wraps your bean in a proxy, a stand-in object that starts the transaction and then calls your method. That only happens when the call comes from outside, through the proxy.
payRent calls withdraw directly on this. The call never passes through the proxy, so the annotation is simply ignored for that call. If nothing else around it is transactional, you have no rollback and your row lock doesn't last until the save.
The fixes:
- Put
@Transactionalon the method that's called from outside (payRenthere), or - Move
withdrawinto a different bean and inject it, so the call goes through the proxy.
What you'd learn next
You now know why two transfers can lose money, and one solid way to stop it. Real backends need more:
- ✅ Race conditions, lost updates and a row-lock fix (this post)
- 🔒 Propagation:
REQUIRED,REQUIRES_NEW,NESTED, and what happens when one transactional method calls another - 🔒 Optimistic locking with
@Version, for when waiting on a lock is too costly - 🔒 Deadlocks: two transfers locking rows in opposite order, and how to avoid them
- 🔒 Database and Spring Data JPA: entities, relationships, JPQL and migrations
- 🔒 Validation and Exception Handling
- 🔒 Spring Security
- 🔒 Testing Spring Boot Applications
- 🔒 Docker and Deployment, then Microservices Fundamentals
- 🔒 Real-World Spring Boot Projects you can put on your CV
🚀 Go from zero to hero with Spring Boot
This post covered one idea from Module 8. The full Learn Spring Boot from Basic to Advanced course on DevTrail takes you through all of it: 13 modules and 86 hands-on lessons, including a full lesson on transaction propagation and isolation levels, and ending with real projects.
Every lesson has code you run and check right in your browser. No setup, no "works on my machine".
Module 1 is free. Start the Spring Boot course →

Top comments (0)