Video in progress
An endpoint responds in 2 seconds. How do you find out whether the time goes in Spring, in Hibernate or in the database?
First I split the time into layers with tracing or metrics: the HTTP request, each SQL statement, external calls. Then I check separately the number of queries (N+1), the plan of the slow SQL (EXPLAIN ANALYZE) and the JVM side (GC, pool wait). I don't optimize on guesses.
📖 Answer
My order:
-
Trace. If Micrometer Tracing + Zipkin/Tempo is hooked up, the trace of a single slow request tells you a lot: the HTTP span is 2 s, and inside it 300 JDBC spans of 4 ms each, which is N+1. Or one 1.8 s SQL, so the query itself is slow. Or an external HTTP span. JDBC spans need separate instrumentation (for example, datasource-micrometer).
-
If there is no trace, the number of queries. Locally or on staging:
spring.jpa.properties.hibernate.generate_statistics: true
At the end of the session the log shows how many JDBC statements were executed and how much time they took. 200 statements for one page, and you've found the problem.
-
Slow SQL. I grab the query with its parameters (
org.hibernate.orm.jdbc.bind=traceor p6spy) and runexplain (analyze, buffers)in the database. Most often: a missing index, a column filtered inside a function, a type mismatch. On prodpg_stat_statementsshows the heaviest queries. -
Waiting.
hikaricp.connections.pendingandhikaricp.connections.acquire: the SQL is fast, but there is a 1.5 s queue to get a connection. The problem is the pool size or long transactions. -
JVM. GC pauses (
jvm.gc.pause), CPU throttling in the container, serializing a large JSON. Here async-profiler or JFR's wall-clock profile shows which method the time goes in.
In my experience the causes usually come in this order: N+1, a missing index, an external HTTP call inside a transaction, connection pool wait. After every fix I measure again with the same trace or a load test: not "seems faster", but with a number.
Sign up to mark studied questions and save your progress.