Skip to lesson

Propagation basics: REQUIRED and REQUIRES_NEW

An order fails and rolls back, and the audit record of the attempt goes with it, so nobody can see that it happened. One setting decides which work survives a failure.

REQUIRED: join the caller, fail together

Propagation says what a @Transactional method does when a transaction is already running: join it or start its own.

REQUIRED is the default, so the audit method joins the order's transaction. The example fails an order on purpose and counts the audit rows afterwards.

Example 1 · AuditService.java: REQUIRED joins and is rolled back with the order

Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)

AuditService.javaJava
// src/main/java/com/shoplite/lab/audit/AuditService.javapackage com.shoplite.lab.audit;
import java.time.LocalDateTime;import java.time.temporal.ChronoUnit;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Propagation;import org.springframework.transaction.annotation.Transactional;
@Servicepublic class AuditService {
    private final AuditRepository audit;
    public AuditService(AuditRepository audit) {        this.audit = audit;    }
    /** REQUIRED (the default): joins the caller's transaction and lives or dies with it. */    @Transactional    public void recordJoined(String action, String detail) {        audit.save(new AuditEntry(action, detail, now()));    }
    /** REQUIRES_NEW: pauses the caller's transaction and commits on its own. */    @Transactional(propagation = Propagation.REQUIRES_NEW)    public void recordInNewTransaction(String action, String detail) {        audit.save(new AuditEntry(action, detail, now()));    }
    /** MANDATORY: refuses to run unless a transaction is already active. */    @Transactional(propagation = Propagation.MANDATORY)    public void recordMandatory(String action, String detail) {        audit.save(new AuditEntry(action, detail, now()));    }
    /** NESTED: a savepoint inside the caller's transaction (needs savepoint support). */    @Transactional(propagation = Propagation.NESTED)    public void recordNested(String action, String detail) {        audit.save(new AuditEntry(action, detail, now()));    }
    private static LocalDateTime now() {        return LocalDateTime.now().truncatedTo(ChronoUnit.SECONDS);    }}
// src/main/java/com/shoplite/lab/propagation/AuditedOrderService.javapackage com.shoplite.lab.propagation;
import java.util.List;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.lab.audit.AuditService;import com.shoplite.lab.placement.OrderLine;import com.shoplite.lab.placement.OrderPlacementService;import com.shoplite.order.Order;
/** Every order attempt must leave an audit row, even a failed one. */@Servicepublic class AuditedOrderService {
    private final AuditService audit;    private final OrderPlacementService placement;
    public AuditedOrderService(AuditService audit, OrderPlacementService placement) {        this.audit = audit;        this.placement = placement;    }
    @Transactional    public Order placeWithJoinedAudit(int customerId, int addressId, List<OrderLine> lines) {        audit.recordJoined("ORDER_ATTEMPT", "customer " + customerId + ", " + lines.size() + " lines");        return placement.place(customerId, addressId, lines);    }
    @Transactional    public Order placeWithSeparateAudit(int customerId, int addressId, List<OrderLine> lines) {        audit.recordInNewTransaction("ORDER_ATTEMPT", "customer " + customerId + ", " + lines.size() + " lines");        return placement.place(customerId, addressId, lines);    }}
// src/main/java/com/shoplite/lab/propagation/PropagationDemo.javapackage com.shoplite.lab.propagation;
import java.util.List;
import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;import com.shoplite.lab.placement.OrderLine;import com.shoplite.lab.placement.OutOfStockException;
@Component("propagation")public class PropagationDemo implements LabDemo {
    private final AuditedOrderService orders;    private final LabDb db;    private final String audit;
    public PropagationDemo(AuditedOrderService orders, LabDb db, @Value("${audit:joined}") String audit) {        this.orders = orders;        this.db = db;        this.audit = audit;    }
    @Override    public void run() {        List<OrderLine> lines = List.of(new OrderLine(3, 9));        try {            if (audit.equals("new")) {                orders.placeWithSeparateAudit(2, 3, lines);            } else {                orders.placeWithJoinedAudit(2, 3, lines);            }        } catch (OutOfStockException e) {            System.out.println("Order failed: " + e.getMessage());        }        System.out.println("Audit rows: " + db.auditRows() + ", orders: " + db.orders());    }}
