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.
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.
What you will see in this session
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
| Endpoint | What it is for |
|---|---|
/actuator/health | Is it alive? Does the database respond? Does the disk have space? Used by Kubernetes and load balancers. |
/actuator/metrics | List of all metrics; /metrics/{name} shows one in detail. |
/actuator/prometheus | The same metrics in the format Prometheus collects. |
/actuator/loggers | View and change the log level at runtime, without restarting. |
/actuator/threaddump | A snapshot of all threads: what each one is doing at this instant. |
/actuator/heapdump | Downloads a file with the application's entire memory. Heavy! |
/actuator/conditions, /beans | Which 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.
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
Shortcuts with annotations
For @Timed to work outside controllers, register a TimedAspect bean; for @Observed, an ObservedAspect (both need spring-boot-starter-aop).
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
/actuator/prometheusIn 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
traceIdtravels 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:
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 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
| Sampling | Instrumentation | |
|---|---|---|
| How it works | Several times per second, it takes a «snapshot» of what each thread is doing. | Inserts measuring code at the entry and exit of every method. |
| Analogy | Peeking 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 application | Low (1–2%). Safe in production. | High. Distorts the results. Development only. |
| Precision | Statistical: great for finding the «big consumers». | Exact, including call counts. |
The tools
.jfr files. It has an «Automated Analysis» that points out problems.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.
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 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
Which Garbage Collector to choose?
| GC | Characteristic | When 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 |
| Parallel | Maximum throughput, longer pauses. | Batch processing, where pauses don't matter. |
| Serial | One 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.
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) | Shallow | Retained | % |
|---|---|---|---|
com.shop.ReportService | 24 B | 312 MB | 71% |
↳ java.util.HashMap (field reportCache) | 48 B | 312 MB | 71% |
↳ 184,220 × com.shop.Report | 32 B each | ~1.7 KB each | |
org.apache.catalina…StandardManager | 96 B | 21 MB | 5% |
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
- Start the course application with
-XX:StartFlightRecording=settings=profile,filename=lab.jfr,dumponexit=true. - Generate load for 60 s. For now a loop in the terminal is enough (in session 3 you will use Gatling):
- Stop the application and open
lab.jfrin JDK Mission Control (or drag it into IntelliJ). - In Method Profiling, find the method with the most samples. In Memory → Allocations, find who creates the most objects.
- In Automated Analysis, note the warnings in red.
- Write down a hypothesis: «The bottleneck is X because Y». You will confirm it in module 2.4.
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
| Action | IntelliJ (Win/Linux) | What it does |
|---|---|---|
| Breakpoint | click in the gutter | The program stops when it reaches this line. |
| Step Over | F8 | Runs the line and stops at the next one. |
| Step Into | F7 | Goes inside the method called on the line. |
| Step Out | Shift+F8 | Finishes the current method and returns to the caller. |
| Resume | F9 | Continues until the next breakpoint. |
| Evaluate Expression | Alt+F8 | Runs any Java expression in the current context. |
Smart breakpoints
order.getId() == 981. It only stops in the case you care about, even in a loop of 10,000 iterations.+ → Java Exception Breakpoint. Stops at the exact moment the exception is thrown.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.
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?»
| Symptom | Most likely cause |
|---|---|
@Transactional seems to be ignored | Self-invocation (this.method()), a private method or a class not managed by Spring. Just like @Async: it's a proxy. |
| It doesn't roll back | A checked exception was thrown (by default rollback only happens with RuntimeException) or the exception was caught in a catch. Use rollbackFor = Exception.class. |
LazyInitializationException | You 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.
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.
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:
| Solution | Advantage | Caveat |
|---|---|---|
JOIN FETCH / @EntityGraph | A single query. | Don't join two collections (@OneToMany) in the same fetch: Cartesian product. With pagination, Hibernate may paginate in memory. |
@BatchSize | Simple, works with pagination and collections. | Still runs a few queries. |
| DTO projections | Brings only what's needed. Usually the fastest for listings. | The objects are not entities (they can't be modified and saved). |
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 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
| Cause | Solution |
|---|---|
| Slow queries (no index, N+1) | Fix the queries. They release the connection sooner. |
HTTP calls inside @Transactional | Make 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 limit | Thousands of requests compete for 10 connections. Limit concurrency (semaphore, bulkhead) or adjust the pool. |
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 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
| State | Meaning |
|---|---|
RUNNABLE | Working (or reading from the network, which also shows up like this). |
BLOCKED | Waiting to enter a synchronized block that another thread holds. |
WAITING / TIMED_WAITING | Waiting 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).
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=….
- Start it with
-Xmx256m -XX:+HeapDumpOnOutOfMemoryErrorand Hibernate statistics turned on. - Call
/ordersonce and count the queries in the log. Fix it with@EntityGraphand confirm it drops to 1. - Generate 50,000 requests to
/reportswith different filters (filter=$RANDOM) until it blows up. - Open the
.hprofin Eclipse MAT, run «Leak Suspects» and identify the guilty field. - 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:
Counteronly goes up,Gaugegoes up and down,Timermeasures 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,@BatchSizeor 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.
Homework
Observability dashboard. Using docker compose, run Prometheus, Grafana and Jaeger (or Grafana Tempo) alongside the course application. Build a dashboard with: requests per second, p95 response time per endpoint, active and pending Hikari connections, heap used and GC pauses. Export the dashboard as JSON.
Reading: Spring Boot documentation, sections «Production-ready Features» → «Metrics» and «Tracing».
In the next session: you will put the application under real load and use this dashboard to find its limit.