The 3 a.m. Deadlock

A Field Guide to Diagnosing and Fixing Real Production Deadlocks in Spring Boot + JPA


The pager goes off at 03:14. The nightly batch, the one that closes the day for a few thousand customers, has rolled back. Your phone shows three Slack messages already, the first one a single word: “again?”. By 03:18 you are at the kitchen table with a laptop, dependency tree in one tab, the previous incident’s post-mortem in another, and a half-formed suspicion that the fix you shipped two weeks ago did not actually fix anything.

This article is for the engineer at that kitchen table. It is a field guide to the deadlocks that actually occur in long-lived Spring Boot applications backed by JPA. The kind you do not see in textbook examples. The kind that hide for months and surface at the worst possible time. The patterns described here come from production incidents on real enterprise systems: nightly batch jobs, planning engines, integration adapters between Spring Boot and ERP backends.

If you have been doing this for more than a few years, you have probably met some of these. If you are newer, this might save you a few of those 03:14 mornings.

Why This Article Exists

The Java publishing landscape has plenty of material on transactions in the abstract: isolation levels, MVCC primers, “what your ORM does not tell you” tutorials. There is much less material on what to actually do when a relational deadlock has just rolled back a 47-minute batch and you have less than an hour to decide whether to retry, patch, or escalate.

There is one notable JAVAPRO piece on deadlocks: Adelina Simion’s “No Deadlocks in MongoDB: Atomic Documents and Retries with Spring Data MongoDB”. That article makes a clear, valid argument for the document-database side of the trade-off space. The piece you are reading is the relational counterpart. Spring Boot teams running PostgreSQL, MySQL/MariaDB, Oracle, or SQL Server still hit deadlocks regularly, and the diagnostic and architectural moves on the relational side are different enough to deserve their own treatment.

What a Deadlock Actually Is, Without the Hand-Waving

A relational deadlock occurs when two or more transactions hold locks that the others need, in a cycle the database cannot break by waiting. Modern databases detect this and pick a victim, but the codes they raise are not identical, and the distinctions matter when you are writing exception handlers:

  • PostgreSQL raises SQLSTATE 40P01 (deadlock_detected) for deadlocks. SQLSTATE 40001 (serialization_failure) is a different condition. It surfaces under SERIALIZABLE or REPEATABLE READ isolation when the engine can no longer guarantee a serial schedule. Both are typically retryable, but they are not the same.
  • MySQL/InnoDB raises error 1213 with SQLSTATE 40001 for deadlocks. The victim transaction is rolled back automatically, and you can inspect the deadlock via SHOW ENGINE INNODB STATUS.
  • Oracle raises ORA-00060. SQL Server raises error 1205 and exposes a deadlock graph in the system_health Extended Events session.

In a Spring JDBC or Spring Data JPA stack, these vendor codes will usually surface as a transient data access exception, most often CannotAcquireLockException or PessimisticLockingFailureException. Both are subclasses of TransientDataAccessException. The exact mapping depends on your driver, JPA provider, and the configured SQLExceptionTranslator, so the right move once in your codebase is to write a small integration test that triggers a real deadlock and confirms which exception type your stack actually produces. That is the type your retry logic should target.

A few things follow from this that matter for the rest of the article:

  • A deadlock is not a bug in the database. The database is doing its job by detecting the cycle and rolling one transaction back. A deadlock is a signal that your application’s locking pattern contains a cycle.
  • A deadlock is transient. The classification matters because it determines what your code is allowed to do automatically. A transient failure can be retried; a logical failure (constraint violation, business rule breach) cannot.
  • The database tells you exactly which locks were involved if you ask it. PostgreSQL’s pg_locks view, MySQL’s SHOW ENGINE INNODB STATUS, and Oracle’s V$LOCK are the canonical sources. The thread dump tells you what your application was doing. Only the database tells you what the transactions were doing.

That last point is where most relational deadlock investigations go wrong. The reflex is to reach for jstack first, find a thread parked on a JDBC socket read, and conclude that the application is “stuck on the database”. That is true but useless. The thread dump shows the symptom; the database log and lock views show the cause.

