Step‑by‑step guide to detecting and visualizing database deadlocks in Java Spring Boot with APM traces

Technician working on the design or analysis of mechanical components in front of several monitors at a computer station within an industrial plant.
Learn how to instrument a Spring Boot application, capture deadlock events with APM traces, and build dashboards that surface critical DB contention quickly.

Introduction

Database deadlocks are a silent threat in high‑throughput Java applications. When two or more transactions lock resources in a circular chain, the database aborts one transaction, but the symptom often appears as a spike in response time or an unexplained error. This guide walks you through building a Spring Boot project that captures deadlock events with APM traces, visualizes them on a dashboard, and shortens mean time to detection (MTTD). By the end you will have a reproducible codebase, a configured APM agent, and a set of Grafana panels that surface deadlocks as soon as they occur.

1. Project Setup – From Idea to Repository

1.1 Define the scope

  • Detect deadlock events on a PostgreSQL database.
  • Use Lescopr APM to collect trace data.
  • Visualize results in Grafana.

1.2 Create the starter project

mkdir spring-deadlock-demo && cd $_
curl -s https://start.spring.io/starter.zip \
  -d dependencies=web,data-jpa,postgresql,lombok \
  -d name=DeadlockDemo -d packageName=com.example.deadlockdemo \
  -o demo.zip
unzip demo.zip && rm demo.zip

1.3 Add Lescopr APM dependency

Edit pom.xml and insert:

<dependency>
    <groupId>com.lescopr</groupId>
    <artifactId>lescopr-apm-spring-boot-starter</artifactId>
    <version>1.4.0</version>
</dependency>

Commit the initial code to a Git repository and push to your preferred remote. This milestone establishes a reproducible baseline for the rest of the tutorial.

2. Implementing a Contended Transaction

2.1 Model a simple inventory table

@Entity
public class Item {
    @Id @GeneratedValue Long id;
    String name;
    int quantity;
}

2.2 Service that creates a lock cycle

@Service
@RequiredArgsConstructor
public class InventoryService {
    private final ItemRepository repo;
    @Transactional
    public void transfer(Long fromId, Long toId, int amount) {
        Item from = repo.findById(fromId).orElseThrow();
        Item to = repo.findById(toId).orElseThrow();
        from.setQuantity(from.getQuantity() - amount);
        // Intentional pause to increase lock window
        try { Thread.sleep(2000); } catch (InterruptedException ignored) {}
        to.setQuantity(to.getQuantity() + amount);
        repo.saveAll(List.of(from, to));
    }
}

2.3 Controller that triggers concurrent transfers

@RestController
@RequiredArgsConstructor
public class DemoController {
    private final InventoryService service;
    @PostMapping("/deadlock")
    public void trigger() {
        ExecutorService exec = Executors.newFixedThreadPool(2);
        exec.submit(() -> service.transfer(1L, 2L, 10));
        exec.submit(() -> service.transfer(2L, 1L, 5));
        exec.shutdown();
    }
}

Running /deadlock creates two overlapping transactions that lock the same rows in opposite order, reproducing a classic deadlock scenario.

3. Configuring Lescopr APM for Deadlock Tracing

3.1 Agent initialization

Add application.yml entries:

lescopr:
  apm:
    enabled: true
    service-name: deadlock-demo
    capture-sql: true
    capture-lock-wait: true   # crucial for deadlock detection

3.2 Enabling JDBC instrumentation

The Lescopr agent automatically wraps the DataSource. No extra code is required, but you must expose the APM UI port:

server:
  port: 8080
management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics
lescopr:
  apm:
    exporter:
      endpoint: http://localhost:8200/api/traces

3.3 Verifying trace collection

Start the application and invoke the endpoint twice. In the Lescopr UI you should see two spans labeled SQL SELECT followed by a span Lock wait. The deadlock abort appears as an error tag on the transaction.

4. Visualizing Deadlocks on a Dashboard

4.1 Exporting metrics to Prometheus

Add the Prometheus exporter configuration:

lescopr:
  apm:
    exporter:
      type: prometheus
      endpoint: http://localhost:9090/metrics

Run a local Prometheus instance and scrape http://localhost:9090/metrics.

4.2 Building Grafana panels

  1. Create a new dashboard titled Database Deadlocks.
  2. Add a Stat panel with the query:
    sum(increase(lescopr_apm_lock_wait_total[1m]))
    
    This shows the number of lock‑wait events per minute.
  3. Add a Table panel to list recent error transactions:
    lescopr_apm_transaction_errors{service="deadlock-demo"}
    
  4. Set an alert rule: if lock‑wait events exceed 5 in a minute, trigger a PagerDuty notification.

4.3 Interpreting the visualization

When a deadlock occurs, the Stat panel spikes, and the Table panel lists the offending SQL statements with their stack traces. This immediate feedback reduces MTTD from minutes to seconds, allowing SRE teams to intervene before user‑visible latency degrades.

5. Refining the Observability Pipeline

5.1 Sampling strategy

Capturing every lock‑wait event can add ~2 % overhead on a busy database. To mitigate impact, enable sampling during peak traffic and switch to full capture only when an alert fires.

5.2 Correlating with application logs

Configure Lescopr to forward trace IDs to your logging framework:

logging.pattern.level=%X{traceId} %p

Now each log line can be linked back to the exact trace that recorded the deadlock, providing end‑to‑end context.

5.3 Extending to other databases

The same instrumentation works with MySQL, MariaDB, and Oracle. Adjust the capture-lock-wait flag according to the vendor‑specific lock‑wait metrics.

Conclusion

By following this step‑by‑step project you have built a Spring Boot service that deliberately creates a deadlock, instrumented it with Lescopr APM, and visualized the contention on a Grafana dashboard. The resulting observability stack shortens mean time to detection and gives your SRE team actionable insights.

To go further, Lescopr's documentation covers step‑by‑step setup.