How does @Transactional actually work in Spring?

@Transactional declares a transaction boundary without writing it out. You don't call begin, commit and rollback yourself. You annotate a method, and Spring wraps it in a transaction at runtime. This keeps transaction handling out of business logic and keeps it consistent across a codebase.

The wrapping is done by Spring AOP. When the container creates a bean that has transactional methods, it doesn't hand out the bean itself. It hands out a proxy around it. A call to the proxy goes to a TransactionInterceptor, which does the following:

  1. Reads the transaction attributes.
  2. Asks the PlatformTransactionManager to start or join a transaction.
  3. Calls your real method.
  4. Commits or rolls back based on the outcome.

The proxy takes one of two forms:

  • JDK dynamic proxy. It implements the bean's interfaces. Callers holding a reference to the concrete class can't use it.
  • CGLIB proxy. It is a generated subclass of your class that overrides its methods. It can't intercept final methods or private methods.

Which one you get depends on configuration. That includes the proxyTargetClass setting and whether the bean implements interfaces. Spring Boot's defaults also differ from plain Spring's. Don't assume. Check it:

  • Log bean.getClass() on the injected reference.
  • Call AopUtils.isJdkDynamicProxy or AopUtils.isCglibProxy.

The key consequence is that the interceptor only runs when a call passes through the proxy. A call that reaches the target object some other way skips the transaction logic entirely. No error is raised and no warning is logged.

So when a transaction misbehaves, first find where the proxy sits in the call path. Do that before you adjust propagation, rollback rules or transaction manager configuration. If the call never went through the proxy, none of those settings were ever applied.

 Caller (another bean, holds the injected reference)
                 |
                 | orderService.place()
                 v
+----------------------------------------------------------+
| Proxy (JDK dynamic proxy OR CGLIB subclass)              |
|                                                          |
|  +---------------------------+     +------------------+  |
|  | TransactionInterceptor    |---->| Platform         |  |
|  | 1. read tx attributes     |<----| Transaction      |  |
|  | 2. start or join tx       |     | Manager          |  |
|  | 4. commit or rollback     |     |                  |  |
|  +-------------+-------------+     +------------------+  |
+----------------+-----------------------------------------+
                 |
                 | 3. call your real method
                 v
+----------------------------------------------------------+
| Target object (your class)                               |
|                                                          |
|  place() ----- this.audit() -----> audit()               |
|                                                          |
|  self-invocation: call stays on the target,              |
|  audit()'s @Transactional attributes are ignored         |
|  (no error, no warning)                                  |
+----------------------------------------------------------+

The TransactionInterceptor runs only when a call enters through the proxy (JDK dynamic proxy or CGLIB subclass), while a self-invocation inside the target object bypasses it and its transaction attributes.

Why is Spring @Transactional not working on self-invocation?

Inside a single bean, a call such as this.saveOrder() goes straight to the target object. The proxy wraps the bean from the outside, so it only sees calls that arrive through the reference the container handed out. Nothing fails or warns. The annotation is simply never consulted.

Take an OrderService whose non-transactional importBatch() loops over records and calls its own @Transactional saveOrder(). Each insert runs in auto-commit mode, so a failure halfway through leaves the earlier rows committed. The fix moves saveOrder() into a separate OrderWriter bean, injects it into OrderService, and has importBatch() call orderWriter.saveOrder(). That call crosses a proxy boundary, and the transaction interceptor runs.

The same blind spot shows up in other forms:

  • Private and final methods. Class-based proxies work by subclassing and overriding, so these methods can't be intercepted. Treat public methods as the only safe target.
  • Objects created with new. The container never sees the instance, so it never wraps it in a proxy.
  • Constructors and @PostConstruct. The proxy is created after initialization finishes, so these calls reach the raw target.
Cause Symptom Quick check
Self-invocation via this Partial writes survive a failure Does the caller live in the same class?
Private or final method Annotation ignored Check the method modifiers
Instance created with new No transaction anywhere on the object Was the instance injected by the container?
Constructor or init callback Startup writes are not atomic Is the call made before the bean is fully initialized?
// BEFORE: self-invocation bypasses the proxy
@Service
public class OrderService {
    private final OrderRepository repo;
    public OrderService(OrderRepository repo) { this.repo = repo; }

    public void importBatch(List<Order> orders) {
        for (Order o : orders) {
            saveOrder(o); // same as this.saveOrder(o): no proxy, @Transactional ignored
        }
    }

    @Transactional
    public void saveOrder(Order o) { repo.save(o); }
}

// AFTER: the transactional method lives in another bean
@Service
public class OrderWriter {
    private final OrderRepository repo;
    public OrderWriter(OrderRepository repo) { this.repo = repo; }

    @Transactional
    public void saveOrder(Order o) { repo.save(o); }
}

@Service
public class OrderService {
    private final OrderWriter orderWriter; // injected reference is the proxy
    public OrderService(OrderWriter orderWriter) { this.orderWriter = orderWriter; }

    public void importBatch(List<Order> orders) {
        for (Order o : orders) {
            orderWriter.saveOrder(o); // crosses the proxy, interceptor runs
        }
    }
}

