Video in progress

A query sent by Hibernate takes 2 seconds in the application, but when you run the same SQL by hand in psql it takes 20 ms. How do you analyze it?

The difference is usually not in the SQL but in the conditions: bind parameter types and the generic plan, an implicit type conversion killing the index, the fetch size, or the time not being in the SQL at all but in turning the result into entities. I measure each one separately.

📖 Answer

The first step is to find out where the time goes. Hibernate statistics or a tracing span show the SQL execution time and the result reading time separately. If the SQL takes 20 ms and the total is 2 seconds, the problem is not in the database.

If the SQL itself is slow, my suspects are:

Parameter type. The column is varchar, but the parameter went out from Java with a different type (for example because of the stringtype setting or a wrong mapping). The database converts the column and the index is not used. In psql you typed a literal, so the index worked.

Generic plan. The PostgreSQL JDBC driver does a server-side prepare after executing a prepared statement 5 times, and the database may switch to a generic plan from the 6th call. If the data distribution is uneven (status = 'NEW' is 0.1%, 'DONE' is 99%), the generic plan is bad. To check: explain (analyze) execute ... or try it with plan_cache_mode = force_custom_plan.

To see it, I turn on the auto_explain module, which writes the plan of the real query sent by the application to the log:

set auto_explain.log_min_duration = '500ms';
set auto_explain.log_analyze = on;

If the SQL is fast but the total is slow:

  • the result is 50 thousand rows and the fetch size is small: lots of network round-trips; use hibernate.jdbc.fetch_size or a query hint;
  • an entity per row, a snapshot, and extra queries for EAGER associations;
  • dirty checking after hydration: 50 thousand entities get compared at flush.

In this case the fix is almost always a projection and pagination. What matters is to measure each step instead of guessing.