Session 2 — Profiling & Debugging
Session 2Profiling & Debugging · 3h

Finding where the slowness is, instead of guessing

Today you will learn to listen to your application: measure what it does with metrics, follow a request from end to end, see where the processor's time and the memory go, and find the most common bugs in Spring applications. No magic, just tools that ship with Java itself.

  • Expose metrics and health with the Actuator and Micrometer
  • Follow requests with distributed tracing
  • Record and read profiles with JFR and flame graphs
  • Understand the heap, the Garbage Collector and heap dumps
  • Debug locally, remotely and inside Spring
  • Diagnose N+1, exhausted pools, deadlocks and memory leaks

Don't guess: measure

When an application is slow, the temptation is to immediately change code «that looks slow». Almost always, the culprit is somewhere else. Studies and the experience of large teams say the same thing: developers are rarely right when they try to guess the bottleneck.

A bottleneck is the point that limits the speed of the whole system, just as the neck of a bottle limits how fast the water comes out, however big the bottle is.

The doctor doesn't operate before running tests

If you go to the doctor in pain, they don't operate straight away. First they take your temperature and blood pressure (metrics), ask what happened (logs), order a CT scan to look inside (profiling) and only then decide. Software is the same.

The three pillars of observability

Observability is the ability to understand what is going on inside a system just by looking at what it emits to the outside.

📈 MetricsNumbers over timeRequests per second, response time, memory used. Light and cheap. They tell you that something is wrong.
📜 LogsEvent messages«Order 981 created», «Error connecting to payments». They tell you what happened.
🧵 TracesThe path of a requestWhich services and queries it went through and how much time it spent in each. They tell you where the time went.

What you will see in this session

0:00–0:40Module 2.1 · Observability with Spring Boot
0:40–1:40Module 2.2 · Profiling the JVM (+ lab)
1:40–1:50Break ☕
1:50–2:30Module 2.3 · Debugging Spring applications
2:30–3:00Module 2.4 · Diagnosing common problems (+ lab)

Spring Boot Actuator: the dashboard

The Actuator adds a set of addresses (endpoints) to your application that show its internal state: whether it is healthy, how much memory it uses, which threads are running, what configuration it has. It is like a car's dashboard.

Enabling it

The endpoints you will use most

EndpointWhat it is for
/actuator/healthIs it alive? Does the database respond? Does the disk have space? Used by Kubernetes and load balancers.
/actuator/metricsList of all metrics; /metrics/{name} shows one in detail.
/actuator/prometheusThe same metrics in the format Prometheus collects.
/actuator/loggersView and change the log level at runtime, without restarting.
/actuator/threaddumpA snapshot of all threads: what each one is doing at this instant.
/actuator/heapdumpDownloads a file with the application's entire memory. Heavy!
/actuator/conditions, /beansWhich auto-configurations were applied and which beans exist.

Try it. Notice that you can change the log level with a POST, and the next request already shows different detail.

Security first

The heapdump may contain passwords and personal data that were in memory. The env endpoint shows configuration. Never expose the Actuator to the internet: use a separate management port, protect it with Spring Security (role ACTUATOR) and expose only what is needed.

Metrics with Micrometer

Micrometer is to metrics what SLF4J is to logs: a facade. You write the code once and it exports to Prometheus, Datadog, New Relic, CloudWatch… Spring Boot already measures loads of things by itself (HTTP requests, JVM, pools, caches). You add the business metrics.

The three types you need to know

CounterOnly goes upLike an odometer. «Orders created», «failed payments».
GaugeGoes up and downLike the fuel gauge. «Items in the queue», «users online».
TimerMeasures durationsCounts how many times and how long. «Time to calculate shipping».

Shortcuts with annotations

For @Timed to work outside controllers, register a TimedAspect bean; for @Observed, an ObservedAspect (both need spring-boot-starter-aop).

Tags: watch out for cardinality

You can add labels (tags) to metrics, such as method=card. But never use values with thousands of possibilities (customer id, email, full URL): each different value creates a new series and the metrics system runs out of memory. This is called cardinality explosion.

Seeing everything on a dashboard: Prometheus + Grafana

Your appexposes /actuator/prometheus
→every 15 s
Prometheuscollects and stores the time series
→
Grafanadraws charts and fires alerts

In Grafana, import the public «JVM (Micrometer)» dashboard (id 4701) and you have memory, GC, threads and HTTP requests in 2 minutes.