The First 15 Minutes: A Triage Playbook

When the page comes in, you have a small number of decisions to make quickly. Make them in this order.

1. Confirm it is actually a deadlock, not a long lock-wait. A timeout (org.postgresql.util.PSQLException: ERROR: canceling statement due to lock timeout) is not a deadlock. It means a transaction held a lock longer than your lock_timeout and you killed it. The fixes are different. Look at the SQLState in the exception. PostgreSQL 40P01, MySQL 1213 (SQLSTATE 40001), Oracle ORA-00060, and SQL Server 1205 are deadlocks. PostgreSQL 57014 (query cancellation) or a Spring QueryTimeoutException is a timeout. PostgreSQL 40001 on its own is a serialization failure: also retryable, but a different condition with a different fix.

2. Decide whether to retry or escalate. If the rolled-back transaction is idempotent and the load is not pathological, a single automatic retry is usually safe and almost always correct. If the same transaction has now deadlocked three times in a row, retry is masking a real lock-ordering problem. Escalate.

3. Capture the evidence before it disappears. PostgreSQL writes the deadlock detail to its log when log_lock_waits and deadlock_timeout are configured. MySQL keeps only the latest deadlock in SHOW ENGINE INNODB STATUS, which means the next deadlock will overwrite the one you need. Pull both immediately:

-- PostgreSQL: which queries are blocking which RIGHT NOW?
SELECT blocked.pid AS blocked_pid,
       blocked.usename AS blocked_user,
       blocking.pid AS blocking_pid,
       blocking.usename AS blocking_user,
       blocked.query AS blocked_query,
       blocking.query AS blocking_query
FROM pg_stat_activity AS blocked
JOIN pg_stat_activity AS blocking
  ON blocking.pid = ANY(pg_blocking_pids(blocked.pid))
WHERE NOT blocked.pid = blocking.pid;

A caveat that catches teams off-guard: this query is only useful while a blocking situation is still active. By the time PostgreSQL has detected a deadlock and aborted the victim, the cycle is already gone, and pg_blocking_pids will return nothing. For an already-detected deadlock, the database log is the primary evidence, not the live catalog views. The catalog views are for live lock-waits that have not yet escalated.

-- MySQL/MariaDB: most recent deadlock graph
SHOW ENGINE INNODB STATUS;
-- Look at the LATEST DETECTED DEADLOCK section.

4. Correlate with application logs. Your Spring Boot app should be logging the SQLState and the transaction name. If it is not, fix that today. The single most useful log line during an incident is the one that says: “Transaction OrderBatchService.closeDay failed with SQLState 40P01 on attempt 2 of 3″. You can build that from a custom @Around advice on @Transactional methods, or by configuring spring.jpa.properties.hibernate.session.events.log and logging.level.org.springframework.transaction=DEBUG for the duration of the incident.

Once you have the deadlock graph from the database and the call stack from the application, you can usually identify the pattern within minutes.

Five Deadlock Patterns That Cover Most Real Incidents

Across enough production systems, the same handful of patterns turn up again and again. None are exotic. All of them are subtle enough to survive code review.

Pattern 1: Inconsistent Lock Ordering Across Two Entities

Symptom. Two transactions touching the same pair of rows from opposite directions. The textbook example is funds transfer. The production example is something less obvious, like a “merge customer” job that touches customers in pairs and is invoked concurrently from two different triggers.

// Looks innocent. Is not.
@Transactional
public void merge(long sourceId, long targetId) {
    Customer source = customerRepo.findById(sourceId).orElseThrow();
    Customer target = customerRepo.findById(targetId).orElseThrow();
    target.absorb(source);
    customerRepo.delete(source);
}

If thread A calls merge(1, 2) and thread B calls merge(2, 1) at the same moment, you have a textbook lock-ordering deadlock. The fix is the textbook fix: impose a total order on the locks.