The first OrderService calls its own @Transactional method through 'this', so the proxy never sees the call; the fixed version moves saveOrder() into an injected OrderWriter bean so the call goes through the transactional proxy.

What are the alternatives for fixing self-invocation?

There are four ways to get the inner call to pass through transactional infrastructure. Each one moves complexity to a different place.

Move the method to a separate bean. This is the cleanest option because the call crosses a real proxy boundary. The risk is design drift: you can end up with thin classes like OrderServiceTx that exist only to satisfy the proxy, which makes the domain harder to read.

Lazy self-injection or ObjectProvider. Inject ObjectProvider<OrderService> and call provider.getObject().process(...) so the call goes through the proxy. This works, but it is a circular dependency in disguise, and recent Spring Boot defaults reject circular references. A reader sees an odd lookup with no obvious reason for it, so add a comment explaining why it is there.

TransactionTemplate. Wrapping the work in transactionTemplate.execute(status -> ...) makes the boundary explicit and easy to test with no proxy involved. The cost is verbosity, and transaction plumbing now sits inside business logic.

AspectJ weaving. Advice is woven into the bytecode, so self-calls and non-public methods are covered. You pay for it with build-time or load-time weaving setup that every developer and CI pipeline has to understand.

Option Reliability Code impact Maintenance cost
Separate bean High Moderate, adds classes Low
ObjectProvider High Small, but obscure Medium
TransactionTemplate High, explicit Verbose Low
AspectJ weaving High None in code High, build tooling

Most teams should default to a separate bean when the split matches a real responsibility. Use TransactionTemplate when you need fine-grained boundaries, such as batch loops. Reserve AspectJ for platforms that already run weaving. Treat ObjectProvider as a documented, local fix rather than a pattern to spread.

@Service
public class OrderService {

    private final OrderRepository orders;
    private final TransactionTemplate tx;
    // Lazy handle to this bean's proxy; resolved on first use, not at construction.
    private final ObjectProvider<OrderService> self;

    public OrderService(OrderRepository orders,
                        PlatformTransactionManager txManager,
                        ObjectProvider<OrderService> self) {
        this.orders = orders;
        this.tx = new TransactionTemplate(txManager);
        this.self = self;
    }

    // TransactionTemplate: one explicit transaction per item, no proxy involved.
    // A failure rolls back only the current item.
    public void importBatch(List<Order> batch) {
        for (Order order : batch) {
            tx.executeWithoutResult(status -> orders.save(order));
        }
    }

    // ObjectProvider: route the inner call through the proxy.
    // Calling this.process(id) here would bypass @Transactional.
    public void processAll(List<Long> ids) {
        for (Long id : ids) {
            self.getObject().process(id);
        }
    }

    @Transactional
    public void process(Long id) {
        Order order = orders.findById(id).orElseThrow();
        order.markProcessed();
    }
}

Two self-invocation fixes in one service: TransactionTemplate creates an explicit per-item transaction boundary, and ObjectProvider sends the inner call through the Spring proxy so @Transactional applies.

How does transaction propagation interact with proxies?

Propagation is a property of the proxy's interceptor, not of the annotated method. When a call enters through the proxy, the interceptor checks whether a transaction is already bound to the current thread and decides what to do based on the propagation setting.

With REQUIRED, the default, the inner method joins the existing transaction. It uses the same connection and the same commit. If the inner method marks the transaction rollback-only, the whole unit rolls back. With REQUIRES_NEW, the interceptor suspends the outer transaction, takes a second connection, and commits or rolls back the inner work on its own.

None of this happens on self-invocation. A REQUIRES_NEW method called through this silently runs inside the caller's transaction, so the isolation you thought you had does not exist.

REQUIRES_NEW fits work that must survive the outer outcome, such as audit records of failed attempts. It has a cost. The suspended outer transaction keeps its connection and its row locks while the inner transaction runs.

Illustrative estimate: assume a pool of 20 connections and 20 concurrent requests. Each request holds one connection for its outer transaction and then needs a second for REQUIRES_NEW. Every connection is now checked out, and every thread waits for one more. Nothing completes until the pool's acquisition timeout fires.

Locks cause a related problem. If the inner transaction updates a row that the suspended outer transaction has locked, the inner transaction waits on a lock its own thread will never release. The request stalls until the database's lock-wait timeout ends it.

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
public class PaymentService {
    private final AuditService audit; // separate bean, so calls go through its proxy
    private final PaymentRepository payments;

    public PaymentService(AuditService audit, PaymentRepository payments) {
        this.audit = audit;
        this.payments = payments;
    }

    @Transactional // REQUIRED: binds connection #1 to this thread
    public void charge(long orderId) {
        audit.recordAttempt(orderId); // via proxy: outer suspended, connection #2 taken
        payments.debit(orderId);      // may throw; the audit row is already committed
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void brokenAudit(long orderId) {
        // Never called via this.brokenAudit(...): self-invocation bypasses the
        // proxy and the method would silently join the caller's transaction.
    }
}

@Service
class AuditService {
    private final AuditRepository auditLog;

