Kushagra Varshney’s Post

A quick question that made me curious: What actually happens behind the scenes when we use @Transactional in Spring Boot? Most of us just add the annotation and trust it to handle everything. But under the hood, something interesting is happening. Spring doesn’t directly modify your method. Instead, it creates a proxy around the bean. So when a transactional method is called, the flow looks like: Client → Proxy → Transaction Manager → Your Method → Commit/Rollback Here’s what the proxy does: • Starts a transaction before method execution • Executes your business logic • Commits if everything is fine • Rolls back if an exception occurs But here’s another catch 👇 Not all exceptions trigger rollback. By default, Spring only rolls back for: • Runtime exceptions (RuntimeException) • Errors (Error) But checked exceptions (like IOException, SQLException) 👉 do NOT trigger rollback by default So sometimes: • Your code throws an exception • But the transaction still commits 😳 If you want rollback for all exceptions, you need: @Transactional(rollbackFor = Exception.class) And one more important catch: The proxy only works when the method is called from outside the bean. If one method inside the same bean calls another method annotated with @Transactional, the call bypasses the proxy. So the transaction may not even start. That’s why sometimes: • Transactions don’t work as expected • Rollbacks don’t happen • Bugs are hard to trace Spring isn’t “magic” — it’s just smart use of proxies and AOP. Now the interesting question: If method A and method B are in the same bean, and B is annotated with @Transactional, and A calls B internally… 👉 How would you make sure the transaction actually works? #SpringBoot #BackendEngineering #Java #SystemDesign #Transactional #AOP

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories