Skip to content

    System Design

    Spring @Transactional: Proxies, Rollback Rules, Propagation

    Learn how Spring's @Transactional works: the proxy, rollback rules, propagation and the self-invocation trap, each proven by a runnable Spring Boot lab on H2.

    By Published 12 min read

    Share

    Standard lessonintermediateSpring Boot labBackend System Design

    Before this: ACID Transactions and Isolation Levels

    What you'll learn: By the end of this lesson you will be able to explain what @Transactional does at run time (a proxy that wraps the call), predict which exceptions roll a transaction back and which silently commit, say why a method called from inside its own class gets no transaction, choose between REQUIRED, REQUIRES_NEW and NESTED, and read the Spring lab's captured output to confirm each rule.

    Picture a kitchen order ticket. The cook either makes every dish on the ticket or voids the whole ticket. Somebody at the pass decides where the ticket starts and ends and voids it when a dish fails. In a Spring application that somebody is not your code but a thin wrapper Spring puts around your service, and it only works while you call the service the way the wrapper expects.

    The database side (atomicity, isolation, what a commit promises) belongs to the lesson on ACID and isolation levels, written alongside this one; the overview is in Databases Basics. This lesson covers the Spring side: where the boundary goes and how it quietly moves.

    Verified with Spring Boot 4.1.2 (Spring Framework 7.0.10), Java 25, H2 2.4.240 and the Spring Framework reference documentation, on 2026-12-01.

    The core idea

    @Transactional is metadata. A Spring proxy reads it and wraps each call that comes in from outside the bean in "begin, run, then commit or roll back". Everything else follows from that sentence: the rollback rules decide which outcome a thrown exception selects, propagation decides what happens when a transaction already exists, and any call that never passes through the proxy is not wrapped at all.

    Three illustrations run through the lesson:

    • Minimal example: a two-write checkout that commits, or rolls both writes back, in the lab (rows 1 and 2).
    • Realistic example: ShopStream's checkout in "In practice", where a business exception turns into a committed oversell.
    • Failure example: a self-invoked method and a caught exception, both of which look transactional and are not.

    What the annotation really does

    The Spring reference says the support "is enabled via AOP proxies" and that the advice is "driven by metadata": the combination yields a proxy that uses a TransactionInterceptor together with a TransactionManager to drive transactions around method invocations. Spring Boot auto-configures JdbcClient and embedded databases such as H2 when they are on the classpath, so this lab needs no XML and no manual manager wiring.

    A call through the Spring proxyCaller to Proxy (call); Proxy to Tx manager (begin); Proxy to Checkout (invoke); Checkout to ShopRepository; ShopRepository to H2 database (SQL)Caller: controller or testCallercontroller ortestProxy: tx interceptorProxytx interceptorCheckout: your serviceCheckoutyour serviceTx manager: begin, commitTx managerbegin, commitShopRepository: SQLShopRepositorySQLH2 database: in memoryH2 databasein memorycallbegininvokeSQL

    Figure 1. The caller holds the proxy, not your object. How to read this: the caller invokes the proxy, which asks the transaction manager to begin, then calls your service. The repository's SQL runs on the connection the manager bound to the current thread, so both writes belong to one transaction.

    The transaction is bound to the thread. The @Transactional Javadoc is explicit that it does not propagate to newly started threads within the method, so work you hand to another thread pool (see Thread Pools, Executors and CompletableFuture) runs outside it.

    sequenceDiagram accTitle: One transactional call, commit and rollback paths accDescr: The caller calls the proxy, which begins a transaction, invokes the service, and then commits if the method returned or if it threw an exception that does not trigger rollback, and rolls back if it threw an unchecked exception. participant C as Caller participant P as Proxy participant S as CheckoutService participant D as Database C->>P: placeOrderCardDeclined(sku, 2) P->>D: begin P->>S: invoke S->>D: update stock S->>D: insert order S-->>P: throws PaymentDeclinedException P->>D: rollback P-->>C: rethrows the exception

    Figure 2. The same exception reaches the caller and rolls the work back. How to read this: the proxy rethrows what your method threw, so the caller still sees the exception. What the exception triggers happens in between, at the proxy.

    Defaults you inherit

    The reference lists the defaults of @Transactional: propagation REQUIRED, isolation ISOLATION_DEFAULT, a read-write transaction, a timeout that falls back to the underlying system's default, and rollback on any RuntimeException or Error but not on a checked Exception. A class-level annotation sets the default for every method of that class; the most derived location wins, so a method-level annotation overrides it. The Spring team recommends annotating methods of concrete classes rather than relying on annotations in interfaces.

    Rollback rules: the checked exception trap

    By default the proxy marks a transaction for rollback only for unchecked exceptions and Error. A checked exception thrown from a transactional method leaves the transaction to commit. This is a deliberate rule, not a bug, and it surprises people exactly when a business rule is modelled as a checked exception.

    flowchart TD accTitle: Does a thrown exception roll back the transaction accDescr: A decision flow. If a rollback rule matches the exception, roll back. Otherwise, if the exception is a RuntimeException or an Error, roll back. Otherwise, commit. A["Method throws an exception"] --> B{"A rollbackFor or noRollbackFor rule matches?"} B -- "rollbackFor matches" --> R["Roll back"] B -- "noRollbackFor matches" --> C["Commit"] B -- "no rule matches" --> D{"RuntimeException or Error?"} D -- "yes" --> R D -- "no, a checked exception" --> C

    Figure 3. The rollback decision. How to read this: custom rules are consulted first and the strongest matching rule wins; only when none matches does the default apply.

    Rules are set with rollbackFor and noRollbackFor (types) or the ...ClassName variants (patterns). A configured type matches a thrown exception when the thrown one is the same type or a subclass. As of Spring Framework 6.2 the default can be changed globally, for example with @EnableTransactionManagement(rollbackOn=ALL_EXCEPTIONS).

    The lab holds two exceptions: PaymentDeclinedException (unchecked) and OutOfStockException (checked). The same two writes then a failure, with and without a rule:

    @Transactional
    public void placeOrderCardDeclined(String sku, int quantity) {
        shop.decrementStock(sku, quantity);
        shop.insertOrder(sku, quantity);
        throw new PaymentDeclinedException("card declined");
    }
    
    @Transactional
    public void placeOrderCheckStockAfter(String sku, int quantity) throws OutOfStockException {
        shop.decrementStock(sku, quantity);
        shop.insertOrder(sku, quantity);
        if (shop.stock(sku) < 0) {
            throw new OutOfStockException("oversold " + sku);
        }
    }
    
    @Transactional(rollbackFor = OutOfStockException.class)
    public void placeOrderCheckStockAfterWithRollbackFor(String sku, int quantity) throws OutOfStockException {
        shop.decrementStock(sku, quantity);
        shop.insertOrder(sku, quantity);
        if (shop.stock(sku) < 0) {
            throw new OutOfStockException("oversold " + sku);
        }
    }

    The results are in the captured output below: rows 2, 3 and 4.

    Self-invocation and visibility

    In proxy mode, "only external method calls coming in through the proxy are intercepted". A method calling another method of the same object bypasses the proxy, so the callee's @Transactional has no effect, "even if the invoked method is marked with @Transactional". The reference points to AspectJ mode for the case where self-invocations must be wrapped.

    sequenceDiagram accTitle: Self-invocation bypasses the transactional proxy accDescr: Through the proxy, reserve runs inside a transaction. When reserveThroughThis calls reserve on the same object, the call does not go back through the proxy, so no transaction exists and the stock write is committed on its own even though an exception is thrown. participant C as Caller participant P as Proxy participant S as CheckoutService C->>P: reserve(sku, 2) P->>S: invoke inside a transaction S-->>P: throws, so rollback C->>P: reserveThroughThis(sku, 2) P->>S: invoke, no transaction (method is not annotated) S->>S: this.reserve(sku, 2) Note over S: the proxy is not involved, no transaction S-->>C: throws, the write is already committed

    Figure 4. Why a call on this is not wrapped. How to read this: the first call enters through the proxy and the failure rolls back. In the second, the outer method has no annotation and the inner call never returns to the proxy.

    @Transactional
    public void reserve(String sku, int quantity) {
        lastCallHadTransaction = TransactionSynchronizationManager.isActualTransactionActive();
        shop.decrementStock(sku, quantity);
        throw new PaymentDeclinedException("card declined");
    }
    
    public void reserveThroughThis(String sku, int quantity) {
        reserve(sku, quantity);
    }

    On visibility: the annotation is typically used on public methods. As of Spring Framework 6.0, protected and package-visible methods can also be transactional for class-based proxies, but a method in an interface-based proxy must be public and declared on the interface. The proxy must also be fully initialized, so do not rely on it in a @PostConstruct method.

    Propagation: what happens when a transaction already exists

    Propagation What the documentation says it does Typical use
    REQUIRED (default) Enforces a physical transaction: a new one if none exists, otherwise it participates in the outer one Almost every service method
    REQUIRES_NEW Always an independent physical transaction; it can commit or roll back separately and releases its locks when it completes An audit row that must survive the caller's rollback
    NESTED One physical transaction with savepoints it can roll back to; typically JDBC savepoints A partial rollback inside one transaction

    Two consequences matter more than the table.

    An inner REQUIRED failure poisons the outer transaction. With REQUIRED, inner and outer scopes map to the same physical transaction, so a rollback-only marker set by the inner scope affects the outer scope's chance to commit. If the caller catches the exception and carries on, the commit fails with UnexpectedRollbackException, so the caller is never misled into thinking a commit happened.

    REQUIRES_NEW costs a second connection. The outer transaction's resources stay bound while the inner one acquires its own connection. The reference warns this can exhaust the connection pool and even deadlock if several threads each hold an outer transaction and wait for an inner connection, and says to size the pool to exceed the number of concurrent threads by at least one.

    REQUIRES_NEW runs on a second connectionplaceOrder to Connection 1 (stock, order); Audit to Connection 2 (audit row); Connection 1 to Database (rolls back); Connection 2 to Database (commits)placeOrder: outer, REQUIREDplaceOrderouter, REQUIREDAudit: REQUIRES_NEWAuditREQUIRES_NEWConnection 1: transaction 1Connection 1transaction 1Connection 2: transaction 2Connection 2transaction 2DatabaseDatabasestock, orderaudit rowrolls backcommits

    Figure 5. Two transactions, two outcomes. How to read this: the outer work and the audit row use different connections. When the outer transaction rolls back, the audit row has already committed.

    readOnly, isolation and timeout are settings, not guarantees

    readOnly = true is documented as a hint: it "will not necessarily cause failure of write access attempts", and a transaction manager that cannot interpret it silently ignores it. For JDBC, Spring applies the standard Connection.setReadOnly hint by default; an opt-in enforceReadOnly flag on DataSourceTransactionManager issues SET TRANSACTION READ ONLY for databases that understand it. isolation and timeout apply only to REQUIRED and REQUIRES_NEW, and the default isolation is the database's, not a Spring choice.

    Build it: ten scenarios on H2

    This is the minimal example you can run. The database is H2, in memory, so nothing here shows PostgreSQL behaviour.

    Goal. Watch each rule change what the database holds afterwards.

    Setup. From the repository's examples/spring-labs folder:

    ./gradlew :labs:spring-transactional:test

    The task runs 11 behaviour tests and a golden-file comparison. The code is in examples/spring-labs/labs/spring-transactional/src/main/java/buildingai/labs/txn/. Every scenario starts from stock of 5 units of milk-1l, no orders and no audit rows, and prints the state after the call.

    Steps. Read the table below against the output, then change one rule at a time.

    Expected output, captured from a real run (Java 25, Spring Boot 4.1.2, 2026-12-01):

    Spring @Transactional on H2 (in-memory). Start state every time: stock(milk-1l)=5, orders=0, audit=[].
    
    1   commit                                     placeOrder(2)                                  -> returned normally              stock=3 orders=1 audit=[]
    2   unchecked exception                        placeOrderCardDeclined(2)                      -> PaymentDeclinedException       stock=5 orders=0 audit=[]
    3   checked exception, default rules           placeOrderCheckStockAfter(8)                   -> OutOfStockException            stock=-3 orders=1 audit=[]
    4   checked exception, rollbackFor             placeOrderCheckStockAfterWithRollbackFor(8)    -> OutOfStockException            stock=5 orders=0 audit=[]
    5a  call through the proxy                     reserve(2)                                     -> PaymentDeclinedException       stock=5 orders=0 audit=[] transactionActive=true
    5b  self-invocation                            reserveThroughThis(2)                          -> PaymentDeclinedException       stock=3 orders=0 audit=[] transactionActive=false
    6   REQUIRES_NEW audit, outer rolls back       placeOrderWithAuditThenDecline(2)              -> PaymentDeclinedException       stock=5 orders=0 audit=[order attempted]
    7a  inner REQUIRED fails, caller catches       placeOrderSwallowingInnerFailure(2)            -> UnexpectedRollbackException    stock=5 orders=0 audit=[]
    7b  inner REQUIRES_NEW fails, caller catches   placeOrderSwallowingIsolatedFailure(2)         -> returned normally              stock=3 orders=1 audit=[]
    8   write inside readOnly = true               writeInsideReadOnly(2)                         -> returned normally              stock=3 orders=0 audit=[]
    Row What it shows
    1, 2 Success commits both writes; an unchecked exception after both writes rolls both back.
    3 A checked exception commits: the order exists and stock is at -3 even though the caller saw a failure.
    4 rollbackFor turns the same failure into a rollback.
    5a, 5b Through the proxy a transaction is active and the stock write is undone; through this none is active and the write stays (stock 3).
    6 The REQUIRES_NEW audit row survives the outer rollback.
    7a Catching an inner REQUIRED failure does not save the transaction: everything is rolled back and the commit throws UnexpectedRollbackException.
    7b With REQUIRES_NEW only the inner work (the points row) is lost; the order commits.
    8 On this H2 the write inside a readOnly = true transaction went through (stock 3).

    Break it. Delete rollbackFor = OutOfStockException.class from placeOrderCheckStockAfterWithRollbackFor and the matching test fails: the order commits with stock at -3. Restore it and re-run.

    Stretch. Add a NESTED method and a TransactionTemplate variant.

    What the lab leaves out. Isolation levels, timeouts, NESTED savepoints, JPA, concurrent transactions and every PostgreSQL behaviour. Row 8 is H2 and its driver, not a statement about other databases.

    Choosing where the boundary goes

    Put the boundary on the service method that implements one business operation, not on a controller and not on each repository call. Slow calls that need no database atomicity (an HTTP call to a payment provider, sending mail) go outside, because the transaction holds a connection while it waits.

    Option Gain Cost Wrong when
    @Transactional on the service method One clear boundary; declarative Proxy rules apply (self-invocation, visibility, rollback rules) Work must be atomic across several databases or a broker
    TransactionTemplate in code The boundary is visible and a callback can call setRollbackOnly() Couples code to Spring's transaction API A simple method suits the annotation
    rollbackFor on specific exceptions Rolls back for chosen checked exceptions Easy to forget when a new exception appears Business rules should not leave partial writes either way
    REQUIRES_NEW for side effects Survives the caller's rollback A second connection, pool pressure The side effect must be undone with the caller
    AspectJ mode Self-invocation is wrapped Needs weaving at build or load time The proxy mode and a separate bean suffice

    When the work spans a database and a message broker or another service, one local transaction is not enough; see Distributed Transactions.

    In practice: ShopStream's checkout

    This is the realistic example, an educational scenario on the course's running example ShopStream; nothing in it describes a real company.

    This is a realistic scenario, not a case history.

    The situation

    Checkout reserves stock, writes the order and records an audit entry. The team has just introduced a checked OutOfStockException for the "stock went negative" rule and wants one transaction around the whole operation.

    Starting architecture

    ShopStream checkout with one transactional service methodShopper to Checkout API (checkout); Checkout API to Checkout; Checkout to Orders DB (stock, order); Checkout to AuditService (audit); AuditService to Orders DB (audit row)ShopperShopperCheckout APICheckout APICheckout: transactionalCheckouttransactionalAuditService: REQUIRES_NEWAuditServiceREQUIRES_NEWOrders DB: three tablesOrders DBthree tablescheckoutstock, orderauditaudit row

    Figure 6. The checkout path in the lab's shape. How to read this: the checkout service owns the transaction around stock and order; the audit service uses its own transaction so a rolled-back checkout still leaves a trace.

    Options considered

    Option Behaviour on a declined card Behaviour on an oversell
    A. Plain @Transactional Rolls back (row 2) Commits with negative stock if the exception is checked (row 3)
    B. @Transactional(rollbackFor = ...) Rolls back Rolls back (row 4)
    C. Make OutOfStockException unchecked Rolls back Rolls back, but every caller loses the compile-time reminder

    The decision

    Option B for the checked business exception, with the audit write in its own REQUIRES_NEW transaction (row 6), and the pool sized for the extra connection. The team also writes down that the audit service is a separate bean, so the call crosses the proxy.

    Rollout and verification

    Reproduce the lab's scenarios as tests against the real service, one per exception type, plus a test per propagation rule; the lab's tests are the template. In operation, check for the symptom the rule prevents: stock rows below zero and orders without a matching successful payment.

    The 2 a.m. failure

    The page reads: stock counts are negative for several products after a flash sale. The oversell check threw the checked exception and, under the default rules, the transaction committed (row 3). Checks: search the code for checked exceptions declared on transactional methods, count orders whose stock went negative, and compare their timestamps with the release that added the exception. The mitigation is to repair the affected stock and orders by hand and add the rollback rule; the lasting fix is a test per exception type and, if the team wants it, the global setting that rolls back on all exceptions.

    Architect's notes

    • Treat exceptions as part of the transaction contract. Every exception a transactional method can throw needs a decision: roll back or commit.
    • Keep slow calls outside. The transaction holds a connection for as long as it runs.
    • Do not swallow exceptions inside a joined transaction. The commit will fail with UnexpectedRollbackException.
    • Call across beans. A call that must be transactional goes through another Spring bean, not through this.
    • Size the pool for REQUIRES_NEW. Each active outer transaction can need a second connection.

    Common mistakes

    • Assuming checked exceptions roll back. They commit by default (row 3).
    • Annotating a method and calling it from the same class. No proxy, no transaction (row 5b).
    • Catching an exception from a joined inner call and carrying on. The outer commit fails (row 7a).
    • Reading readOnly as a safety lock. It is a hint; H2 let the write through (row 8).
    • Expecting a transaction in another thread. It is thread-bound.

    Key takeaways

    • @Transactional is applied by a proxy around calls that arrive from outside the bean.
    • By default a transaction rolls back for RuntimeException and Error and commits for checked exceptions; rollbackFor changes that.
    • A method called on this is not wrapped.
    • REQUIRED joins the outer transaction and shares its fate; REQUIRES_NEW is independent and uses another connection; NESTED uses savepoints.
    • readOnly, isolation and timeout are settings whose effect depends on the transaction manager and the database.
    • A lab that prints the database state afterwards is the quickest way to learn which rule applies.

    Practice exercises

    Exercise 1 (20 min). For the ten rows of the output, say which rule explains each stock and orders value.

    Exercise 2 (45 min). Add a method annotated with both rollbackFor = Exception.class and noRollbackFor = OutOfStockException.class that throws OutOfStockException after the two writes; predict the outcome from "the strongest matching rule wins", then run it.

    Exercise 3 (1 hour). Run "Break it". Then move reserve into a second bean and call it from reserveThroughThis through that bean; say what row 5b becomes.

    Exercise 4 (2 hours). Decide, for ShopStream's cart, checkout, audit log and email, which are inside the checkout transaction, which are REQUIRES_NEW and which are outside, and what each choice costs under a connection pool of 10.

    Official documentation

    Ask about this article

    Get answers grounded in this post. AI-generated — based on this article, and may be imperfect.

    Scaled AI Weekly

    Enjoyed this? Get more like it every Monday.

    Real architecture decisions, LLMOps patterns that survive production, and engineering leadership advice — from 12+ years of building at enterprise scale. Free. No spam. Unsubscribe anytime.

    Get new articles by email

    Free. We email a confirmation link first, and you can unsubscribe from any email.

    Join engineers building production AI systems

    Comments