Transactions in Spring
@Transactional's proxy, propagation types, isolation, read-only, rollback rules, and the checked exception that does not roll back.
@Transactional is one word that does a great deal, and the reason it surprises people is that the word is not where the work happens. Spring does not rewrite your method. It wraps your bean in a proxy, and the proxy is what starts and ends the transaction.
Every trap in this lesson is a consequence of that one sentence.
The proxy, and the call that never reaches it
When a bean is annotated, the object Spring hands to everyone else is not your object. It is a generated subclass (or a JDK interface proxy) that looks identical, and whose job is: begin a transaction, call the real method, commit or roll back.
another bean. A controller or another service holds a reference to what it thinks is your service. It is holding the proxy — Spring injected that, not your instance.
proxy intercepts. The proxy reads the annotation, asks the transaction manager for a connection, and begins. Your code has not run yet.
your method. Now your body runs, with a persistence context bound to this transaction. Dirty checking works because that context exists and is open.
it returns. Control passes back through the proxy, which flushes and commits — or rolls back, if what came out was an exception it rolls back for.
this.debit(id). A call from inside the same class. `this` is your real object, not the proxy, so nothing intercepts it. The annotation is still there and does nothing at all.
Self-invocation, measured
That last frame is the trap, and it is worth seeing rather than being warned about. Two calls to the same annotated method, differing only in who calls it:
@Service
public class Money {
private final Accounts accounts;
/** No annotation here. It calls the annotated method on `this`. */
public void selfInvoked(Long id) {
this.debit(id);
}
@Transactional
public void debit(Long id) {
Account a = accounts.findById(id).get();
a.balance -= 10; // dirty checking is supposed to write this
}
}### A: calling debit() from INSIDE the bean (this.debit)
### inside debit(): transaction active? false
### balance for ana: 100 (was 100)
### B: calling debit() from OUTSIDE the bean
### inside debit(): transaction active? true
### balance for bo: 90 (was 100)Same method. Same annotation. In the first case there is no transaction, so there is no persistence context to hold a managed entity, so dirty checking never happens and the debit is silently discarded. No exception. No warning. A log line would show the select and no update, and only if anyone were looking.
Three ways out, in the order you should prefer them:
- Move the method to another bean. Usually the right answer, because a method that needs its own transaction is usually a different responsibility.
- Inject the proxy into itself —
@Lazyon a self-reference, thenself.debit(id). It works and it looks strange, which is honest: it looks strange because something is. AopContext.currentProxy(). Works, requiresexposeProxy = true, and ties your code to Spring's AOP. Last resort.
Rollback rules are not what you expect
Ask most engineers what happens when a @Transactional method throws, and they will say it rolls back. That is true for unchecked exceptions and false for checked ones:
### C: debit, then throw a CHECKED exception
### caught Checked
### balance for cy: 90 (was 100)
### D: debit, then throw an UNCHECKED exception
### caught Unchecked
### balance for di: 100 (was 100)Read C again. The method debited the account, threw an exception, the caller caught it — and the money moved anyway. The transaction committed on the way out because a checked exception is, by Spring's default, a business outcome rather than a failure.
That default comes from EJB and is defensible in theory: a checked exception is a declared, expected result. In practice, teams write checked exceptions for exactly the cases where they mean stop, undo this. So say it:
@Transactional(rollbackFor = Checked.class)### E: checked again, but with rollbackFor = Checked.class
### caught Checked
### balance for ed: 100 (was 100)Propagation: what happens when a transaction is already running
Propagation answers one question: this method wants a transaction, and the caller already has one — now what?
| Propagation | With a transaction already running |
|---|---|
REQUIRED (default) | join it. One transaction, one commit, all-or-nothing together |
REQUIRES_NEW | suspend the caller's, start a second, independent one |
NESTED | a savepoint inside the caller's; can roll back alone |
SUPPORTS | join if there is one, otherwise run with none |
MANDATORY | throw if there is not one |
NEVER | throw if there is one |
The two that matter are the first two, and the distinction is worth stating as a rule: REQUIRED means your work dies with the caller's; REQUIRES_NEW means it survives.
That is what makes REQUIRES_NEW the right choice for an audit record or a failed-attempt log — the thing you most want written is the record of the operation that just failed, and under REQUIRED it rolls back along with everything else.
It also carries a real cost that is easy to miss: REQUIRES_NEW takes a second connection from the pool while the first is still held open and suspended. A request that nests three of those holds four connections. On a pool of ten, that is a deadlock waiting for traffic.
Isolation, briefly and honestly
Isolation decides what one transaction can see of another's uncommitted or in-flight work:
| Level | Prevents |
|---|---|
READ_UNCOMMITTED | nothing; you can read another transaction's uncommitted rows |
READ_COMMITTED | dirty reads |
REPEATABLE_READ | dirty reads and non-repeatable reads |
SERIALIZABLE | all of it, including phantoms |
The honest advice is: leave it alone. PostgreSQL defaults to READ_COMMITTED, MySQL's InnoDB to REPEATABLE_READ, and both are right for almost all application work. Raising it trades throughput for a guarantee you usually do not need, and raising it for one method is an invitation to a lock ordering problem that appears under load and nowhere else.
Reach for the locking below instead. It is more precise and it fails in a way you can catch.
Optimistic locking is a column, not a lock
Add one field:
@Entity
public class Account {
@Id public Long id;
public int balance;
@Version public Long version;
}Hibernate now includes the version in every update's where clause and increments it:
### F: @Version on an ordinary update
### version on load: 0, balance 100
### version afterwards: 1Nothing is locked. Nobody waits. The check happens at write time: if the row's version is no longer the one you read, your update matches zero rows and Hibernate knows somebody changed it underneath you.
### G: two writers, one stale read
### user A read version 0
### user B has written and bumped the version
### user A now commits...
### org.springframework.orm.ObjectOptimisticLockingFailureExceptionIn a real system B's transaction has committed and B's change stands; A's is rejected and A must retry with fresh data. That is the whole trade: cheap when conflicts are rare, and it turns a silent lost update into a loud exception.
Without @Version, the same sequence produces no error at all. A read the change, B read the same row, both wrote, and whoever wrote last silently erased the other. Nobody finds out until the numbers stop adding up.
Pessimistic locking is the other answer: SELECT ... FOR UPDATE, via @Lock(LockModeType.PESSIMISTIC_WRITE). It holds a database lock for the length of the transaction, so the second reader waits. Correct, and expensive, and a source of deadlocks if two transactions take locks in different orders. Use it when conflicts are the normal case — seat booking, stock decrement on a hot item — and optimistic everywhere else.
Under the hood: what "begin a transaction" actually binds, and how REQUIRES_NEW suspends it
The proxy section above already names the mechanism at a high level — a TransactionInterceptor wraps your method — and the low-level-design course's own deep-dive into JDK dynamic proxies covers why self-invocation bypasses any proxy in general. This section goes one level lower than either: what the interceptor actually does with a PlatformTransactionManager, and why that specific design is what makes propagation levels behave the way the table above says they do, rather than being an arbitrary set of named options.
Every @Transactional call is intercepted by a TransactionInterceptor, which delegates to a PlatformTransactionManager — for JPA, that is a JpaTransactionManager. Calling getTransaction(definition) on it does not "start a transaction" in the abstract; concretely, for a fresh REQUIRED call with no transaction already running, it asks the EntityManagerFactory for a new EntityManager, begins a JDBC transaction on the connection that EntityManager acquires, and then binds both the EntityManager and the connection to the current thread via TransactionSynchronizationManager — a set of ThreadLocals keyed by resource factory (the EntityManagerFactory, the DataSource). Anything else running on that same thread that asks for "the current EntityManager" — another @Repository, another @Service method called deeper in the same call stack — finds the one already bound to the thread and reuses it, which is the actual mechanism behind "join the caller's transaction": there is no negotiation between beans, just a thread-local lookup that happens to find something already there.
That thread-local binding is exactly what REQUIRES_NEW has to work around, and seeing it this way makes the "suspend" language precise rather than metaphorical. When the interceptor sees REQUIRES_NEW and a transaction is already bound to the thread, JpaTransactionManager.suspend() removes the currently bound EntityManager and connection from TransactionSynchronizationManager's thread-locals and hands them back wrapped in a SuspendedResourcesHolder, kept on the Java stack (as a local variable inside the interceptor's call), not the database. The thread's thread-locals are then genuinely empty, so the next getTransaction() call has nothing bound to find and creates a second, independent EntityManager, a second JDBC connection, and a second database transaction, bound fresh to the same thread. When that inner method returns, the interceptor commits or rolls back the inner transaction, unbinds its resources, and resume() puts the original SuspendedResourcesHolder's EntityManager and connection back into the thread-locals — the outer transaction is exactly where it left off, because nothing about it was ever touched, only unreachable for the duration.
This is precisely why the cost this lesson already names — "a second connection from the pool, while the first is still held open and suspended" — is not a configuration detail but a structural consequence: the suspended EntityManager's connection is never released back to the pool during the suspension, because releasing it would mean committing or rolling back a transaction nobody asked to end. It is simply parked, unreachable through the normal thread-local lookup, for as long as the nested REQUIRES_NEW call runs.
Try it yourself
Reason through what REQUIRES_NEW leaves running
A @Transactional(propagation = Propagation.REQUIRED) method placeOrder() calls a second method logAttempt() annotated @Transactional(propagation = Propagation.REQUIRES_NEW) from another bean, purely to record that an order attempt happened regardless of whether placeOrder() ultimately succeeds. Partway through logAttempt(), before it returns, an unrelated bug throws an unchecked exception inside placeOrder() itself, after logAttempt() has already committed.
Using the suspend/resume mechanism above: does placeOrder()'s rollback undo what logAttempt() wrote? And separately — while logAttempt()'s inner transaction is running, how many database connections does this call chain hold at once, and why?
Trace the thread-locals through suspend, the inner commit, and resume
No, logAttempt()'s write survives. By the time placeOrder() throws, logAttempt()'s REQUIRES_NEW transaction has already been committed by the interceptor and its resources unbound and released — the outer transaction's later rollback only ever acts on the EntityManager/connection that was resumed after logAttempt() returned, which never saw the logging write at all, because that write happened on a completely different EntityManager bound to the thread only during the inner call. This is the entire reason REQUIRES_NEW is the right choice for an audit or attempt log: its commit is not entangled with the outer transaction's eventual outcome in either direction. On the connection count: while logAttempt()'s inner transaction is actually running, the call chain holds two connections at once — the outer transaction's connection, suspended and parked in a SuspendedResourcesHolder rather than released to the pool, plus the inner transaction's own freshly acquired connection — which is exactly the cost this lesson's propagation section already names, made concrete: nesting REQUIRES_NEW calls three deep would hold four connections simultaneously, all from the same request.
Misconceptions
- "Propagation levels are just configuration flags the transaction manager reads and applies uniformly."
REQUIREDandREQUIRES_NEWdiffer in a real, structural way, not a config toggle:REQUIREDperforms no suspend/resume at all and simply reuses whateverEntityManagerand connection are already thread-bound, whileREQUIRES_NEWactively removes the current thread-local resources, parks them off the database entirely, creates independent ones, and later restores the originals. The two are different code paths throughAbstractPlatformTransactionManager, not two settings of the same one. - "Since @Transactional uses ThreadLocal binding, it's safe to assume the current transaction is visible anywhere in the request, including code dispatched to another thread." Thread-local means exactly what it says: bound to the thread that began the transaction. Work handed to another thread — a thread pool,
@Async, a manually createdThread— starts with empty thread-locals on that thread and either silently begins its own new transaction (underREQUIRED) or, if the method requires an existing one (MANDATORY), throws, because from the new thread's perspective the outer transaction genuinely does not exist there.
Sources
- Spring Framework reference documentation, "Transaction Management" —
PlatformTransactionManager,TransactionSynchronizationManager, and the suspend/resume mechanics behindREQUIRES_NEW. - Spring Framework Javadoc,
org.springframework.transaction.support.AbstractPlatformTransactionManager— thesuspend()/resume()methods andSuspendedResourcesHolder. - Spring Framework reference documentation, "Using @Transactional" — the proxy mechanism and the self-invocation limitation this lesson's earlier sections already draw on.