Video in progress

Senior 🌱 Spring

A single transaction is doing 10 minutes of work. What problems does that cause, and how would you redesign it?

A long transaction holds a connection, holds locks, prevents cleanup of old versions in MVCC (vacuum), and if it fails everything starts over from the beginning. I split it into small, idempotent chunks and turn it into a process that can resume where it stopped.

📖 Answer

For example, monthly invoices for 500,000 customers are generated in a single @Transactional method. What happens:

  • the updated rows sit under locks for 10 minutes, other requests wait or you get deadlocks;
  • in PostgreSQL, while a transaction is open, vacuum can't clean up dead rows and tables bloat;
  • the persistence context holds hundreds of thousands of entities in memory;
  • you hit timeouts such as idle_in_transaction_session_timeout in the proxy or the database;
  • if an error happens in minute 9, everything rolls back and starts over.

The redesign:

  1. split the work into chunks (say, 500 customers each);
  2. each chunk gets its own short transaction (TransactionTemplate);
  3. save progress (the last processed id, or per-item status);
  4. make each chunk idempotent, so reprocessing doesn't create duplicates (unique(customer_id, period));
  5. a lock so it runs on a single instance, or SKIP LOCKED so it can run in parallel.
Long lastId = progress.lastId("invoices-2026-10");
List<Long> ids;
while (!(ids = customers.nextIds(lastId, 500)).isEmpty()) {
    List<Long> batch = ids;   // the lambda needs an effectively final variable
    tx.executeWithoutResult(s -> invoicing.createFor(batch, period));
    lastId = batch.getLast();
    progress.save("invoices-2026-10", lastId);
}

If the job is big and complex, Spring Batch gives you chunking, restart and state out of the box.