Distributed tracing: following a request from end to end

In an architecture with several services, a single user click may go through five applications. If it takes 3 seconds, where was the time lost? Tracing answers that.

Trace
The complete journey of a request. It has a unique identifier (traceId).
Span
One leg of that journey: an HTTP call, an SQL query. It has a start, a duration and a spanId.
Propagation
The traceId travels in the HTTP headers (traceparent) from service to service.

This is how a trace looks in a tool such as Jaeger, Zipkin or Grafana Tempo:

GET /checkout
shop-api · 1240 ms
SELECT cart
18 ms
POST /stock
stock · 120 ms
POST /payment
payments · 965 ms ⚠
↳ external bank
bank-gateway · 910 ms
INSERT order
22 ms
Of 1240 ms, 910 ms were spent waiting for the bank. Optimising the SQL would be pointless.

Configuring it in Spring Boot 3

Spring automatically instruments incoming HTTP requests, calls made with RestClient/WebClient (as long as they are built from the builder injected by Spring), JDBC (with the datasource-micrometer library) and methods annotated with @Observed.

Logs linked to traces

With the pattern above, every log line carries the traceId. When a customer complains, you search for the traceId and see every line of that request, across all services.

The MDC and threads

The traceId lives in the MDC, which is attached to the thread. Remember session 1? With @Async you need the ContextPropagatingTaskDecorator, otherwise the logs from the other thread show up without a traceId.

Metrics tell you there is slowness; logs tell you what happened. The trace shows each leg of the request with its duration, so it points straight at where the time is.

Profiling: an X-ray of the code

Metrics and traces tell you that the /orders endpoint is slow. But which method, which line? For that you use a profiler: a tool that watches the running application and records where the processor spends its time and who creates objects in memory.

Sampling vs. instrumentation

SamplingInstrumentation
How it worksSeveral times per second, it takes a «snapshot» of what each thread is doing.Inserts measuring code at the entry and exit of every method.
AnalogyPeeking into the kitchen every 10 seconds and noting what each cook is doing.Putting a stopwatch on every task of every cook.
Overhead on the applicationLow (1–2%). Safe in production.High. Distorts the results. Development only.
PrecisionStatistical: great for finding the «big consumers».Exact, including call counts.

The tools

Java Flight Recorder (JFR)A recorder built into the JVM, free. Records CPU, memory, GC, locks, I/O, exceptions. Designed for production.
JDK Mission Control (JMC)An application to open and analyse .jfr files. It has an «Automated Analysis» that points out problems.
async-profilerA very precise open-source profiler, famous for its flame graphs. It also sees native and kernel code.
VisualVMA simple interface to watch CPU, memory and threads live, and take dumps.
IntelliJ ProfilerBuilt into the IDE (uses JFR and async-profiler). Right-click → Profile. The easiest way to start.

Recording with JFR

settings=profile collects more detail (at a slightly higher cost) than the default profile, which is the one meant for continuous recording in production.

Reading a flame graph

A flame graph shows thousands of samples in a single picture. The reading rules are few:

  • Each rectangle is a method. At the bottom is the caller; above it, the callee.
  • The width is the percentage of samples in which the method appeared. Wider = more CPU time.
  • The colour has no special meaning (it just helps tell them apart). The horizontal axis is not time: methods are in alphabetical order.
  • Look for wide «plateaus» at the top: that is where the processor is really busy (the self time).

Click a rectangle to zoom in. Click the base to go back.

What this profile reveals

Almost half the time is in Order.getCustomer → Hibernate lazy loading, called inside a loop. It is the N+1 problem, which you will solve in module 2.4. And notice the String.format inside the price calculation: small but easy to eliminate.

Memory: the heap and the Garbage Collector

Every new creates an object in an area of memory called the heap. In Java you don't free memory by hand: the Garbage Collector (GC) finds objects that nobody uses any more and frees the space.

The waiter who clears the plates

The customers (your code) keep ordering plates (objects). The GC goes round the tables and takes away the plates nobody is using any more. If nobody ever lets go of their plates, the tables fill up and the restaurant grinds to a halt: that is the OutOfMemoryError.

Generations: most objects die young

Young generation (Eden + Survivor)new objects · collected often and quickly
↓ survived several collections
Old generationlong-lived objects (caches, singletons) · collected rarely
outside the heap
Metaspace, thread stacks, native memoryloaded classes, direct buffers

