How @Transactional Works in Spring

How Spring invokes @Transactional through proxies, how propagation and rollback rules work, and how to handle external API calls with short transactions, an outbox, and idempotency.

Alexandru DancauNovember 10, 2026 · 16 min read
A glass enclosure groups a database and records inside a local transaction, while a separate external API sits outside its boundary.

An order is saved, a payment provider charges the customer, and the next database operation fails. Spring rolls back the transaction. Has the customer been refunded?

The database changes can roll back. The charge remains with the payment provider.

Understanding that boundary is central to using @Transactional. We also need to understand how a call reaches the annotation, what happens when one transactional method calls another, and which failures cause a rollback.

The examples use Java 21, Spring Boot 3.5, and Spring Data JPA with one relational database. They use Spring's annotation:

import org.springframework.transaction.annotation.Transactional;

Java itself does not interpret this annotation. Spring provides its runtime behavior. Jakarta also defines jakarta.transaction.Transactional, with different configuration attributes; the propagation, rollbackFor, and readOnly examples below belong to Spring's API.

How a method call becomes transactional

In the usual Spring configuration, another bean receives a proxy around the service. A proxy is an object that intercepts a call before forwarding it to the real implementation.

Controller
    -> Spring proxy
        -> TransactionInterceptor
            -> OrderService.placeOrder()
                -> Repository

When the call reaches TransactionInterceptor, Spring reads the transaction settings and asks a transaction manager to apply them. For JPA, that manager is typically JpaTransactionManager.

The interceptor runs the method within the resulting transaction context, then handles completion. It commits a transaction it started if the work succeeds, or applies rollback rules if the method throws. If the call joined an existing transaction, physical completion belongs to the outer boundary.

For a call that starts a new transaction, the sequence looks like this:

Caller invokes the proxy
    Begin transaction
    Invoke service method
    Service method returns
    Flush pending changes and commit
Caller receives the result

A successful return from the method body does not guarantee a successful commit. A constraint violation or another database error can still occur during completion. A try/catch inside that method cannot catch an error raised after its body returns; a caller around the proxy invocation can catch it.

Annotation processing must be enabled. Spring Boot normally configures it when the appropriate transaction infrastructure is present; in a manually configured Spring application, @EnableTransactionManagement enables it. The object must be managed by Spring and the call must pass through its transaction advice. Creating the service with new does not activate that advice.

Put the boundary around the business operation

Suppose creating an order requires two database writes: one order row and one payment request row. The payment request here is a local database record; it does not charge a customer.

@Service
public class OrderService {
    private final OrderRepository orders;
    private final PaymentRequestRepository paymentRequests;

    public OrderService(OrderRepository orders,
                        PaymentRequestRepository paymentRequests) {
        this.orders = orders;
        this.paymentRequests = paymentRequests;
    }

    @Transactional
    public UUID placeOrder(PlaceOrder command) {
        Order order = orders.save(Order.pending(command));
        paymentRequests.save(PaymentRequest.forOrder(order));
        return order.getId();
    }
}

The domain factories and repositories are application types. Later snippets show relevant methods only and assume constructor injection for their dependencies.

Both saves participate in the service transaction. If the second operation fails with an exception that requires rollback, the order insertion rolls back too.

Spring Data already gives inherited CRUD methods transaction settings. A service boundary lets several repository operations form one business unit. Without it, separate repository calls can finish in separate transactions, leaving the first write committed when the second fails.

Why calling a method in the same class changes the result

Consider this version of the service:

public void checkout(PlaceOrder command) {
    persistOrder(command);
}

@Transactional
public UUID persistOrder(PlaceOrder command) {
    Order order = orders.save(Order.pending(command));
    paymentRequests.save(PaymentRequest.forOrder(order));
    return order.getId();
}

An external caller invokes checkout(). Inside the target object, persistOrder() is a call through this. It bypasses the proxy, so its annotation does not establish a transaction around the two saves. Each repository may still apply its own transaction behavior.

This is self-invocation. It also matters when the outer method is transactional: the inner method runs within that existing transaction, but its own annotation is not intercepted. Adding REQUIRES_NEW to it does not create an independent transaction through this call path.

