A Spring service annotated with @Transactional that throws a business exception and, against every expectation, still commits the writes that already happened, is one of the most confusing bugs to track down, precisely because the code looks correct on the page. The annotation is there, the exception is genuinely thrown, and yet the database retains a trace of exactly what should have been rolled back. Understanding why requires understanding how @Transactional is actually implemented, not just what it's supposed to do.
The mechanism: a proxy, not an instruction
@Transactional isn't a language keyword or an instruction executed at call time. It's an annotation read by Spring AOP, which wraps the Spring bean in a proxy (a JDK dynamic proxy for an interface, CGLIB for a concrete class). When another bean calls an annotated method, the call goes through that proxy, which opens a transaction, delegates to the real method, then commits or rolls back depending on the outcome.
The trap shows up when the call happens from within the same class, internally, without going through the proxy:
@Service
public class OrderService {
private final OrderRepository orderRepository;
private final AuditLogService auditLogService;
public OrderService(OrderRepository orderRepository, AuditLogService auditLogService) {
this.orderRepository = orderRepository;
this.auditLogService = auditLogService;
}
public void cancelOrder(Long orderId) {
// internal call: this is NOT intercepted by the transaction proxy
this.doCancelOrder(orderId);
}
@Transactional
public void doCancelOrder(Long orderId) {
Order order = orderRepository.findById(orderId)
.orElseThrow(() -> new OrderNotFoundException(orderId));
order.cancel();
orderRepository.save(order);
if (order.getTotal().compareTo(BigDecimal.ZERO) > 0) {
throw new RefundRequiredException(orderId);
}
}
}
Here, cancelOrder calls doCancelOrder through this, meaning directly on the real object, completely bypassing the proxy. The @Transactional annotation on doCancelOrder is therefore ignored: no transaction gets opened, and if orderRepository.save() relies on the connection's default auto-commit, the change is already persisted to the database before the exception is even thrown. The expected rollback never had a chance to exist.
Diagnosing: making the proxy visible
The most reliable way to confirm whether a transaction is actually active is to turn on the transaction framework's logging:
# application.yml
logging:
level:
org.springframework.transaction: TRACE
org.springframework.orm.jpa: DEBUG
A correctly intercepted call produces an explicit line: Creating new transaction with name [...]: PROPAGATION_REQUIRED, ISOLATION_DEFAULT. The total absence of that line at the time doCancelOrder is called is direct proof of the problem, far more reliable than re-reading the source.
In tests, TransactionSynchronizationManager.isActualTransactionActive() lets you assert programmatically that a transaction is genuinely open at a given point, turning this diagnostic into an automated assertion rather than a manual log inspection every time a regression is suspected.
The fix: avoid self-invocation, don't work around it
The cleanest fix is to not call the transactional method from within the same class at all, and instead route the call through another bean, where Spring will naturally inject the proxy:
@Service
public class OrderCancellationService {
@Transactional
public void doCancelOrder(Long orderId) {
// ...
}
}
@Service
public class OrderService {
private final OrderCancellationService cancellationService;
public OrderService(OrderCancellationService cancellationService) {
this.cancellationService = cancellationService;
}
public void cancelOrder(Long orderId) {
cancellationService.doCancelOrder(orderId); // correctly goes through the proxy
}
}
Splitting the service into two distinct classes is preferable to the workaround of fetching the current proxy via AopContext.currentProxy() with @EnableAspectJAutoProxy(exposeProxy = true): the latter works, but couples application code to AOP framework implementation details, and breaks silently if someone removes exposeProxy = true later without understanding why it was needed.
The second trap: not every exception triggers a rollback
Even with a call correctly intercepted by the proxy, a second trap is waiting: by default, Spring only triggers a rollback on an unchecked RuntimeException or an Error. A checked exception (one that extends Exception directly) does not trigger a rollback by default, even if it propagates out of the annotated method.
@Transactional
public void processPayment(Long orderId) throws PaymentGatewayException {
Order order = orderRepository.findById(orderId).orElseThrow();
order.markAsPaid();
orderRepository.save(order);
paymentGatewayClient.charge(order); // throws PaymentGatewayException (checked)
}
If PaymentGatewayException extends Exception rather than RuntimeException, the order gets marked as paid in the database even though the payment actually failed, because Spring commits the transaction despite the propagated exception. The explicit fix is rollbackFor:
@Transactional(rollbackFor = PaymentGatewayException.class)
public void processPayment(Long orderId) throws PaymentGatewayException {
// ...
}
This is documented behavior, but it's rarely checked until someone has already been bitten by it, precisely because it goes against the intuition that any exception should roll back the ongoing transaction.
The tradeoffs of propagation
Spring offers several propagation types, and REQUIRES_NEW is often used to isolate a side effect that must survive even if the enclosing transaction fails, typically an audit log entry:
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void logAuditEvent(AuditEvent event) {
auditRepository.save(event);
}
That choice has a real cost: REQUIRES_NEW suspends the current transaction and opens a new one, consuming an extra connection from the pool while both transactions coexist. Under heavy load, with a connection pool sized for normal usage, stacking REQUIRES_NEW across frequently called paths can exhaust the pool and cause timeouts that have nothing to do with the original business logic.
When @Transactional isn't enough
Network calls inside a transaction are a frequent trap: calling an external HTTP API (a payment gateway, a third-party service) from a @Transactional method keeps the database connection open, along with the locks held on the modified rows, for the entire duration of that network call, potentially several seconds. Under concurrent load on the same rows, this can cause cascading lock contention. The right approach is to pull the network call out of the transaction, committing the local state first, then handling the external call separately with its own compensation logic in case of failure.
Read-only transactions benefit from an explicit optimization via @Transactional(readOnly = true), which tells Hibernate to disable automatic dirty checking on loaded entities, reducing memory and CPU overhead on high-traffic read endpoints.
Tests using @Transactional deserve particular care: Spring Test automatically rolls back the transaction at the end of each test, which is convenient for isolation, but can mask bugs tied to Hibernate's flush timing (a query that depends on an explicit flush doesn't necessarily behave the same way in production, where the flush happens at commit time). TestEntityManager.flush() or @Commit let you verify that behavior explicitly instead of trusting it by default.
Catching long transactions at the connection pool level
The logging-based diagnosis described earlier confirms whether a transaction opened at all, but it doesn't tell you how long a connection stayed checked out of the pool, which is exactly what matters for the network-call-inside-a-transaction trap. HikariCP, Spring Boot's default connection pool, has a built-in leak detector that logs a warning with the full stack trace whenever a connection is held longer than a configured threshold:
# application.yml
spring:
datasource:
hikari:
maximum-pool-size: 10
leak-detection-threshold: 2000
With this set, a @Transactional method that calls a slow payment gateway from inside the transaction produces a log entry pointing at the exact line that acquired the connection, once it's held past two seconds, without waiting for the pool to actually exhaust under production load. This turns a theoretical concern raised in code review into a concrete, timestamped signal visible in logs the first time it happens in staging, which is considerably cheaper than discovering it through a HikariPool-1 - Connection is not available, request timed out error during a traffic spike.
It's worth pairing this with Micrometer's HikariCP metrics (hikaricp.connections.active, hikaricp.connections.pending) exported to whatever monitoring stack is in place, so a creeping increase in active connections shows up as a trend on a dashboard well before it becomes an incident.
Takeaway
@Transactional works through an AOP proxy, which means two rules worth remembering in practice: an internal call within the same class never goes through that proxy, and only unchecked exceptions trigger a rollback without explicit configuration. Both behaviors are documented, neither is intuitive, and both are almost always discovered in production rather than in a code review.