@Transactional
public void merge(long sourceId, long targetId) {
    long firstId  = Math.min(sourceId, targetId);
    long secondId = Math.max(sourceId, targetId);

    // Acquire locks in deterministic order.
    Customer first  = customerRepo.findByIdForUpdate(firstId).orElseThrow();
    Customer second = customerRepo.findByIdForUpdate(secondId).orElseThrow();

    Customer source = (firstId == sourceId) ? first  : second;
    Customer target = (firstId == sourceId) ? second : first;

    target.absorb(source);
    customerRepo.delete(source);
}

public interface CustomerRepository extends JpaRepository<Customer, Long> {

    @Lock(LockModeType.PESSIMISTIC_WRITE)
    @Query("select c from Customer c where c.id = :id")
    Optional<Customer> findByIdForUpdate(@Param("id") long id);
}

The substantive change here is not the addition of @Lock. It is the ordering of the locks. Without ordering, pessimistic locking just moves the deadlock around without preventing it.

Lesson. Whenever a transaction acquires write locks on more than one row of the same table, define an ordering and stick to it. The simplest ordering, sort by primary key, is almost always correct. Document the rule in the entity’s class comment so the next engineer who adds a method does not break it.

Pattern 2: The Shared Hot Row Hidden Inside a Parallel Batch

This is the pattern most likely to wake you at 03:14. It scales with batch size and only manifests once the data is large enough. Suppose you have orders and order items, with a foreign key from order_item.order_id to order.id. Your nightly batch closes orders in parallel chunks:

@Transactional
public void closeOrder(long orderId) {
    Order order = orderRepo.findById(orderId).orElseThrow();
    order.markClosed();
    // ... and somewhere down the call chain ...
    auditService.recordClosure(order);   // inserts into order_audit
    metricsService.bumpCounter(order);   // updates a small "stats" row
}

When two threads close two different orders, they are not contending on order rows. They are contending on the stats row that metricsService updates. Every closing transaction wants to write to it, and the write lock on a single shared row serialises an otherwise parallel batch. The deadlock arrives when chunk A is holding a write lock on order row 100 and waiting for the stats row, while chunk B is holding the stats row and waiting on a foreign-key path back to data chunk A has not yet committed. Whether that FK path actually produces a wait depends on your database, your isolation level, and your indexes. With insufficiently indexed FKs and parallel writers, the cycle is depressingly easy to construct.

The fix is not better locking. It is a separation of concerns:

  1. Move the hot “stats” update out of the per-order transaction. Maintain it asynchronously, or batch it once at the end.
  2. If the audit must be transactional with the close, write to a dedicated audit table that does not feed back into the same lock graph.
  3. When batches do touch the same tables, configure Hibernate to make insert order deterministic:
# application.properties
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_inserts=true
spring.jpa.properties.hibernate.order_updates=true
spring.jpa.properties.hibernate.batch_versioned_data=true

hibernate.order_inserts and hibernate.order_updates make Hibernate order batched DML deterministically, primarily by entity type and primary-key value. This both improves batching and reduces the probability of two parallel sessions producing a cycle when they touch the same tables. Hibernate’s own documentation recommends them for highly concurrent workloads, and they have resolved more nightly-batch deadlocks than any clever lock annotation. Set them as a baseline for batch-heavy systems, but treat them as a configuration decision, not free magic. Verify behavior with your entity graph, your batch size, and your database before declaring victory.

Lesson. Anything that every transaction in a workload writes to is a deadlock magnet. Counters, “last updated” rows, monotonically increasing audit metadata: none of these belong in the hot path of a parallel batch. Get them out.

Pattern 3: The Long Transaction That Crossed a Hot Row

This is the pattern that survives code review because it does not look like a transaction problem at all. A service method is annotated @Transactional, does a bit of work, makes a remote call, then writes a row. The remote call takes 800 ms on average and 9 seconds at the 99th percentile. While you are waiting, you are holding every lock you have already acquired, including, crucially, any row you wrote to inside this transaction.

