Database Transactions in Spring: @Transactional, Propagation and Isolation

How Spring manages transactions: ACID, PlatformTransactionManager, how @Transactional works through proxies, rollback rules, all seven propagation behaviours with use cases, isolation levels and anomalies, read-only transactions, timeouts, optimistic and pessimistic locking, programmatic TransactionTemplate, and transactions with messaging.

On this page

Simple definition#

A transaction groups database operations so they all succeed or all fail (ACID). In Spring you declare transaction boundaries with @Transactional. A proxy then begins, commits or rolls back through a PlatformTransactionManager (for example JpaTransactionManager).

The problem#

Without clear boundaries, a failure halfway through “debit account, credit account, record transfer” leaves money missing. Wrong propagation silently joins or splits transactions. Wrong isolation allows lost updates and double bookings. Misplaced @Transactional simply does nothing.

ACID in one table#

PropertyMeaning
AtomicityAll or nothing
ConsistencyConstraints and invariants hold before and after
IsolationConcurrent transactions do not see each other’s intermediate states (to a configurable degree)
DurabilityCommitted data survives crashes

How @Transactional works#

Open the interactive diagram: How @Transactional works through a proxy Standalone page with zoom, light/dark themes and SVG/PNG export, generated with Archify. Diagram source.

@Service
class TransferService {
    @Transactional                                       // REQUIRED, default isolation, rollback on RuntimeException
    public void transfer(AccountId from, AccountId to, Money amount) {
        Account a = accounts.findByIdForUpdate(from);    // pessimistic lock (see below)
        Account b = accounts.findById(to).orElseThrow();
        a.debit(amount);
        b.credit(amount);
        transfers.save(new Transfer(from, to, amount));
    }                                                    // commit (flush, then COMMIT) or rollback
}
  • The proxy (AOP) begins or joins a transaction, binds the connection to the current thread, calls the method, then commits or rolls back. See AOP and proxies.
  • Put @Transactional on public service methods (the use-case boundary), not on repositories or controllers.
  • Self-invocation (this.otherTransactionalMethod()) bypasses the proxy.

Rollback rules#

  • By default: roll back on RuntimeException and Error, commit on checked exceptions.
  • Change that with @Transactional(rollbackFor = Exception.class) or noRollbackFor = ….
  • An exception caught inside the method does not roll back, unless you call TransactionAspectSupport.currentTransactionStatus().setRollbackOnly().
  • If an inner REQUIRED method throws and the outer method catches, the shared transaction is marked rollback-only, so the outer commit throws UnexpectedRollbackException.

Propagation#

PropagationIf a transaction existsIf none existsUse case
REQUIRED (default)Join itStart a new oneAlmost everything
REQUIRES_NEWSuspend it, start a new independent oneStart newAudit logs or outbox entries that must persist even if the caller rolls back. Uses a second connection.
NESTEDSavepoint inside the current one (JDBC only)Start newPartial rollback of a sub-step
SUPPORTSJoinRun withoutRead helpers that work either way
MANDATORYJoinThrowMethods that must be called inside a transaction
NOT_SUPPORTEDSuspend, run withoutRun withoutLong non-transactional work (calling external APIs)
NEVERThrowRun withoutGuard against transactions
REQUIRED joins; REQUIRES_NEW suspends and starts another
flowchart LR
    A["placeOrder()<br/>REQUIRED: tx1"] --> B["reserveStock()<br/>REQUIRED: joins tx1"]
    A --> C["writeAudit()<br/>REQUIRES_NEW: tx2<br/>(commits even if tx1 rolls back)"]

Isolation levels#

LevelDirty readNon-repeatable readPhantom readNotes
READ_UNCOMMITTEDpossiblepossiblepossibleRarely used
READ_COMMITTED✗possiblepossiblePostgreSQL, Oracle and SQL Server default
REPEATABLE_READ✗✗possible (no phantoms in PostgreSQL’s snapshot implementation)MySQL InnoDB default
SERIALIZABLE✗✗✗Safest; may fail with serialisation errors, so retry

@Transactional(isolation = Isolation.SERIALIZABLE) overrides the database default per transaction.

Lost updates and write skew are the anomalies that bite business code most (two users booking the last seat). Prevent them with locking or serializable isolation.

Locking#

ApproachHowUse when
Optimistic@Version column. UPDATE … WHERE version = ?; on conflict, OptimisticLockExceptionLow contention, web forms (pair with ETag / If-Match). Retry or report the conflict.
Pessimistic@Lock(PESSIMISTIC_WRITE) gives SELECT … FOR UPDATEHigh contention, short critical sections (balances, inventory)
Atomic SQLUPDATE stock SET qty = qty - :n WHERE sku = :s AND qty >= :nCounters and stock: often the simplest and fastest
SKIP LOCKEDFOR UPDATE SKIP LOCKEDWork queues in the database

Read-only and timeouts#

  • @Transactional(readOnly = true) lets Hibernate skip dirty checking and snapshots, and can route to read replicas. Put it on query services; class-level read-only with method-level writes is a common pattern.
  • @Transactional(timeout = 5) caps long transactions.
  • Keep transactions short: no remote HTTP calls inside a transaction. They hold locks and connections while waiting.

Programmatic transactions#

transactionTemplate.executeWithoutResult(status -> {
    repository.save(entity);
    if (!valid) status.setRollbackOnly();
});

Useful for fine-grained boundaries, loops with a transaction per item, or avoiding self-invocation issues.

Transactions and messaging#

A database transaction does not include Kafka or RabbitMQ sends or HTTP calls. To publish events reliably with a DB change, use the transactional outbox, or @TransactionalEventListener(AFTER_COMMIT) for best-effort in-process reactions. See application events and event-driven architecture.

Common mistakes#

Quick check#

Which exceptions roll back by default? RuntimeException and Error. Checked exceptions commit unless rollbackFor is set.

REQUIRED vs REQUIRES_NEW? REQUIRED joins an existing transaction or starts one. REQUIRES_NEW always suspends the current one and runs in a new, independent transaction.

What is PostgreSQL’s default isolation level? READ COMMITTED.

Optimistic vs pessimistic locking? Optimistic detects conflicts at write time with a version column. Pessimistic locks rows (SELECT … FOR UPDATE) to prevent them.

Why shouldn’t you call external APIs inside a transaction? The transaction holds connections and locks for the whole network wait, which hurts throughput and risks deadlocks and timeouts.

What does readOnly = true do with Hibernate? It skips dirty checking and snapshot storage and hints the database. It may route to read replicas.

Summary#

  • @Transactional works through proxies: public methods, called from outside.
  • Default rollback is on unchecked exceptions; REQUIRED joins; REQUIRES_NEW isolates (at the cost of a second connection).
  • Choose isolation and locking for the anomalies you must prevent.
  • Keep transactions short and local; use the outbox for messaging.

References#