TL;DR: If you lock a row and then make an HTTP call inside the same transaction, the lock and the database connection are held for the whole call. @Async called on this doesn’t help, and afterCommit only half helps: it releases the lock but keeps the connection, and quietly throws away your writes. What works: commit first, then hand the call to a @TransactionalEventListener(AFTER_COMMIT) + @Async listener in a separate bean.

In the post about Apache HttpClient defaults, I said a well-sized connection pool is only half the story. This is the other half.

Take a simple online bookstore as the example. It has a “ship order” button. When you press it, the app marks the order as shipped and tells a (pretend) warehouse service to send the parcel. There’s also a “cancel order” button. Obviously, shipping and cancelling the same order at the same moment would be bad, so the natural move is to lock the order row while working on it.

Here’s the code most of us would write first. It looks completely reasonable:

@Transactional
public void ship(Long orderId) {
    BookOrder order = repo.findByIdForUpdate(orderId).orElseThrow(); // SELECT ... FOR UPDATE
    order.setStatus(SHIPPED);
    warehouseClient.createShipment(orderId);                      // HTTP call
}

Lock the row so nobody else touches it, update it, tell the warehouse. The tests pass. But press cancel while a shipment is in progress and the cancel button spins for ages. And with a few shipments running at once, the whole app gets sluggish, including pages that have nothing to do with orders.

To understand exactly why, I built a small Spring Boot 3.5 example app with:

  • an H2 database (I raised H2’s lock timeout so it waits the way MySQL and PostgreSQL do),
  • a fake warehouse API that takes 2 seconds to answer,
  • a database connection pool of just 3 connections, to make problems easy to see.

All the timings below are real output from that app.

Quick refresher: what does “locking a row” mean?

findByIdForUpdate is a Spring Data method annotated with @Lock(LockModeType.PESSIMISTIC_WRITE), which becomes SELECT ... FOR UPDATE in SQL. It tells the database: “I’m about to change this row. Anyone else who wants to lock it has to wait until I’m done.”

The key question is: when am I “done”? Not when you finish with the row. The lock is released when the transaction ends, with a commit or a rollback. And with @Transactional on the method, the transaction ends when the method returns.

The HTTP call is inside the method, so the lock is held until the warehouse answers.

It’s like taking the key to the only fitting room in a shop, then walking off to the till with it in your pocket while you queue to pay. Nobody else can use the fitting room, even though you’re not using it either.

Problem 1: other requests wait for your network call

Here’s a cancel for the same order, arriving 200 ms after the shipment started:

[0.03s] ship     locked order 1
[0.03s] ship     calling warehouse for order 1
[0.20s] cancel   trying to lock order 1
[2.09s] ship     warehouse replied
[2.09s] cancel   got the lock

The cancel waited almost 2 seconds, and none of that was database work. It was waiting for someone else’s HTTP call to finish. If the warehouse takes 30 seconds, so does your cancel.

And the database won’t rescue you quickly: by default, MySQL’s InnoDB waits up to 50 seconds for a row lock, and PostgreSQL waits forever unless you set lock_timeout.

Problem 2: the connection is stuck too

A transaction doesn’t only hold the lock. It holds a database connection from your pool for its whole lifetime.

Next, six concurrent ship calls on six different orders. No lock conflicts at all, just a pool of 3 connections:

[0.01s] locked order 9 / 8 / 7, calling warehouse...
[0.51s] active=3  waiting for a connection=3
[2.02s] locked order 10 / 11 / 12, calling warehouse...
[4.04s] 6 ships done

Three requests grabbed a connection and then sat on it, doing nothing, while waiting for HTTP. The other three couldn’t even start: they were queued for a connection that was just idling. Six calls that should take 2 seconds took 4.

That’s why the whole app gets sluggish. Scale it up: a slow warehouse plus a busy “ship” button can use up the entire pool, and then every feature that needs the database stops working, including browsing books, logging in, and everything else.

Bonus: the waiting request holds a connection too

With HikariCP’s leak detection turned on which logs a warning when a connection is held longer than a threshold, it flags both requests:

WARN ProxyLeakTask : Connection leak detection triggered for conn0 ... on thread pool-3-thread-1
java.lang.Exception: Apparent connection leak detected
    at demo.Shipping$$SpringCGLIB$$0.shipHoldingLock(<generated>)

WARN ProxyLeakTask : Connection leak detection triggered for conn1 ... on thread main
java.lang.Exception: Apparent connection leak detected
    at demo.Cancelling$$SpringCGLIB$$0.cancel(<generated>)

The first one is the shipment holding its connection during the HTTP call. The second is the cancel: while it’s blocked waiting for the row lock, it’s also holding a connection. So one slow HTTP call can tie up two connections, and the more requests pile up behind the lock, the faster the pool drains.

Attempt #1: “just make it @Async”

A common first idea is to push the HTTP call into an async method so the transaction can finish:

@Transactional
public void ship(Long orderId) {
    BookOrder order = repo.findByIdForUpdate(orderId).orElseThrow();
    order.setStatus(SHIPPED);
    this.notifyWarehouseAsync(orderId);   // looks async...
}

@Async
public void notifyWarehouseAsync(Long orderId) {
    warehouseClient.createShipment(orderId);
}

It changes absolutely nothing:

[0.00s] pool-3-thread-1   locked order 2
[0.00s] pool-3-thread-1   calling warehouse (tx active=true)
[0.20s] main              cancel: trying to lock order 2
[2.01s] pool-3-thread-1   warehouse replied
[2.01s] pool-3-thread-1   returned from notifyWarehouseAsync
[2.01s] main              cancel: got the lock

Check the thread names: the “async” call ran on the same thread, synchronously, still inside the transaction.

Why: Spring’s annotations live on a proxy

Spring makes @Async, @Transactional and friends work by wrapping your bean in a proxy, a stand-in object that adds the extra behaviour and then calls your real method.

other bean ──► [ proxy: adds @Async / @Transactional ] ──► your real object

When another bean calls your method, the call goes through the proxy and the annotation works. But this.notifyWarehouseAsync() is a call from your object to itself. It never goes through the proxy, so the annotation is simply ignored. The same thing happens with @Transactional(propagation = REQUIRES_NEW) or NOT_SUPPORTED on a method you call from inside the same class.

Attempt #2: run it after commit

Spring lets you register code that runs once the transaction has committed:

@Transactional
public void ship(Long orderId) {
    BookOrder order = repo.findByIdForUpdate(orderId).orElseThrow();
    order.setStatus(SHIPPED);

    TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
        @Override public void afterCommit() {
            warehouseClient.createShipment(orderId);
        }
    });
}

This fixes the lock:

[0.01s] ship     locked order 3
[0.01s] ship     afterCommit: active DB connections=1
[0.01s] ship     calling warehouse (tx active=true)
[0.21s] cancel   trying to lock order 3
[0.21s] cancel   got the lock          <- no waiting!
[0.72s] main     mid-call: active DB connections=1
[2.02s] ship     warehouse replied
[2.02s] main     after call: active DB connections=0

The cancel got the lock right away. 🎉 But look at the connection count: the connection is still checked out for the whole HTTP call. afterCommit runs after the commit, but before Spring cleans up and hands the connection back to the pool. It even still reports a transaction as active. So the lock problem is solved, and the pool problem is still there.

And a sneaky trap: writes in afterCommit vanish

Say you want to record “warehouse notified” on the order after the call:

@Override public void afterCommit() {
    BookOrder again = repo.findById(orderId).orElseThrow();
    again.setStatus(WAREHOUSE_NOTIFIED);
    repo.save(again);                    // no error...
}
afterCommit: saved status WAREHOUSE_NOTIFIED
status of order 5 in DB: SHIPPED

No exception, no warning, and the update just never reached the database. The transaction it would have joined has already committed, so there’s nothing left to commit it. The Spring docs do mention this (you’d need a REQUIRES_NEW transaction), but it’s very easy to miss, and silent data loss is the worst kind.

What actually works: commit first, then hand off

