Video in progress
If you turn on Hibernate's query cache, when does it do harm instead of good?
The query cache stores only the result ids, and any write to one of the tables in the query invalidates the whole result. On frequently changing tables the hit rate is low, and invalidation overhead and extra loads by id are added on top.
📖 Answer
The mechanism: the key is the SQL text plus the parameters, and the value is the list of entity ids in the result. Then each id is fetched from the L2 cache (or the database). So if the entity isn't cached in L2, you took 100 ids from the cache and then ran 100 SELECTs, which is worse than having no cache.
Invalidation works at the table level: Hibernate keeps a "last modified time" for each table (the update timestamps region). One INSERT into the product table, and every cached query that touches product is stale, even if its result didn't change.
List<Country> list = em.createQuery("select c from Country c order by c.name", Country.class)
.setHint("org.hibernate.cacheable", true)
.getResultList();
The example above is a good case: the table almost never changes, and Country itself is in L2 too.
Cases where it does harm:
- tables updated every minute (orders, logs);
- queries with a huge variety of parameters: the cache fills up and there are no hits;
- if the update timestamps region isn't in sync across several nodes: stale results.
In practice I almost never turn on the query cache. If there is a repeated heavy query, caching the result at the service level (Spring Cache + Caffeine/Redis) with an explicit TTL is easier to manage, and I can see what I'm caching.
Sign up to mark studied questions and save your progress.