// The 800ms remote call holds your DB locks the entire time.
@Transactional
public void enrichAndSave(long orderId) {
    Order order = orderRepo.findById(orderId).orElseThrow();
    order.markEnrichmentStarted();      // UPDATE; lock held
    EnrichmentDto dto = httpClient.fetch(orderId);   // 800ms to 9s
    order.applyEnrichment(dto);
    // implicit commit at method exit
}

Under load, the long tail of that HTTP call combined with the held lock on order produces a pathology that looks like a deadlock from above. The database reports it as one when a second transaction joins the cycle. Underneath, it is a lock duration problem.

The fix is structural:

public void enrichAndSave(long orderId) {
    EnrichmentDto dto = httpClient.fetch(orderId);   // OUTSIDE any transaction

    enrichmentTx.persist(orderId, dto);              // short, local transaction
}

@Component
class EnrichmentTransaction {

    @Transactional
    public void persist(long orderId, EnrichmentDto dto) {
        Order order = orderRepo.findById(orderId).orElseThrow();
        order.applyEnrichment(dto);
    }
}

The transaction now spans only the database work. The remote call happens with no locks held. This is sometimes summarised as “never hold a database lock across a network call you do not control”, a rule that is easier to state than to enforce, but worth enforcing anyway.

Lesson. A @Transactional method is a contract about lock duration as much as about consistency. Audit your transactional methods for hidden I/O: HTTP calls, message broker publishes, file system reads, calls to other services. Each one is a candidate to either move outside the transaction or to wrap in a hard timeout.

Pattern 4: Mixed Optimistic and Pessimistic Locking on the Same Entity

This pattern is rare but devastating when it happens, because the cause is not visible at any single call site. It occurs when two code paths through the same entity disagree on the locking strategy: one path uses @Version optimistic locking, another uses SELECT ... FOR UPDATE (pessimistic). The optimistic path increments the version, the pessimistic path holds a row lock, and an unfortunate concurrent ordering produces a wait cycle.

The diagnostic clue is a deadlock graph showing one transaction blocked on a row-level write lock while the other is blocked on what looks like an UPDATE ... WHERE version = ? predicate.

There is no clever way to mix these implicitly. The dangerous state is not the mere presence of both mechanisms. @Version plus an occasional PESSIMISTIC_WRITE escalation is a defensible design. The dangerous state is undocumented and inconsistent use across code paths. If you keep @Version on an entity, decide whether pessimistic locks are an exceptional escalation mechanism (for one specific contended operation, say) or part of the normal update path, and write that decision down on the entity itself.

// Decide and document the policy on the entity itself.
@Entity
public class Order {

    @Id @GeneratedValue
    private Long id;

    // Concurrency policy: optimistic. Pessimistic locks are allowed
    // only via OrderRepository.findByIdForUpdate for the close-order path.
    @Version
    private long version;

    // ...
}

The reconciliation is rarely fun, but it is finite. The alternative, leaving both strategies in place and hoping, is not.

Pattern 5: Hibernate Flush Order Surprises

The last pattern is the most Hibernate-specific. By default, Hibernate flushes statements at the end of a transaction (or at query boundaries, depending on FlushMode), and the order it chooses for those statements is not the order in which you wrote them in your code. With hibernate.order_inserts=false (the default), Hibernate may flush inserts in a different order across two sessions. That alone is enough to produce a deadlock when two sessions are inserting into the same tables in parallel.

Two specific incidents from real systems:

  • A saveAll of a few hundred entities of two types (Header and Detail, with an FK from Detail to Header) deadlocks under load. Diagnosis: Hibernate is interleaving header and detail inserts; the FK constraint check inside one transaction is waiting on a header row another transaction has not yet committed.
  • A bulk reconciliation job updates rows in a hash-partitioned table. Two workers process disjoint partitions, but their statements share index pages, and the gap-locking behavior of MySQL InnoDB produces a cycle.

The first incident is fixed by the same property block as Pattern 2: order_inserts=true, order_updates=true. The second often requires changing the index strategy itself (adding a covering index, or in extreme cases switching the isolation level to READ_COMMITTED for that specific operation to avoid gap locks).