Which Garbage Collector to choose?

GCCharacteristicWhen to use it
G1 (default)A balance between throughput and short pauses (target: 200 ms).Most Spring applications. Don't touch it without a reason.
ZGC (generational)Pauses under 1 ms, even with huge heaps. Uses a bit more CPU.Latency-sensitive APIs (tight p99s), large heaps. -XX:+UseZGC
ParallelMaximum throughput, longer pauses.Batch processing, where pauses don't matter.
SerialOne thread, simple.Tiny containers (1 CPU, little memory).

Watch the heap breathe (and suffocate)

A healthy heap makes a «sawtooth»: it fills up, the GC cleans it, it goes back to the baseline. With a memory leak, the baseline keeps rising, GCs become more and more frequent and, in the end, the application dies.

Reading GC logs

It reads like this: 301M->118M(512M) 6.214ms = before the collection 301 MB were in use, afterwards 118 MB remained, the heap has 512 MB and the pause lasted 6 ms. The last line is an alarm signal: a Full GC of 812 ms that freed only 27 MB. Almost all the memory is held.

Tools to read GC logs

GCeasy and GCViewer turn gc.log into charts. In production, Micrometer's jvm.gc.pause and jvm.memory.used metrics give you the same in Grafana.

Heap dumps and Eclipse MAT

A heap dump is a snapshot of every object in memory at one instant. You open the .hprof file in Eclipse Memory Analyzer (MAT) to find out who is taking up the memory.

Shallow size
Memory taken by the object itself (its fields).
Retained size
Memory that would be freed if that object disappeared: itself plus everything that only it holds. This is the number that matters.
Dominator tree
A list of the objects that «hold» the most memory. The first place to look.
GC root
A starting point that keeps objects alive: static variables, active threads, local variables.
Dominator tree (example)ShallowRetained%
com.shop.ReportService24 B312 MB71%
↳ java.util.HashMap (field reportCache)48 B312 MB71%
  ↳ 184,220 × com.shop.Report32 B each~1.7 KB each
org.apache.catalina…StandardManager96 B21 MB5%

MAT's «Leak Suspects» report would reach the same conclusion: a HashMap used as a cache, with no limit, inside a singleton.

Lab 2: recording and analysing a profile under load

Steps lab · 20 min

  1. Start the course application with -XX:StartFlightRecording=settings=profile,filename=lab.jfr,dumponexit=true.
  2. Generate load for 60 s. For now a loop in the terminal is enough (in session 3 you will use Gatling):
  3. Stop the application and open lab.jfr in JDK Mission Control (or drag it into IntelliJ).
  4. In Method Profiling, find the method with the most samples. In Memory → Allocations, find who creates the most objects.
  5. In Automated Analysis, note the warnings in red.
  6. Write down a hypothesis: «The bottleneck is X because Y». You will confirm it in module 2.4.
Alternative with async-profiler

asprof -d 30 -f flame.html 4711 records 30 seconds and generates an interactive HTML flame graph. With -e alloc it shows allocations instead of CPU; with -e wall it includes time spent waiting (useful for I/O).

Debugging: stopping time and looking inside

A debugger lets you pause the program at a line of your choice and inspect every variable, moving forward one line at a time. It is the most powerful tool for understanding logic errors.

The essential commands

ActionIntelliJ (Win/Linux)What it does
Breakpointclick in the gutterThe program stops when it reaches this line.
Step OverF8Runs the line and stops at the next one.
Step IntoF7Goes inside the method called on the line.
Step OutShift+F8Finishes the current method and returns to the caller.
ResumeF9Continues until the next breakpoint.
Evaluate ExpressionAlt+F8Runs any Java expression in the current context.

Smart breakpoints

ConditionalRight-click the breakpoint → Condition: order.getId() == 981. It only stops in the case you care about, even in a loop of 10,000 iterations.
LogpointTurn off «Suspend» and turn on «Evaluate and log». Writes to the log without stopping the program, and without changing the code.
ExceptionIn View Breakpoints → + → Java Exception Breakpoint. Stops at the exact moment the exception is thrown.
WatchesExpressions that stay visible as you step forward.

Remote debugging (server or Docker)

You can attach your IDE's debugger to a JVM running on another machine or in a container, through the JDWP protocol.