If checkout should be one database transaction, put @Transactional on the externally invoked checkout() method. If persistence needs a separate boundary, move it to another Spring bean and call that injected bean:

// Method on CheckoutService, which has no transaction of its own.
public UUID checkout(PlaceOrder command) {
    return orderWriter.persistOrder(command);
}

// Method on a separate OrderWriter bean.
@Transactional
public UUID persistOrder(PlaceOrder command) {
    Order order = orders.save(Order.pending(command));
    paymentRequests.save(PaymentRequest.forOrder(order));
    return order.getId();
}

Public methods on concrete service classes make these boundaries easy to follow. Spring 6 supports certain non-public methods with class proxies, but interface proxies require public interface methods. Private methods cannot be advised through these proxies, and class proxies cannot override final methods. These examples assume the default proxy mode; AspectJ weaving uses a different interception mechanism.

Propagation decides whether a call joins a transaction

Propagation answers a specific question: what should this method do if the caller already has a transaction?

The table assumes calls through Spring proxies and a transaction manager that supports the requested behavior.

Propagation No current transaction Current transaction exists
REQUIRED Start one Join it
REQUIRES_NEW Start one Suspend it and start an independent one
SUPPORTS Run without a physical transaction Join it
MANDATORY Throw an exception Join it
NOT_SUPPORTED Run without a transaction Suspend it and run without one
NEVER Run without a transaction Throw an exception
NESTED Start one Use a savepoint within it, when supported

REQUIRED is the default. Propagation governs the intercepted scope: a method running without a transaction can still call another bean that starts one. Transaction suspension also depends on manager support.

REQUIRED shares the outcome

Suppose OrderService.placeOrder() calls ReservationService.reserve() through an injected bean. Both methods use @Transactional with default propagation, on the same thread and with the same transaction manager.

OrderService.placeOrder()          transaction T1
    -> ReservationService.reserve() joins T1
    -> save order                   uses T1
End of placeOrder()                completes T1

The two method boundaries share one physical transaction. The inner method returning successfully does not commit its changes independently.

Now suppose reserve() throws an unchecked OutOfStockException, which its transaction interceptor handles as a rollback failure. The outer service catches it:

@Transactional
public void placeOrder(PlaceOrder command) {
    orders.save(Order.pending(command));

    try {
        reservations.reserve(command);
    } catch (OutOfStockException exception) {
        log.info("Reservation failed");
    }
}

With the standard configuration, the inner failure marks the shared transaction rollback-only. Catching the exception does not clear that state. When the outer boundary attempts to commit, Spring rolls back and throws UnexpectedRollbackException. The caller must not be told that work committed when it could only roll back.

REQUIRES_NEW has an independent outcome

An independent audit record is one possible reason for another transaction:

// Method on a separate AuditService bean.
@Transactional(propagation = Propagation.REQUIRES_NEW)
public void recordAttempt(UUID attemptId, String outcome) {
    auditEntries.save(new AuditEntry(attemptId, outcome));
}

When a transactional caller invokes this bean, Spring suspends the outer transaction and runs the audit operation in a new one. A successful audit commit survives a later rollback of the outer operation. If the audit operation fails, its transaction rolls back independently. An exception that escapes back through the outer method can still cause the outer transaction to roll back as well.

The outer transaction retains its resources while the inner one acquires its own. With JDBC, this can require another connection per nested call. Under concurrency, a pool full of outer transactions can leave every thread waiting for an inner connection.

For this audit example, use an attempt identifier that does not require an order row created by the uncommitted outer transaction. An inner transaction generally cannot read that row at normal isolation levels; a foreign key or a conflicting lock can make the audit write fail or wait.

NESTED uses savepoints

NESTED can roll back an inner scope to a savepoint while allowing the outer transaction to continue. The outer transaction still controls the final commit. If it rolls back, the inner work rolls back too.

Support matters here. JDBC transaction managers can use database savepoints. JPA itself does not define nested transactions, and enabling JDBC savepoints in JpaTransactionManager does not rewind the JPA persistence context. Treating NESTED as a drop-in alternative for ordinary JPA entity operations can leave database and in-memory state out of step.

