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 }
Enter fullscreen mode
Exit fullscreen mode
Read, subtract, save. Run it once and it's perfect.…