Never in open production

Anyone who connects to the JDWP port can run any code on the server. Use it only in development, or through an SSH tunnel. And remember: at a breakpoint, all threads of that request stop, and timeouts fire. On shared servers, prefer logpoints.

Spring-specific debugging

«Why wasn't this bean created?»

Here Spring explains that the Redis cache was not configured because it found no connection to Redis (the dependency or the configuration is missing). The same report is available at /actuator/conditions.

«Why didn't my transaction roll back?»

SymptomMost likely cause
@Transactional seems to be ignoredSelf-invocation (this.method()), a private method or a class not managed by Spring. Just like @Async: it's a proxy.
It doesn't roll backA checked exception was thrown (by default rollback only happens with RuntimeException) or the exception was caught in a catch. Use rollbackFor = Exception.class.
LazyInitializationExceptionYou accessed a lazy association after the transaction closed.

Strategic logging

Changing the log level at runtime (with the Actuator) is a debugging tool in production: you turn on DEBUG for a package for 5 minutes, collect what you need and go back to INFO.

Logs have a cost

Logging SQL with parameters in production fills disks and can expose personal data. And concatenating text in a disabled log still burns CPU: write log.debug("Order {}", id) and not log.debug("Order " + id).

Classic problem 1: the database N+1

You ask for the list of 100 orders (1 query). Then, to show each customer's name, Hibernate runs one query per order (N = 100 queries). Total: N+1 = 101 trips to the database, when one would do.

Going to the supermarket 101 times

You have a shopping list with 100 items. Instead of grabbing a trolley and bringing everything at once, you go to the supermarket, bring back one item, go home, and repeat 100 times. Each trip is quick, but the total is enormous.

Try the different solutions and look at the generated SQL:

SolutionAdvantageCaveat
JOIN FETCH / @EntityGraphA single query.Don't join two collections (@OneToMany) in the same fetch: Cartesian product. With pagination, Hibernate may paginate in memory.
@BatchSizeSimple, works with pagination and collections.Still runs a few queries.
DTO projectionsBrings only what's needed. Usually the fastest for listings.The objects are not entities (they can't be modified and saved).
Catching N+1 automatically

Turn on hibernate.generate_statistics in development and look at «JDBC statements executed». In tests, libraries such as datasource-proxy or Hypersistence Utils let you write assertSelectCount(1) so that an N+1 breaks the build.

Classic problem 2: the exhausted connection pool

Opening a database connection is slow (authentication, network). That's why Spring Boot uses a connection pool, HikariCP, which keeps a fixed number of connections open and lends them to requests. By default there are 10.

The car park

The pool is a car park with 10 spaces. Each request parks while it talks to the database. If 100 cars arrive and each one stays parked for a long time (a slow query, or a transaction that includes an HTTP call), the other 90 queue up. If they wait longer than the connectionTimeout (30 s by default), they give up with an error.

Typical causes and solutions

CauseSolution
Slow queries (no index, N+1)Fix the queries. They release the connection sooner.
HTTP calls inside @TransactionalMake the external call outside the transaction. The connection stays held while you wait for the other service!
spring.jpa.open-in-view=true (default)Keeps the connection until the HTTP response is written. Turn it off with false.
Connections never returned (leak)leak-detection-threshold shows in the log the stack trace of whoever borrowed it.
Virtual threads with no limitThousands of requests compete for 10 connections. Limit concurrency (semaphore, bulkhead) or adjust the pool.
A bigger pool is not always better

The database has limited cores and disks. The starting formula suggested by the HikariCP team is connections ≈ (database cores × 2) + disks. A pool of 200 connections usually makes everything slower. You will measure this in session 3.

Monitor it with the metrics hikaricp.connections.active, hikaricp.connections.pending and hikaricp.connections.acquire. If pending is always above zero, there is a queue at the car park.

Classic problem 3: stuck threads

The application stops responding, but CPU is at 0%. The threads are all waiting for something. A thread dump shows exactly what.

Take three, not one

Take 3 dumps 5 to 10 seconds apart. A thread that shows up in the same place in all three really is stuck; in a single dump, it might just be passing through.

Thread states

StateMeaning
RUNNABLEWorking (or reading from the network, which also shows up like this).
BLOCKEDWaiting to enter a synchronized block that another thread holds.
WAITING / TIMED_WAITINGWaiting for a signal, a join, a connection from the pool, a sleep.