Sample output
$ java -jar target/tx-lab-0.1.0.jar --demo=propagation --audit=joined
DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [com.shoplite.lab.propagation.AuditedOrderService.placeWithJoinedAudit]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
DEBUG o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(89118198<open>)] for JPA transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@36cc6055]
DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(89118198<open>)] for JPA transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(89118198<open>)] for JPA transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(89118198<open>)] for JPA transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(89118198<open>)] for JPA transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(89118198<open>)] for JPA transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Participating transaction failed - marking existing transaction as rollback-only
DEBUG o.s.orm.jpa.JpaTransactionManager : Setting JPA transaction on EntityManager [SessionImpl(89118198<open>)] rollback-only
DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction rollback
DEBUG o.s.orm.jpa.JpaTransactionManager : Rolling back JPA transaction on EntityManager [SessionImpl(89118198<open>)]
DEBUG o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager after transaction
Order failed: Only 8 units of iPhone 15 128GB are in stock; 9 were requested.
Audit rows: 0, orders: 16

What this code does

  • recordJoined (REQUIRED) logged Participating in existing transaction, and its INSERT into audit_log ran inside the order transaction.
  • When the iPhone check failed, the rollback removed the audit row too: Audit rows: 0. Nobody can see that Ravi tried to order.
  • AuditEntry is a small entity for the lab's audit_log table (id, action, detail, createdAt).

With no transaction running, a REQUIRED method starts one. With one running, it joins it: the log says Participating in existing transaction, and both methods share one connection, one EntityManager and one commit. An inner failure therefore rolls back everything, including work the outer method did before the call. That is usually right, because an order and its stock change belong together, but it is wrong for a record of the attempt that must stay.

The examples add an audit_log table to the tx-lab database (lab only, not part of ShopLite's schema) and an AuditService with one method per propagation.

REQUIRES_NEW: an audit record that survives a rollback

REQUIRES_NEW always starts a new, independent transaction. A running caller transaction is suspended until the new one has committed or rolled back.

REQUIRES_NEW is the fix for the missing audit row. The next lines call it from the failing order and count the rows again.

Two connections at once. The order transaction runs on connection 1: it starts and takes stock, is suspended while the audit method runs, then resumes and fails. The audit method runs REQUIRES_NEW on connection 2 and commits on its own. The order rolls back, but the audit row stays.

Example 2 · REQUIRES_NEW: suspend, commit the audit row, resume

Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)

Java
// AuditedOrderService.placeWithSeparateAudit from Example 1 calls:@Transactional(propagation = Propagation.REQUIRES_NEW)public void recordInNewTransaction(String action, String detail) {    audit.save(new AuditEntry(action, detail, now()));}
Sample output
$ java -jar target/tx-lab-0.1.0.jar --demo=propagation --audit=new
DEBUG o.s.orm.jpa.JpaTransactionManager : Creating new transaction with name [com.shoplite.lab.propagation.AuditedOrderService.placeWithSeparateAudit]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT
DEBUG o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(705480294<open>)] for JPA transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@5c4f07c1]
DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(705480294<open>)] for JPA transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Suspending current transaction, creating new transaction with name [com.shoplite.lab.audit.AuditService.recordInNewTransaction]
DEBUG o.s.orm.jpa.JpaTransactionManager : Opened new EntityManager [SessionImpl(194606901<open>)] for JPA transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Exposing JPA transaction as JDBC [org.springframework.orm.jpa.vendor.HibernateJpaDialect$HibernateConnectionHandle@178826db]
DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(194606901<open>)] for JPA transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction commit
DEBUG o.s.orm.jpa.JpaTransactionManager : Committing JPA transaction on EntityManager [SessionImpl(194606901<open>)]
DEBUG o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager after transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Resuming suspended transaction after completion of inner transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(705480294<open>)] for JPA transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(705480294<open>)] for JPA transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Found thread-bound EntityManager [SessionImpl(705480294<open>)] for JPA transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Participating in existing transaction
DEBUG o.s.orm.jpa.JpaTransactionManager : Participating transaction failed - marking existing transaction as rollback-only
DEBUG o.s.orm.jpa.JpaTransactionManager : Setting JPA transaction on EntityManager [SessionImpl(705480294<open>)] rollback-only
DEBUG o.s.orm.jpa.JpaTransactionManager : Initiating transaction rollback
DEBUG o.s.orm.jpa.JpaTransactionManager : Rolling back JPA transaction on EntityManager [SessionImpl(705480294<open>)]
DEBUG o.s.orm.jpa.JpaTransactionManager : Closing JPA EntityManager after transaction
Order failed: Only 8 units of iPhone 15 128GB are in stock; 9 were requested.
Audit rows: 1, orders: 16