Which exceptions trigger rollback

With Spring's default rollback policy, an exception leaving an intercepted transactional method produces these decisions:

Outcome Default decision
Normal return Attempt commit
RuntimeException or a subclass Roll back
Error or a subclass Roll back
Checked exception, such as IOException Attempt commit

These decisions assume the transaction has not already become rollback-only and completion itself succeeds. An HTTP error response is not a transaction rule: what matters is the exception or state seen at the transactional boundary.

Make a checked exception trigger rollback explicitly when that matches the business operation:

@Transactional(rollbackFor = PaymentRejectedException.class)
public void placeOrder(PlaceOrder command)
        throws PaymentRejectedException {
    // PaymentRejectedException extends Exception.
    orders.save(Order.pending(command));
    paymentPolicy.validate(command); // May throw the checked exception.
}

rollbackFor = Exception.class covers checked exceptions broadly. noRollbackFor can exempt a particular exception, but it cannot restore a transaction already marked rollback-only by a participating operation or persistence provider.

Spring 6.2 also supports a global ALL_EXCEPTIONS default through @EnableTransactionManagement(rollbackOn = ALL_EXCEPTIONS). Check the application's configuration before assuming the default policy applies.

Where we catch the exception matters

An exception caught entirely inside the service may never reach its transaction interceptor:

@Transactional
public void placeOrder(PlaceOrder command) {
    orders.save(Order.pending(command));

    try {
        paymentClient.charge(command); // Ordinary HTTP client.
    } catch (PaymentUnavailableException exception) {
        log.warn("Payment provider unavailable");
    }
}

Assume the HTTP client has no transactional advice and the database remains healthy. The method returns normally, so Spring can commit the order even though the charge failed. If the intended operation must fail, propagate an exception covered by the rollback policy. A broad catch that logs and returns success changes the transaction's outcome.

The earlier reservation example differs because another transaction interceptor had already marked the shared transaction for rollback. Persistence failures can also make a transaction unusable before we catch them. Continuing database work after such a failure is not a reliable recovery strategy.

Handle the application error outside the service boundary, for example in a controller advice, when it needs an HTTP representation. That lets the transactional invocation finish its rollback before the error is translated into a response.

Saving and flushing are different from committing

With JPA, save() does not promise that every SQL statement has already run. flush() synchronizes pending persistence changes with the database; it does not commit the transaction. SQL can run earlier, and some failures only surface during completion.

Calling saveAndFlush() before an external API call can expose some database errors sooner. It cannot guarantee that the later commit will succeed, and it cannot make the API call part of the database transaction.

What happens when we call an external service

Consider this synchronous workflow:

@Transactional
public UUID placeOrder(PlaceOrder command) {
    Order order = orders.saveAndFlush(Order.pending(command));
    PaymentReceipt receipt = paymentClient.charge(command);
    order.markPaid(receipt.reference());
    return order.getId();
}

The payment provider has its own state. The local JPA transaction does not extend over an ordinary HTTP request. A provider can use its own database transaction, but it commits independently of ours.

Failure point Local database outcome Possible provider outcome
Database fails before the request is sent Rollback No charge from this attempt
Provider rejects payment and the client throws an unchecked exception Rollback under the default policy Payment rejected
Provider charges, then the local commit fails Local work does not commit Customer remains charged
Request times out after being sent Depends on handling and rollback policy Provider may already have charged

The timeout case is especially easy to misread. It tells us that the client did not receive a response in time. It does not establish whether the provider performed the operation. Retrying with a new payment identity can produce a second charge.

This is a distributed consistency problem. Changing propagation to REQUIRES_NEW, or adding the same annotation in both services, does not coordinate their commits. Transaction systems such as JTA can coordinate compatible enlisted resources; an ordinary REST endpoint is not automatically such a resource.

There is also a capacity cost. In this example, database access happens before the network call. The transaction can retain a connection and database locks while waiting for the provider. Many slow requests can exhaust the pool and delay unrelated database work. Suspending the transaction with NOT_SUPPORTED does not finish it or release its locks; its resources must remain available for resumption.

Keep database transactions short and persist recovery work