// Per-method isolation override; use sparingly and document why.
@Transactional(isolation = Isolation.READ_COMMITTED)
public void reconcilePartition(int partitionId) {
    // ...
}

Lesson. Hibernate’s default flush order is an implementation detail. When you depend on it implicitly, a Hibernate upgrade or a small entity-graph change can flip the order and produce a regression. Set order_inserts and order_updates to true as a baseline. Treat it as posture, not optimization.

Building a Regression Test You Actually Trust

A deadlock that has happened once will happen again. The most expensive thing you can do after fixing one is to ship the fix without a regression test, then watch the same deadlock recur six months later because somebody refactored the code path.

The reason teams do not write deadlock tests is that they look hard to write. They are not. They just need Testcontainers and two threads.

@Testcontainers
@SpringBootTest
class CustomerMergeDeadlockTest {

    @Container
    static PostgreSQLContainer<?> postgres = new PostgreSQLContainer<>("postgres:16");

    @DynamicPropertySource
    static void datasource(DynamicPropertyRegistry r) {
        r.add("spring.datasource.url", postgres::getJdbcUrl);
        r.add("spring.datasource.username", postgres::getUsername);
        r.add("spring.datasource.password", postgres::getPassword);
    }

    @Autowired CustomerMergeService merge;
    @Autowired CustomerRepository customers;

    @Test
    void concurrent_merges_in_opposite_order_must_not_deadlock() throws Exception {
        long a = customers.save(new Customer("A")).getId();
        long b = customers.save(new Customer("B")).getId();

        ExecutorService pool = Executors.newFixedThreadPool(2);
        CountDownLatch start = new CountDownLatch(1);

        // Each task blocks on the latch, so they really start together.
        Callable<Void> ab = () -> { start.await(); merge.merge(a, b); return null; };
        Callable<Void> ba = () -> { start.await(); merge.merge(b, a); return null; };

        Future<Void> f1 = pool.submit(ab);
        Future<Void> f2 = pool.submit(ba);
        start.countDown();

        Throwable t1 = catchThrowable(() -> f1.get(10, SECONDS));
        Throwable t2 = catchThrowable(() -> f2.get(10, SECONDS));
        pool.shutdownNow();

        // The fix is specifically about deadlocks. We assert that no thread
        // failed with a deadlock-class exception. Other failures (e.g. one
        // thread losing the race and finding the entity already merged) are
        // expected and should be asserted separately according to the business
        // semantics of merge().
        assertThat(Stream.of(t1, t2)
                .filter(Objects::nonNull)
                .map(Throwables::getRootCause))
            .noneMatch(ex -> ex instanceof CannotAcquireLockException
                          || ex instanceof PessimisticLockingFailureException);
    }
}

The test is valuable for two reasons. It runs against the real database engine, since Testcontainers gives you a throwaway PostgreSQL and the deadlock detection logic you are testing is the engine’s, not a mock. And the CountDownLatch ensures the threads start at the same instant. Without it, one thread routinely finishes before the other starts, and the test passes for the wrong reason.

When you write this test before the fix, it should fail (or be flaky, which is the same thing). When you write it after, it should pass reliably. Pin it to the CI pipeline and let it die loudly if anyone reintroduces the regression.

A Word About Retries

A pragmatic deadlock strategy includes retries, but retries are not a substitute for fixing the underlying pattern. Spring Retry composes cleanly with Spring’s transaction management:

@Retryable(
    retryFor = {
        CannotAcquireLockException.class,
        PessimisticLockingFailureException.class
    },
    maxAttempts = 3,
    backoff = @Backoff(delay = 50, multiplier = 2.0, random = true)
)
@Transactional
public void closeOrder(long orderId) {
    // ...
}

@Recover
public void recover(DataAccessException ex, long orderId) {
    log.warn("close-order gave up after retries for order {}", orderId, ex);
    // surface to monitoring; do not silently swallow
}

