Video in progress
On prod, one endpoint slows down from time to time and suspicion falls on Hibernate. How do you diagnose it?
First I isolate which part is slow: the number of SQL statements (N+1), a single slow query, connection waits, or flush/hydration. For that I use a trace (OpenTelemetry), a datasource-proxy or p6spy log, Hibernate statistics, HikariCP metrics and the database's slow query log together.
📖 Answer
"From time to time" is an important sign. Usually the cause depends on data volume or parallel load.
My order:
-
Trace. With OpenTelemetry/Micrometer tracing, the JDBC spans are visible inside the endpoint's span. 300 small selects means N+1. One 2-second select means a query/index problem. A gap between the JDBC spans means work on the Java side (hydration, dirty checking, flush).
-
The connection pool. HikariCP's
hikaricp_connections_pendingandconnection_acquiremetrics. If the waiting is high, the problem is elsewhere: connections held by a long transaction (OSIV enabled, an HTTP call inside a transaction). -
Hibernate statistics. I turn them on temporarily and log slow queries with
hibernate.session.events.log.LOG_QUERIES_SLOWER_THAN_MS=200. Session-level metrics: the number of entity loads, flushes and collection fetches. -
The database.
pg_stat_statementsfor the queries that take the most time, andEXPLAIN (ANALYZE, BUFFERS)with the exact parameters. To see Hibernate's bind parameters in the log,org.hibernate.orm.jdbc.bind=TRACE(only temporarily). -
Reproduce it. A test with Testcontainers at a prod-like data volume and a query budget assertion.
Typical findings: a big customer with many rows makes N+1 multiply; a big context is flushed before every query because of FlushMode.AUTO; many different IN lengths in the plan cache; lock waits. After the fix I leave the metric on a dashboard so that a regression is visible if it returns.
Sign up to mark studied questions and save your progress.