What this code does

  • Suspending current transaction, creating new transaction and a second Opened new EntityManager: a separate transaction on its own connection, committed at once.
  • Resuming suspended transaction brings the order transaction back. It still fails and rolls back, but the committed audit row stays: Audit rows: 1, orders still 16.

If the caller has a transaction, Spring suspends it (puts it aside), runs the inner method in its own transaction with its own connection, commits or rolls back that one, and then resumes the caller's. The inner commit is final, which is what an audit record, a failed-login counter or an attempt log needs.

The other direction works too: if the inner transaction fails and the caller catches the exception, only the inner work is lost.

Predict the output

Audit rows after a failed order

The order always fails with OutOfStockException.

Round 1 of 3

How many audit rows exist afterwards?

@Transactional
public void place() {
audit.recordJoined("ORDER", "Ravi");
throw new OutOfStockException("iPhone");
}
REQUIRES_NEW must be called through another bean (here AuditService); a call to a method of the same class skips the proxy, as the next lesson shows.

REQUIRES_NEW holds two connections: pool exhaustion

Pool exhaustion is when every pooled database connection is busy, so new requests wait for one and then time out.

While the inner transaction runs, the suspended outer one still holds its connection, so one request needs two. The demo forces the problem with a pool of two connections and two requests.

Example 3 · BusyCheckoutService.java: two requests, a pool of two, and REQUIRES_NEW

Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)

BusyCheckoutService.javaJava
// src/main/java/com/shoplite/lab/propagation/BusyCheckoutService.javapackage com.shoplite.lab.propagation;
import java.util.concurrent.CountDownLatch;import java.util.concurrent.TimeUnit;
import org.springframework.stereotype.Service;import org.springframework.transaction.annotation.Transactional;
import com.shoplite.lab.audit.AuditService;import com.shoplite.product.Product;import com.shoplite.product.ProductRepository;
@Servicepublic class BusyCheckoutService {
    private final ProductRepository products;    private final AuditService audit;
    public BusyCheckoutService(ProductRepository products, AuditService audit) {        this.products = products;        this.audit = audit;    }
    @Transactional    public void checkout(int productId, CountDownLatch allInside) throws InterruptedException {        Product product = products.findById(productId).orElseThrow();        product.setStock(product.getStock() - 1);        allInside.countDown();        allInside.await(5, TimeUnit.SECONDS);        audit.recordInNewTransaction("CHECKOUT", "product " + productId);    }}
// src/main/java/com/shoplite/lab/propagation/PoolExhaustionDemo.javapackage com.shoplite.lab.propagation;
import java.util.ArrayList;import java.util.List;import java.util.concurrent.CountDownLatch;
import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;
@Component("pool-exhaustion")public class PoolExhaustionDemo implements LabDemo {
    private final BusyCheckoutService checkout;    private final LabDb db;    private final int requests;
    public PoolExhaustionDemo(BusyCheckoutService checkout, LabDb db, @Value("${requests:2}") int requests) {        this.checkout = checkout;        this.db = db;        this.requests = requests;    }
    @Override    public void run() {        CountDownLatch allInside = new CountDownLatch(requests);        List<Thread> threads = new ArrayList<>();        for (int i = 1; i <= requests; i++) {            int productId = i == 1 ? 9 : 11;            Thread t = new Thread(() -> {                try {                    checkout.checkout(productId, allInside);                    System.out.println(Thread.currentThread().getName() + ": done");                } catch (Exception e) {                    System.out.println(Thread.currentThread().getName() + ": " + e.getClass().getSimpleName()                            + ": " + e.getMessage());                }            }, "request-" + i);            threads.add(t);            t.start();        }        for (Thread t : threads) {            try {                t.join();            } catch (InterruptedException e) {                Thread.currentThread().interrupt();            }        }        System.out.println("Audit rows: " + db.auditRows());    }}
