Propagation and rollback
- Key idea
- Propagation decides what a `@Transactional` method does when it's called: join the current transaction (`REQUIRED`), open a new independent one (`REQUIRES_NEW`), create a savepoint (`NESTED`) or require that there is, or isn't, a transaction. `rollbackFor` and `noRollbackFor` change which exceptions roll back.
- In the box
- If a booking fails, the audit record should stay; if the loyalty points fail, the booking shouldn't be lost. Decide what happens when a transactional method calls another one with propagation, and fine-tune rollback with rollbackFor and noRollbackFor.
The athlete sends book(full) to BookingService, which calls logRequired() on AuditService, highlighted; transaction #1's ROLLBACK reaches the database and takes both writes with it.
BookingService sends BEGIN to transaction #1, highlighted, and AuditService joins it: both writes go in the same transaction.
BookingService calls logRequiresNew(); AuditService opens and commits transaction #2, highlighted; transaction #1 rolls back on its own.
BookingService calls addPoints(), which fails; LoyaltyService, highlighted, marks transaction #1 as rollback-only.
LoyaltyService, highlighted, sends SAVEPOINT to transaction #1: its failure only rolls back to that point.
StrictServices, highlighted, receives from BookingService one call that satisfies MANDATORY and another that breaks NEVER.
InvoiceService, highlighted in BookingService's place, sends rollbackFor to transaction #1: its checked exception does roll back.
BookingService, highlighted, has only transaction #1: the internal call didn't create the second one.
Final view: BookingService, AuditService and LoyaltyService with the two physical transactions and the database.
Step 1 of 9
The audit goes down with the booking
Every booking attempt must be audited, even when it fails. bookWithSharedAudit() is @Transactional and calls audit.logRequired(...) before checking capacity.
If the class is full, ClassFullException is thrown, the proxy rolls back… and the audit record disappears too. The test checks it: zero bookings, zero audits.
Step 2 of 9
REQUIRED: all in the same boat
A bare @Transactional uses propagation = REQUIRED:
- If there's already a transaction in progress, the method joins it.
- If there isn't, it creates a new one.
That's why logRequired() writes inside the booking's transaction #1: there's a single physical transaction, and the commit or rollback affects everything done in it.
Step 3 of 9
REQUIRES_NEW: a transaction of its own
With @Transactional(propagation = Propagation.REQUIRES_NEW) on logRequiresNew():
- Spring suspends the booking's transaction #1.
- It opens transaction #2 (with another connection), inserts the audit and commits on return.
- It resumes #1. If the booking fails afterwards, only #1 is rolled back.
The test: zero bookings, one audit.
Step 4 of 9
Trap: catching isn't enough
bookIgnoringLoyalty() inserts the booking and calls loyalty.addPoints(), which is REQUIRED and throws LoyaltyDownException. The booking catches the exception and carries on, thinking "we'll give the points later".
But when the exception leaves addPoints()'s proxy, the proxy marks the shared transaction as rollback-only. When bookIgnoringLoyalty() finishes and its proxy tries to commit, Spring throws UnexpectedRollbackException and rolls everything back.
Step 5 of 9
NESTED: a savepoint
NESTED creates a savepoint inside the current transaction:
- If the inner method fails, it goes back to the savepoint: only the points are undone.
- The outer transaction stays alive and can commit: the booking is saved.
- If the outer one fails later, everything is undone, including the inner work (unlike
REQUIRES_NEW).
Step 6 of 9
The other four propagations
| Propagation | Transaction exists | No transaction |
|---|---|---|
REQUIRED |
joins | creates one |
REQUIRES_NEW |
suspends it and creates another | creates one |
NESTED |
savepoint inside | creates one |
SUPPORTS |
joins | no transaction |
NOT_SUPPORTED |
suspends it | no transaction |
MANDATORY |
joins | IllegalTransactionStateException |
NEVER |
IllegalTransactionStateException |
no transaction |
The test calls issueReceipt() (MANDATORY) from outside and it fails, and from bookAndIssueReceipt(), inside a transaction, and it works. exportReport() (NEVER) fails the other way round.
Step 7 of 9
rollbackFor and noRollbackFor
The default rules (rollback on RuntimeException/Error, commit on checked ones) are tuned with:
rollbackFor = InvoiceException.class: a checked exception that does roll back.noRollbackFor = SoftWarningException.class: aRuntimeExceptionthat does not roll back (here, a warning that the waiver isn't signed yet; the booking is saved anyway).
There are also rollbackForClassName and noRollbackForClassName, with the name as text. A common choice is rollbackFor = Exception.class so any exception rolls back.
Step 8 of 9
Trap: propagation needs the proxy too
bookWithSelfAudit() calls this.selfAudit(), which has REQUIRES_NEW. It looks like the audit will get its own transaction…
No: the call through this doesn't go through the proxy, so the attribute is ignored. selfAudit() writes inside the booking's transaction and disappears with its rollback. The test proves it: zero audits.
Step 9 of 9
Recap
REQUIRED(default): join or create; one shared physical transaction.REQUIRES_NEW: suspend and create another; commits on its own.NESTED: savepoint; JDBC only.SUPPORTS,NOT_SUPPORTED,MANDATORY,NEVER: depending on whether a transaction exists.rollbackFor/noRollbackForchange the default rules.- Traps: catching an inner
REQUIREDfailure →UnexpectedRollbackException;thisignores propagation.
Code
BookingService.java
@Transactional
public void bookWithSharedAudit(String athlete, boolean full) {
jdbc.update("INSERT INTO booking (athlete) VALUES (?)", athlete);
audit.logRequired("booking attempt by " + athlete); // joins THIS transaction…
if (full) throw new ClassFullException(); // …so the rollback erases the audit too
}AuditService.java
@Transactional // propagation = REQUIRED (the default): join the caller's transaction if there is one
public void logRequired(String message) {
jdbc.update("INSERT INTO audit (message) VALUES (?)", message);
}AuditService.java
@Transactional(propagation = Propagation.REQUIRES_NEW) // suspend the caller's, run in a NEW one
public void logRequiresNew(String message) {
jdbc.update("INSERT INTO audit (message) VALUES (?)", message);
} // commits here, whatever the caller does laterBookingService.java
@Transactional
public void bookIgnoringLoyalty(String athlete) {
jdbc.update("INSERT INTO booking (athlete) VALUES (?)", athlete);
try {
loyalty.addPoints(athlete); // REQUIRED: same transaction, now marked rollback-only
} catch (LoyaltyDownException e) {
// "we'll give the points later"… but the shared transaction can no longer commit
}
} // commit → UnexpectedRollbackExceptionLoyaltyService.java
@Transactional(propagation = Propagation.NESTED) // a savepoint inside the caller's transaction
public void addPointsNested(String athlete) {
jdbc.update("MERGE INTO points KEY (athlete) VALUES (?, 10)", athlete);
throw new LoyaltyDownException(); // rolls back to the savepoint only
}StrictServices.java
@Transactional(propagation = Propagation.MANDATORY) // must be called inside a transaction
public String issueReceipt(String athlete) {
return "receipt for " + athlete;
}
@Transactional(propagation = Propagation.NEVER) // must NOT be called inside one
public String exportReport() {
return "report";
}
@Transactional(propagation = Propagation.SUPPORTS) // joins if there is one, else runs without
public boolean supports() {
return TransactionSynchronizationManager.isActualTransactionActive();
}
@Transactional(propagation = Propagation.NOT_SUPPORTED) // suspends any transaction
public boolean notSupported() {
return TransactionSynchronizationManager.isActualTransactionActive();
}InvoiceService.java
@Transactional(rollbackFor = InvoiceException.class) // a checked exception that DOES roll back
public void bookAndInvoice(String athlete) throws InvoiceException {
jdbc.update("INSERT INTO booking (athlete) VALUES (?)", athlete);
throw new InvoiceException();
}
@Transactional(noRollbackFor = SoftWarningException.class) // a runtime exception that does NOT
public void bookWithWarning(String athlete) {
jdbc.update("INSERT INTO booking (athlete) VALUES (?)", athlete);
throw new SoftWarningException();
}PropagationTest.java
@Test
void propagationNeedsTheProxyToo() {
assertThatThrownBy(() -> bookings.bookWithSelfAudit("Ana")).isInstanceOf(ClassFullException.class);
assertThat(count("audit")).isZero(); // this.selfAudit() ran in the OUTER transaction
}AuditService.java
@Transactional(propagation = Propagation.REQUIRES_NEW) // suspend the caller's, run in a NEW one
public void logRequiresNew(String message) {
jdbc.update("INSERT INTO audit (message) VALUES (?)", message);
} // commits here, whatever the caller does later