Transactions in Controllers: A Red Flag in Clean Code

Day 27. I put @Transactional in my controller. My senior caught it in code review. That conversation changed how I think about layers. I had this: @RestController public class UserController {  @Transactional  @PostMapping("/users")  public ResponseEntity<?> createUser(@RequestBody User user) {   userRepository.save(user);   return ResponseEntity.ok("User created");  } } It worked. No errors. Everything looked fine. Looked clean. Until a senior looked at it. Here’s what actually happens: → Transaction starts at the controller → It stays open longer than needed → Higher chance of locks & performance issues → Blurred business logic boundaries That’s when it clicked. Transactions don’t belong in controllers. Controllers should: → Handle HTTP → Delegate work Not manage transactions. So I changed it. (see implementation below 👇) What I learned: → Transactions define business boundaries → They should live close to business logic (service layer) → Not at the API layer The hard truth: → Working code and well-designed code are two different things → Most tutorials only teach you the first one Writing working code is easy. Placing responsibility in the right layer is what makes you a backend developer. If your senior reviewed your controller today — would @Transactional be there? 👇 Drop your take #SpringBoot #Java #BackendDevelopment #CleanCode #Hibernate #JavaDeveloper

  • text

Hot take: Most Spring Boot bugs aren't code bugs. They're architecture bugs. Wrong layer. Wrong responsibility. Wrong boundary. The code runs fine. The system design is broken. Have you ever had a senior catch something like this in review? 👇

This is a very common mistake. I recently came across a method that had `@transactional` and inside it performed a database transaction and sent a message to Kafka, that was causing data inconsistency. The idea is to use it within the service layer where we have the business logic.

See more comments

To view or add a comment, sign in

Explore content categories