One design for payment processing gives the operation an explicit lifecycle:

Transaction 1
    Save order as PAYMENT_PENDING
    Save payment job in an outbox
    Commit both records

Worker
    Claim the job in a short database transaction
    Call provider outside a database transaction
    Reuse the same idempotency key on every retry

Transaction 2
    Record the confirmed result
    Update order and job state
    Commit

The outbox stores the order and the obligation to perform follow-up work atomically. A worker can find committed jobs after a restart. Claims need a recoverable lease or another concurrency mechanism so that crashes do not leave work permanently stuck. Repeated delivery must be expected.

The payment job needs a stable operation ID, also used as the provider's idempotency key. If the worker crashes after a successful charge but before recording it, it retries or queries the provider using that identity. This requires a provider contract that supports deduplication or outcome lookup, including appropriate key retention. Outbox persistence alone cannot prevent duplicate remote effects.

The order remains pending until its outcome is known. An ambiguous timeout needs retry or reconciliation; a later business failure may require a refund. That refund is a new operation with its own possible failures. A workflow of local commits and compensating actions is commonly described as a saga.

For a synchronous API, a non-transactional orchestrator can similarly call separate beans for the short database phases and perform the network call between them. It still needs persisted pending state and recovery for the gap between the remote result and the final local commit. Moving the HTTP call alone does not close that gap.

What an AFTER_COMMIT listener guarantees

An event listener can defer work until a transaction commits:

@TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
public void onOrderCreated(OrderCreated event) {
    notificationClient.sendConfirmation(event.orderId());
}

This prevents the listener from sending confirmation for a transaction that rolls back. By default, it does not run when the event is published without a transaction. The listener also does not become asynchronous just because it uses @TransactionalEventListener.

An ordinary in-process event is not a durable delivery queue. A process crash between commit and delivery can lose the notification. For work that must survive that gap, persist an outbox record. If the listener itself needs to commit new database changes, call a separate transactional bean with an appropriate new transaction; the original transaction has already committed.

Other transaction settings

readOnly = true communicates that an operation is intended for reads and may enable optimizations. It is not a portable write prohibition. The effect depends on the transaction manager, persistence provider, and database.

Isolation controls which concurrent changes a transaction can observe. The default delegates to the database. An annotation alone does not prevent two requests from reading the same stock count and both deciding to decrement it. Depending on the business rule, use an atomic conditional update, an optimistic version check, a suitable lock, or stronger isolation, with appropriate conflict handling.

timeout configures the transaction timeout in seconds where supported. It does not configure an HTTP client's connect or response timeout. Set those on the client. Isolation and timeout settings also do not replace the characteristics of an existing transaction that a REQUIRED method joins.

Transactions and asynchronous work

With the imperative transaction manager used here, transaction resources are associated with the current thread. Starting a new thread, using CompletableFuture.runAsync(), or invoking an @Async bean does not carry the caller's transaction into that execution.

An asynchronous method can start its own transaction through its own intercepted boundary. It has an independent outcome and may run before the caller commits. Reactive transactions use Reactor context instead of the thread-bound model, so their participation rules need separate treatment.

Verify the boundaries through the real call path

An integration test should call the injected Spring bean so that its transaction proxy participates. Constructing the service directly only tests the method body. Useful cases for this order workflow include:

  1. Fail the second database write and verify that neither record commits.
  2. Throw a checked business exception and verify the intended rollback policy.
  3. Catch a failure from a participating REQUIRED bean and observe the outer rollback.
  4. Commit an audit entry through REQUIRES_NEW, fail the outer operation, and verify that the audit entry remains.
  5. Simulate a provider accepting payment while the client loses the response; verify that recovery reuses the operation identity.

Avoid putting the whole test in a transaction when the behavior under test is service completion. A test-owned transaction can cause the service to join it and defer the very commit failure the test needs to observe. Query the result after the service invocation has completed, using a fresh transaction or connection.

For a checkout flow, make each committed state explicit: an order waiting for payment, a confirmed charge, or a recorded failure requiring recovery. Then place @Transactional around each database transition and give every remote operation a stable identity that recovery can reuse.

Further reading