A few things matter in that snippet. Target the specific exception types that your stack actually produces, and verify them with an integration test, since the mapping varies across drivers, JPA providers, and Spring versions. Resist the temptation to retry on the broad TransientDataAccessException: that family includes connection-acquisition and timeout failures whose root causes you do not want to mask behind a retry loop. The random = true jitter on the backoff matters too. Without it, two retrying transactions tend to re-collide on the same tick. And the @Recover method must surface the failure to a metric, a dead-letter queue, or a human. Never silently swallow it. A retry that always recovers without anyone noticing is how a deadlock spike becomes an outage.

The retry annotation goes on a method that is the transaction boundary, not inside it. You cannot retry from inside the same transaction, because the transaction is already poisoned. If your @Transactional and @Retryable are on the same method, Spring’s proxy ordering must put the retry advice outside the transaction advice. Modern Spring Boot gets this right by default, but the ordering has historically required @Order adjustments in some configurations. Verify it for your version with a deliberate failing test.

The Architectural Takeaway: Discipline Beats Cleverness

Across these five patterns, the common thread is not “use this annotation” or “tune that property”. It is a small set of architectural disciplines that, applied consistently, eliminate most deadlocks before they ever reach production:

  1. Order locks deterministically. When a transaction touches multiple rows of the same table, sort by primary key before acquiring write locks.
  2. Keep transactions short. No HTTP calls, message-broker publishes, or file I/O inside a transaction. If you absolutely must, set a hard timeout and treat exceeding it as a failure mode.
  3. Get hot rows out of the parallel hot path. Counters, “last update” rows, and audit metadata that every transaction touches do not belong in the per-record transaction. Aggregate them asynchronously.
  4. Pick one locking strategy per entity. Either optimistic with @Version or pessimistic with @Lock, never both by accident. Document the choice on the entity.
  5. Make Hibernate’s flush order deterministic. order_inserts=true and order_updates=true are a sensible baseline for batch-heavy systems and prevent a class of incidents. Verify them against your own entity graph and batch size, not by faith.

None of these is a clever trick. All of them are habits. The teams that do not have 03:14 deadlock pages are the ones that internalised these habits years ago and now apply them without thinking.

The 3 a.m. deadlock is rarely a story about the database doing something exotic. It is almost always a story about the application asking the database to do something that looks fine in isolation and produces a cycle in concert. The database is not the antagonist of the story. It is the witness, and if you read the lock graph carefully, it will tell you exactly which line of your code put the cycle there.

Sleep well.


Want to Dive Deeper?

  • PostgreSQL documentation, Explicit Locking and pg_locks. Authoritative reference for lock modes and the catalog views you need during incident response.
  • MySQL Reference Manual, InnoDB Locking and SHOW ENGINE INNODB STATUS. The “Latest Detected Deadlock” section is your single most important production diagnostic on MySQL.
  • Hibernate ORM User Guide, Locking, Flushing, and Batch Operations. The chapters on flush ordering and batched DML are short and worth re-reading once a year.
  • Spring Framework Reference, Transaction Management. Pay particular attention to the section on isolation levels, propagation, and how SQLExceptionTranslator maps vendor codes to Spring’s DataAccessException hierarchy.
  • Adelina Simion, “No Deadlocks in MongoDB: Atomic Documents and Retries with Spring Data MongoDB” (JAVAPRO). The complementary view from the document-database side, worth reading alongside this article to see where the trade-offs differ.

This article is part of the JAVAPRO magazine issue:

Autonomous Java

Explore how modern Java is evolving beyond frameworks and APIs toward intelligent, highly automated software systems. Discover why sustainable engineering, maintainable architectures, automation, semantic search, AI agents, and runtime optimization are becoming the foundation for the next generation of enterprise applications.

Discover the edition →

Total
0
Shares
Previous Post

Java 26 Agentic Microservices: Cloud Performance Re-imagined for FinTech

Next Post

IBM Bob: Try AI-Powered Java Development Free for 30 Days

Related Posts

Building MCP Tools (for AI Agents) using Spring AI

Introduction The innovation of AI Agents and Agentic AI systems has revolutionized the adoption of Generative AI. Agents…
Read More