Skip to content

Lesson 3 of 9 · 28m

Database Access That Respects Transactions

Understand persistence contexts, transaction boundaries, lock behavior, and query shape before JPA turns small mistakes into production incidents.

A system I once debugged lost inventory only during flash sales. The code looked correct: read stock, decrement, save. The bug was not SQL syntax; it was transaction design. Two requests read the same entity, both decremented it, both committed. The database did exactly what it was told. JPA did not save the team from understanding isolation, locking, and boundaries. It merely made the failure easier to miss.

Transactions belong at the application-service boundary

A transaction should cover one unit of business work:

@Service
public class OrderService {
    @Transactional
    public Receipt placeOrder(PlaceOrderCommand command) {
        Order order = orders.findByIdForUpdate(command.orderId())
            .orElseThrow(() -> new OrderNotFound(command.orderId()));
        order.reserve(command.items());
        payments.authorize(order.paymentReference(), order.total());
        return orders.save(order).receipt();
    }
}

Controllers should not orchestrate half-transactions across multiple service calls. Repositories should not decide business transaction scope. If rollback behavior is part of correctness, make it visible at the service boundary.

Read-modify-write is not automatically safe

This pattern is a race waiting for traffic:

var item = repository.findById(itemId).orElseThrow();
item.decreaseStock(1);
repository.save(item);

Use database constraints, atomic updates, optimistic locking, or pessimistic locks depending on contention:

@Modifying
@Query("update InventoryItem i set i.available = i.available - :quantity " +
       "where i.id = :id and i.available >= :quantity")
int decrementIfAvailable(@Param("id") UUID id, @Param("quantity") int quantity);

A zero-row result is meaningful. Treat it as insufficient stock, not as success.

N+1 is a traffic multiplier

An endpoint that returns 100 orders can execute 101 queries if each order lazily loads a customer. Under low traffic this looks fine. Under production concurrency it becomes pool exhaustion and cascading latency. Use entity graphs, join fetches for controlled cases, or explicit DTO projections. Measure actual SQL in tests and staging.

Do not enable routine SQL logging in production as a diagnostic lifestyle. It is expensive and leaks data.

Know what rollback really means

By default, Spring rolls back for unchecked exceptions and commits for checked exceptions unless configured otherwise. Timeouts and remote failures complicate the story: a payment can succeed remotely while the local database transaction rolls back. Use idempotency keys, reconciliation jobs, and explicit state machines where side effects cross system boundaries.

Field notes

  • REQUIRES_NEW is not a performance tool or a retry shortcut; it creates a real separate transaction with real deadlock and consistency consequences.
  • Transactional self-invocation does not pass through the proxy, so annotations on internal method calls often do nothing.
  • Long transactions hold locks and connection pool slots. Do not call remote services inside them unless you have measured the consequences.
  • Unique constraints are correctness controls. Application-level existence checks alone race under concurrency.
  • If every query needs a lock, the data model or workflow partitioning probably needs redesign.

Was this lesson helpful?

Sign in to rate