Spring Transaction Propagation: REQUIRED vs REQUIRES_NEW

You have two @Transactional methods. The outer service calls the inner one. The inner method fails, but you want to handle the error and continue the outer transaction. Why does the whole thing roll back by default? This isn't a bug. It's Spring's transaction propagation. By default, Spring uses `Propagation.REQUIRED`. This means if a transaction already exists, the inner method just joins it. They become one single unit of work. If any part fails, the whole thing is marked for rollback. Simple and safe. But what if that inner method *must* succeed on its own? Think of logging a critical audit record. That's when you use `Propagation.REQUIRES_NEW`. This tells Spring to pause the current transaction and start a completely new, independent one. This new transaction can commit or fail on its own, without affecting the outer one. The audit log gets saved even if the main operation later rolls back. The trade-off? Performance. `REQUIRES_NEW` is more resource-intensive because it often requires a separate database connection. So don't use it everywhere. Reserve it for specific, independent tasks where a separate outcome is essential. Understanding the difference gives you precise control. #Java #SpringBoot #SoftwareDevelopment #BackendDevelopment #SpringFramework #Transactions #SystemDesign #DeveloperTips

To view or add a comment, sign in

Explore content categories