A deadlock caught red-handed

The JVM detects synchronized deadlocks by itself and tells you the two threads and the line. The fix: always lock the accounts in the same order (for example, lowest id first).

Pinned virtual threads

In Java 21–23, look for the JFR event jdk.VirtualThreadPinned or start with -Djdk.tracePinnedThreads=full. If many show up, there are synchronized blocks with waits inside them cancelling out the benefit of virtual threads.

Classic problem 4: memory leaks in Java

The GC only frees objects that nobody can reach. A memory leak in Java is almost always an object that remains reachable even though you no longer need it: the GC can't take it away.

Fix: use @Cacheable with Caffeine and maximumSize (session 1). A field in a singleton lives as long as the application lives.

Tomcat's threads are reused and live forever. Whatever you put in a ThreadLocal and don't remove stays attached to the thread, and may even leak into another user's request! Fix: try { … } finally { current.remove(); }, in a filter.

Each registration keeps a reference to the object, which will never be collected. Fix: remove the listener when it's no longer needed, or use Spring events (ApplicationEventPublisher and @EventListener), which manage the lifecycle for you.

Lab 3: diagnose and fix

Steps lab · 20 min

The course project has two defects introduced on purpose: an N+1 in GET /orders and a leak in GET /reports?filter=….

  1. Start it with -Xmx256m -XX:+HeapDumpOnOutOfMemoryError and Hibernate statistics turned on.
  2. Call /orders once and count the queries in the log. Fix it with @EntityGraph and confirm it drops to 1.
  3. Generate 50,000 requests to /reports with different filters (filter=$RANDOM) until it blows up.
  4. Open the .hprof in Eclipse MAT, run «Leak Suspects» and identify the guilty field.
  5. Fix it with Caffeine (maximumSize=1000), repeat the test and show in Grafana that the heap now makes a sawtooth.

Exercises

1. A business metric easy

Create a counter shop.payments with the tag result (success or failure) and increment it in the payment service.

Show solution

2. Reading a GC log medium

What do you conclude from these lines? GC(90) Pause Young 480M->470M(512M) 31ms, GC(91) Pause Young 482M->474M(512M) 34ms, GC(92) Pause Full 505M->498M(512M) 1.4s.

Show solution

Each collection frees very little (10 MB, 8 MB, 7 MB) and the level after GC is close to the maximum. The memory is almost entirely taken by live objects: either the heap is too small for the load, or (more likely, if it keeps growing over time) there is a memory leak. Next step: heap dump and Eclipse MAT.

3. A transaction that holds the connection medium

Find the problem and rewrite it:

Show solution

The database connection is held for the duration of the HTTP call. With 10 connections and 2 s payments, the maximum is 5 checkouts per second for the whole application. Split it: read the cart, charge outside a transaction and only then open a short transaction to save.

Session summary

The essentials in 10 points

  • Measure before optimising: metrics tell you that, logs tell you what, traces tell you where.
  • The Actuator exposes health, metrics, loggers and dumps. Always protect it.
  • Micrometer: Counter only goes up, Gauge goes up and down, Timer measures durations. Watch out for high-cardinality tags.
  • Micrometer Tracing + OpenTelemetry link logs and spans through the traceId.
  • Sampling profilers (JFR, async-profiler) are safe in production.
  • In a flame graph, width = time; look for wide plateaus at the top.
  • A healthy heap makes a sawtooth; a baseline that keeps rising means a leak.
  • Heap dump + Eclipse MAT: look at the retained size and the dominator tree.
  • N+1: solve it with JOIN FETCH, @EntityGraph, @BatchSize or projections.
  • Exhausted connection pool: slow queries, HTTP inside transactions, open-in-view.

Glossary

Bottleneck
The point that limits the performance of the whole system.
Observability
The ability to understand a system's internal state through its metrics, logs and traces.
Span
One leg of a trace, with a start and a duration.
Profiler
A tool that measures where CPU and memory are spent.
JFR
Java Flight Recorder, the event recorder built into the JVM.
Flame graph
A visualisation of sampled stack traces; width is proportional to time.
Heap
The area of memory where objects live.
GC
Garbage Collector: frees unreachable objects.
Retained size
Memory that would be freed if an object disappeared.
N+1
1 query for the list + 1 for each element.
Thread dump
A snapshot of the state of all threads.