How @Transactional Works in Spring Boot

One of the toughest questions in every senior Java interview: “How does @Transactional actually work in Spring Boot?” Most candidates stop at: ➡️ “It manages database transactions automatically.” That’s not wrong — but it’s far from enough. Here’s what really happens under the hood When you use @Transactional, Spring doesn’t modify your class directly. It creates a proxy using Spring AOP. So when your method is called: 👉 You’re not calling your code directly 👉 You’re calling the proxy first That proxy: 1️⃣ Intercepts the method call 2️⃣ Delegates to a TransactionInterceptor 3️⃣ Uses a PlatformTransactionManager 4️⃣ Starts the transaction (via ThreadLocal context) 5️⃣ Executes your method 6️⃣ Commits or rolls back based on outcome 💡 Your business code never manages transactions — Spring does it transparently. --- ### ⚠️ But here’s where things break in production 1. Self Invocation (Silent Failure) Calling a @Transactional method within the same class bypasses the proxy. ❌ No transaction is applied ✅ Fix: Call via another bean or through Spring context --- 2. Checked Exceptions Don’t Rollback By default, only RuntimeException triggers rollback. ❌ Checked exception → transaction commits ✅ Fix: @Transactional(rollbackFor = Exception.class) --- 3. Wrong Propagation = Data Inconsistency - REQUIRED → joins existing (safe) - REQUIRES_NEW → starts new (can cause partial commits) - NESTED → savepoints (partial rollback) ❌ Payment fails but order is committed 👉 Classic production issue --- ### 🧠 What senior engineers understand ✔️ Transaction context is maintained using ThreadLocal ✔️ Transactions should wrap business use cases, not just DB calls ✔️ Isolation levels matter for concurrency ✔️ Lazy loading fails outside transaction boundaries ✔️ readOnly = true improves performance --- ### 🎯 The answer that gets the offer @Transactional works via Spring AOP proxies. The proxy intercepts method calls and delegates transaction management to a TransactionManager. However, it can silently fail due to proxy bypass (self-invocation), default rollback rules, and incorrect propagation settings — leading to real production issues if not handled carefully. The gap between knowing @Transactional and understanding it deeply 👉 is the gap between getting shortlisted and getting the offer. #Java #SpringBoot #BackendEngineering #SystemDesign #TechInterviews #S

To view or add a comment, sign in

Explore content categories