The version that fixes everything has three parts:

  1. Publish an event inside the transaction.
  2. Listen for it only after commit.
  3. Run the listener asynchronously, in a separate bean, so the call goes through the proxy and @Async really works.
@Transactional
public void ship(Long orderId) {
    BookOrder order = repo.findByIdForUpdate(orderId).orElseThrow();
    order.setStatus(SHIPPED);
    events.publishEvent(new OrderShipped(orderId));
}
@Component
class WarehouseNotifier {
    @Async
    @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT)
    public void on(OrderShipped e) {
        warehouseClient.createShipment(e.orderId());
    }
}

(Don’t forget @EnableAsync on one of your configuration classes, otherwise @Async does nothing.)

[0.01s] task-1   calling warehouse (tx active=false)
[0.21s] main     cancel: got the lock          <- no waiting
[0.21s] main     active DB connections now: 0  <- connection already returned
[2.01s] task-1   warehouse replied

The HTTP call now runs on a different thread (task-1), outside any transaction, holding neither the lock nor a connection. Rerunning the six-concurrent-ships test:

[0.01s] 6 ships committed; active=0
[2.02s] all 6 warehouse calls replied

All six committed in about 10 milliseconds. The tiny pool of 3 wasn’t a bottleneck at all, because nobody held a connection longer than their actual database work.

A nice bonus: because the listener only fires AFTER_COMMIT, the warehouse is never told about a shipment that later rolled back.

The catch: “later” can fail

Moving the call after commit is a trade-off, not a free win. The database now says SHIPPED before the warehouse knows anything. So what if the warehouse call fails, or the app restarts in between? It’s worth deciding up front:

  • Is it OK to lose one now and then? For something like a “thanks for your order” email, retry a few times and log failures. Good enough.
  • Must it always happen? Use the transactional outbox pattern. In the same transaction as the status change, insert a row into an outbox table that says “tell the warehouse about order 42”. A small background job reads the outbox, makes the call, and marks the row as done. Because the outbox row commits together with the order, the call is guaranteed to happen eventually.
  • Can the receiver handle duplicates? Once you retry, the warehouse will sometimes get the same request twice. Send an idempotency key, like the order ID, so it can ignore repeats.

And keep an eye on the @Async executor. Spring Boot’s default runs 8 threads with an unbounded queue (configurable under spring.task.execution.pool.*). If the warehouse slows down, tasks quietly pile up in memory instead of failing. Give it a size and a queue limit that suit your app. Also remember that exceptions thrown from void @Async methods never reach the caller, so set an AsyncUncaughtExceptionHandler to at least log them.

How to spot this in your own code

A few things that help you find (and prevent) this:

  • Turn on HikariCP leak detection in development: spring.datasource.hikari.leak-detection-threshold=2000. It logs a stack trace whenever a connection is held longer than that, which is exactly the “HTTP call inside a transaction” smell. One gotcha: values under 2000 ms are silently ignored. Hikari logs a warning at startup and disables leak detection.
  • Search for remote calls inside @Transactional methods: HTTP clients, message publishing, file uploads, sending email. Anything that isn’t the database is a suspect.
  • Look for this.someMethod() calls to methods annotated with @Async or @Transactional. They won’t do what the annotation says.
  • Set a lock wait timeout (innodb_lock_wait_timeout in MySQL, lock_timeout in PostgreSQL) so a stuck request fails clearly instead of hanging.

The checklist

  • No HTTP calls, messaging, or file I/O inside a transaction that holds a lock
  • Keep SELECT ... FOR UPDATE transactions short: lock, check, update, commit
  • Don’t call @Async / @Transactional methods via this
  • Remember afterCommit releases the lock but not the connection, and writes inside it are lost
  • Prefer @TransactionalEventListener(AFTER_COMMIT) + @Async in a separate bean
  • Decide what happens when the post-commit call fails: retry, outbox, or accept the loss
  • Give the async executor a sensible size and a bounded queue
  • Turn on leak detection in dev, and set lock wait timeouts

The rule to remember: a transaction should only ever wait on the database. Everything else happens after the commit.