Tech Interview RoomStudy guides

Spring

How does @Transactional work? Explain propagation, isolation, rollback rules and the common pitfalls.

Advanced · 2 min read · Lesson 8 of 8 in Spring

Mechanics

@Transactional is applied by a proxy (TransactionInterceptor). Before the method it asks the PlatformTransactionManager (for example JpaTransactionManager) to begin or join a transaction, binding the connection or EntityManager to the current thread. After the method it commits, or rolls back if a matching exception was thrown.

Propagation

  • REQUIRED (default): join an existing transaction or start a new one.
  • REQUIRES_NEW: suspend the current transaction and start an independent one (for example, writing an audit log that must persist even if the business transaction rolls back). It uses a second connection, so heavy use can exhaust the pool.
  • NESTED: a savepoint inside the current transaction (JDBC only, not JPA).
  • SUPPORTS, NOT_SUPPORTED, MANDATORY, NEVER: rarely needed.

Isolation

DEFAULT (the database's: READ COMMITTED for PostgreSQL and Oracle, REPEATABLE READ for MySQL InnoDB), READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE. Higher isolation prevents more anomalies (dirty, non-repeatable and phantom reads) at the cost of concurrency.

Rollback rules

By default, rollback happens only for unchecked exceptions (RuntimeException) and Errors. Checked exceptions commit. Use rollbackFor = Exception.class or make business exceptions unchecked.

Pitfalls

  1. Self-invocation and private methods bypass the proxy (no transaction).
  2. Catching an exception inside the method and not rethrowing means the transaction commits.
  3. An inner REQUIRED method throws, the outer method catches it and continues: the transaction is already marked rollback-only, and the outer commit fails with UnexpectedRollbackException.
  4. Long transactions holding connections while calling remote services; keep network calls outside the transaction.
  5. readOnly = true is a hint: it lets Hibernate skip dirty checking and flushing and lets drivers route to replicas, but it is not a security mechanism.
  6. Transactions are thread-bound: work submitted to another thread or @Async method is not part of the caller's transaction.

Example

java
@Service
class OrderService {
    private final AuditService audit;  // separate bean so REQUIRES_NEW goes through its proxy

    @Transactional(rollbackFor = Exception.class, timeout = 5)
    public Order place(OrderRequest req) throws PaymentException {
        Order order = orders.save(Order.from(req));
        inventory.reserve(order);          // runtime exception → rollback
        payments.charge(order);            // checked PaymentException → rollback thanks to rollbackFor
        audit.record("ORDER_PLACED", order.getId());
        return order;
    }
}

@Service
class AuditService {
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void record(String type, Long id) { auditRepo.save(new AuditEvent(type, id)); }
}

Follow-up questions interviewers ask

Try answering each one before you open it.

When does REQUIRES_NEW cause problems?

Each nested REQUIRES_NEW holds an extra connection while the outer transaction still holds its own. Under load, with a pool of N connections and N concurrent outer transactions, every thread waits for a second connection that never frees up: a pool deadlock. It can also cause lock waits if the inner transaction touches rows the outer one has locked. Use it sparingly and size the pool accordingly.

How do you run code only after a transaction commits?

Use @TransactionalEventListener(phase = AFTER_COMMIT) with an event published inside the transaction, or TransactionSynchronizationManager.registerSynchronization(...). This prevents, for example, sending an "order confirmed" email for an order that is later rolled back. For guaranteed delivery to other services, use the transactional outbox pattern, because the process can crash between commit and send.

Which isolation level would you use for a balance update, and why?

Usually READ COMMITTED plus explicit concurrency control: an atomic SQL update (UPDATE account SET balance = balance - :amt WHERE id = :id AND balance >= :amt), optimistic locking with @Version, or SELECT ... FOR UPDATE for a short critical section. Raising everything to SERIALIZABLE works but causes serialisation failures under contention that you must retry, and reduces throughput.