Video in progress
On prod, the Hibernate query plan cache has taken a large part of the heap. What could be the cause, and how do you fix it?
Usually IN lists of varying length, or values concatenated into the query text, so a new query text is generated every time and lands in the cache. Writing with parameters, turning on in_clause_parameter_padding and limiting the cache size all help.
📖 Answer
Hibernate parses each JPQL/HQL string and caches the result (SQM and SQL). The key is the query text. If there are unboundedly many texts, the cache fills up.
Classic sources:
IN lists. where id in :ids is one text, but in SQL it is in (?, ?, ?): a different SQL depending on the number of parameters. Every size from 1 to 1000 means 1000 plans, and it also fills the database's prepared statement cache. The fix:
spring:
jpa:
properties:
hibernate.query.in_clause_parameter_padding: true
Now the number of parameters is rounded up to a power of 2 (5 → 8, 13 → 16), repeating the last value. The number of variants drops from 1000 to 10.
Concatenation:
// bad: a new cache entry for every userId, and a SQL injection risk
em.createQuery("select u from User u where u.id = " + userId);
I catch this kind of code with static analysis (SpotBugs, a Sonar rule).
Dynamic Criteria queries also produce a separate plan for each combination of filters. This is usually bounded, but you need to watch it on search screens with lots of optional filters.
You can cap the cache size with hibernate.query.plan_cache_max_size, but that treats the symptom. To find the real cause, I open the heap dump in MAT and look at the keys in the cache: thousands of strings with the same template usually jump out right away.
On the PostgreSQL side, instead of very large IN lists, = any(?) with an array parameter is better: one SQL text, any length.
Sign up to mark studied questions and save your progress.