Sample output (timings differ)
$ java -jar target/tx-lab-0.1.0.jar --demo=pool-exhaustion --spring.datasource.hikari.maximum-pool-size=2 --spring.datasource.hikari.connection-timeout=3000
WARN  org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 0, SQLState: null
WARN  org.hibernate.orm.jdbc.error : HHH000247: ErrorCode: 0, SQLState: null
WARN  org.hibernate.orm.jdbc.error : HikariPool-1 - Connection is not available, request timed out after 3046ms (total=2, active=2, idle=0, waiting=0)
WARN  org.hibernate.orm.jdbc.error : HikariPool-1 - Connection is not available, request timed out after 3011ms (total=2, active=2, idle=0, waiting=1)
request-2: CannotCreateTransactionException: Could not open JPA EntityManager for transaction
request-1: CannotCreateTransactionException: Could not open JPA EntityManager for transaction
Audit rows: 0

What this code does

  • Each request holds connection 1 in checkout and asks for connection 2 for the audit. Both connections of the pool are busy (total=2, active=2, idle=0), so both requests wait 3 seconds and fail with CannotCreateTransactionException.
  • Both outer transactions then roll back as well: no audit rows, no stock change. With maximum-pool-size=3 the same run finished both requests.
  • The latch only makes the unlucky timing certain; with 10 connections and enough traffic the same thing happens on its own.

Under load this can deadlock the pool: every connection is held by an outer transaction, and every request is waiting for a second one. HikariCP waits connection-timeout (30 seconds by default in Spring Boot, 5 in ShopLite) and then throws SQLTransientConnectionException: ... Connection is not available, request timed out.

Keep REQUIRES_NEW for short, rare side work, and never call it in a loop.

The other options in one line each

REQUIRED and REQUIRES_NEW cover nearly every service. Spring has seven propagation values; the other five enforce special rules, and the example tries two of them.

Example 4 · MANDATORY and NESTED in tx-lab

Runs in: the tx-lab practice project (Spring Boot 4.1, ShopLite database)

OtherPropagationsDemo.javaJava
// src/main/java/com/shoplite/lab/propagation/OtherPropagationsDemo.javapackage com.shoplite.lab.propagation;
import org.springframework.stereotype.Component;import org.springframework.transaction.support.TransactionTemplate;
import com.shoplite.lab.LabDb;import com.shoplite.lab.LabDemo;import com.shoplite.lab.audit.AuditService;
@Component("other-propagations")public class OtherPropagationsDemo implements LabDemo {
    private final AuditService audit;    private final TransactionTemplate tx;    private final LabDb db;
    public OtherPropagationsDemo(AuditService audit, TransactionTemplate tx, LabDb db) {        this.audit = audit;        this.tx = tx;        this.db = db;    }
    @Override    public void run() {        try {            audit.recordMandatory("PRICE_CHANGE", "no caller transaction");        } catch (RuntimeException e) {            System.out.println("MANDATORY without a transaction -> " + e.getClass().getSimpleName() + ": " + e.getMessage());        }        try {            tx.executeWithoutResult(status -> audit.recordNested("PRICE_CHANGE", "inside a transaction"));        } catch (RuntimeException e) {            System.out.println("NESTED with JPA -> " + e.getClass().getSimpleName() + ": " + e.getMessage());        }        System.out.println("Audit rows: " + db.auditRows());    }}
Sample output
$ java -jar target/tx-lab-0.1.0.jar --demo=other-propagations
MANDATORY without a transaction -> IllegalTransactionStateException: No existing transaction found for transaction marked with propagation 'mandatory'
NESTED with JPA -> NestedTransactionNotSupportedException: Transaction manager does not allow nested transactions by default - specify 'nestedTransactionAllowed' property with value 'true'
Audit rows: 0

What this code does

  • recordMandatory called with no transaction refused to run at all, with the exact rule in the message.
  • recordNested inside a TransactionTemplate transaction was refused by JpaTransactionManager, which does not allow nested transactions unless you switch them on; the template's transaction then rolled back, so no row was saved.

The other five, in one line each:

  • MANDATORY: must run inside an existing transaction, otherwise IllegalTransactionStateException.
  • SUPPORTS: joins one if there is one, else runs without.
  • NOT_SUPPORTED: suspends any running transaction and runs without one, for example a slow report.
  • NEVER: throws if a transaction is running.
  • NESTED: a savepoint inside the caller's transaction that can roll back alone. JpaTransactionManager refuses it by default (nestedTransactionAllowed is false), so in JPA code use REQUIRES_NEW or split the work.

Next step

Check your understanding

12 quick questions