    AuditService(AuditRepository auditLog) { this.auditLog = auditLog; }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void recordAttempt(long orderId) {
        // Commits independently; keep it short and avoid rows the outer tx locked.
        auditLog.save(new AuditEntry(orderId, "CHARGE_ATTEMPT"));
    }
}

REQUIRES_NEW isolates the audit write only because it lives in a separate bean reached through its proxy; while it runs, each request holds two connections, which is the source of the pool-exhaustion risk described above.

Why does my transaction commit when an exception is thrown?

By default, Spring rolls back only on RuntimeException and Error. A checked exception such as IOException propagates out of the proxy and the transaction still commits. This default follows the old EJB convention that checked exceptions represent recoverable business outcomes. To roll back on checked exceptions, declare @Transactional(rollbackFor = Exception.class). The other silent commit happens when the method catches and logs the exception itself. The proxy only sees a normal return, so it commits. If you must catch, rethrow, either the original exception or a wrapping unchecked one, so the exception reaches the interceptor.

A less obvious failure involves two beans. OrderService.place() is @Transactional and calls auditService.record(), which uses the default REQUIRED propagation and so joins the outer transaction. record() throws a RuntimeException. Inside place(), the call to record() is wrapped in a try/catch so that a failed audit doesn't block the order.

When the exception passes through the inner proxy, Spring can't roll back a transaction it doesn't own, so it marks the shared transaction rollback-only. place() swallows the exception and returns normally. The outer proxy then attempts to commit, finds the rollback-only flag, rolls back anyway and throws UnexpectedRollbackException. The caller believed the order was saved, and it wasn't.

There are several ways to resolve this:

  • Make record() handle its own failure internally, so no exception crosses its proxy boundary.
  • Annotate record() with REQUIRES_NEW so its failure rolls back only its own transaction. Keep in mind the locking hazard described in the previous section.
  • Use noRollbackFor on record() for exceptions that are genuinely harmless.
  • Let the exception propagate if the whole unit of work really should fail.

When should you avoid class-level @Transactional and broad transaction scopes?

Annotating a class with @Transactional applies the same transaction settings to every public method the proxy intercepts. That is convenient when a service is small and every method writes. As the class grows, it starts wrapping methods that never needed a transaction: lookups, report queries, and methods that call other systems.

The cost comes from what a transaction holds while it is open. A transaction typically keeps a pooled database connection for its whole duration, and any row locks it takes stay held until commit or rollback. If a transactional method calls a payment gateway or another internal service and that call takes several seconds, the connection and the locks are held for those seconds too. Under load, this exhausts the pool and increases lock contention, even though the database work itself takes milliseconds. A remote call inside a transaction also cannot be rolled back. If the remote side succeeds and the local commit then fails, the two systems disagree, and the transaction gives no protection against that.

Some practical rules:

  • Put boundaries on the service method that represents one unit of work. That method should do one consistent set of writes that must succeed or fail together.
  • Keep remote calls outside the transaction. Have a non-transactional orchestrating method make the external call, then delegate to a transactional method on a separate bean so the proxy applies. For cross-system consistency, use explicit patterns such as an outbox table or compensating actions.
  • Mark read paths explicitly. Use readOnly = true on query methods, or give them no transaction where that is safe.

When transactions are placed deliberately, you can find where one starts and ends by reading a single method. With a class-level default, you have to reason about every public method. The narrower placement also makes it less likely that a held connection or lock surprises you in production.

How can you verify that a transaction is really active?

Guessing wastes time. Each of these four checks takes a few minutes and tells you exactly where the transaction boundary is.

Read the transaction manager's own log

Set org.springframework.transaction to DEBUG. If you use JPA, also set org.springframework.orm.jpa. The transaction manager logs when it creates a new transaction, joins an existing one, suspends one, commits and rolls back, and it names the method or definition involved. If your method runs and none of those lines appear, no proxy intercepted the call. That points straight back to self-invocation, a non-public method or a bean Spring doesn't manage.

Assert at the suspect line

Call TransactionSynchronizationManager.isActualTransactionActive() where you expect a transaction, either temporarily or behind an assertion. It reports whether a real transaction is bound to the current thread. This catches cases where a method looks transactional but runs with only synchronization active, for example under SUPPORTS with no outer transaction.

Check what you injected

Log bean.getClass() or use AopUtils.isAopProxy(bean). A CGLIB subclass or a JDK proxy confirms that interception is possible. A plain class name means no advice will ever run on calls to that bean.

Test boundaries without hiding them

A test annotated @Transactional opens its own transaction and rolls it back afterward. Every service call joins that outer transaction, so a missing or misplaced annotation in production code goes unnoticed. Slice tests such as @DataJpaTest behave this way by default. Structure boundary tests so they reveal the real behavior:

  • Leave the test method non-transactional, or mark it Propagation.NOT_SUPPORTED.
  • Call the service and force a failure partway through.
  • Verify the stored state in a separate transaction, such as a fresh repository call or a TransactionTemplate.
  • Clean up data explicitly afterward, because nothing rolls it back for you.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to spring transactional not working, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.