Quick revision
The short answer
The cost comes from many managed entities multiplied by many flushes: with the default AUTO flush mode, every query in a writing transaction can trigger a dirty check of the whole persistence context. For requests that mostly read, we would run them in read-only transactions so Hibernate keeps no snapshots and never flushes, load DTO projections instead of entities, and load fewer entities per request with targeted queries. For write paths that genuinely load many entities, bytecode enhancement with dirty tracking makes each flush cheaper.
What to remember
In this answer, we saw that flush cost grows with the number of managed entities times the number of flushes, and that the AUTO flush mode can run a full dirty check before queries even when a request writes almost nothing. After confirming with Hibernate statistics, the fixes in order are read-only transactions, DTO projections for reads, targeted queries that load fewer entities, and, for heavy write paths only, bytecode enhancement for dirty tracking, followed by measuring again.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
The cost comes from many managed entities multiplied by many flushes: with the default AUTO flush mode, every query in a writing transaction can trigger a dirty check of the whole persistence context. For requests that mostly read, we would run them in read-only transactions so Hibernate keeps no snapshots and never flushes, load DTO projections instead of entities, and load fewer entities per request with targeted queries. For write paths that genuinely load many entities, bytecode enhancement with dirty tracking makes each flush cheaper.
Why this question is asked
A profile that shows 30 percent of CPU inside Hibernate flush code for read-mostly traffic is a classic sign that the application asks Hibernate to protect data it never intends to change. The fix is usually not tuning Hibernate but telling it the truth about what each request does. Interviewers ask this to see whether we can connect a profiler result to the mechanism behind it and choose fixes in the right order. In this answer, we will see why flushing gets expensive, confirm the diagnosis with numbers, and then go through the fixes from the cheapest to the most involved.
1Why Flushing Gets Expensive
Every managed entity has a snapshot of its loaded values. Each flush walks all managed entities and compares every attribute with the snapshot. With the default FlushModeType.AUTO, Hibernate may flush before each query whose tables overlap with pending changes, and before every native query, as well as at commit. So the work is roughly the number of managed entities times the number of attributes times the number of flushes.
Here is a realistic case. A dashboard request loads 2,000 order lines as entities, then runs 30 small queries to build its sections, inside a normal @Transactional method. If even one entity has been touched, or the queries are native, each query can cause a full dirty check: 30 flushes over 2,000 entities with 25 attributes is 1.5 million attribute comparisons for a request that writes nothing. Snapshots also double the memory for those entities, which adds garbage collection time.
- Load 2,000 entitieseach gets a snapshot
- Run the next query
- Pending changes or native query?Yesauto flush: compare all 2,000 entitiesNorun the query
- More queries?Yesrun the next queryNocommit: one more full flush
4 steps in order. Play them, or step through them one at a time.
Read-only work still pays for change detection on every flush.
2Confirming the Diagnosis
Before changing code we confirm the cause. Hibernate statistics, enabled with spring.jpa.properties.hibernate.generate_statistics=true in a test or staging environment, report flushes, entities loaded and statements per session. A session log like the one below makes the problem obvious.
Thirty-one flushes and one modifying statement tell us the request is effectively a read. So the fixes below aim at removing flushes and reducing the number of managed entities.
3Fix 1: Read-Only Transactions
The cheapest fix is to mark read paths @Transactional(readOnly = true). With Hibernate, Spring then sets the session flush mode to MANUAL, so no automatic flush runs, and marks the session read-only by default, so loaded entities get no snapshots at all. Both costs disappear: no comparisons and no doubled memory.
If one request mixes a small write with a large read, we split it: the read runs in a read-only method, and the write runs in its own short transaction. A single query can also be marked read-only with the org.hibernate.readOnly query hint when only part of a method is a read.
4Fix 2: DTO Projections Instead of Entities
Read screens rarely need managed entities. A DTO projection, a query that selects only the columns a view needs straight into a record or interface, creates plain objects that the persistence context does not track at all. They also select fewer columns and never trigger lazy loading.
This is usually the biggest win for dashboards and lists, because it removes both the flush cost and the cost of building full entities.
5Fix 3: Load Fewer Entities Per Request
Sometimes the code loads far more than it uses: a whole collection to count it, all lines to show the first twenty, or an association graph pulled in by eager fetching. Targeted queries fix that: count in the database, page with a limit, fetch only the association the screen needs with a join fetch or an entity graph. Going from 2,000 managed entities to 50 makes any remaining flush 40 times cheaper.
For batch-like writes that must process many entities, we flush and clear every few hundred, so the persistence context never holds more than one chunk.
6Fix 4: Bytecode Enhancement for Heavy Write Paths
If the remaining cost is in write paths that legitimately load many entities, bytecode enhancement with dirty tracking helps. The enhanced entity records which attributes were set, so the flush checks a flag per entity instead of comparing every attribute. It adds a build plugin and is worth it only when the profiler still shows flush cost after the first three fixes.
Finally, we measure again with the same statistics and profile. The target is concrete: zero flushes on read requests, and flush time in the profile down from 30 percent to a few percent.
7Follow-up questions
Why not just switch the whole application to FlushModeType.COMMIT?
Because it changes semantics everywhere. Queries in writing transactions would stop seeing pending changes, which can produce wrong results that are hard to trace. Read-only transactions fix the read paths without touching the behaviour of the writes.
Does open-in-view make this worse?
It can. With open-in-view, the persistence context lives for the whole web request, so entities loaded anywhere stay managed and lazy loads during view rendering add more of them. Turning it off (spring.jpa.open-in-view=false) and building DTOs inside services keeps the context small and short.
How do we stop the problem from coming back?
Assert flush counts or statement counts in tests for the main read endpoints, and keep the statistics enabled in a performance test environment so a new eager fetch or a missing readOnly shows up before production.
8Conclusion
In this answer, we saw that flush cost grows with the number of managed entities times the number of flushes, and that the AUTO flush mode can run a full dirty check before queries even when a request writes almost nothing. After confirming with Hibernate statistics, the fixes in order are read-only transactions, DTO projections for reads, targeted queries that load fewer entities, and, for heavy write paths only, bytecode enhancement for dirty tracking, followed by measuring again.
Open with
I would first confirm the mechanism. Flush cost is roughly the number of managed entities times the number of flushes. Each flush compares every attribute of every managed entity with its snapshot, and with the default AUTO flush mode Hibernate can flush before queries as well as at commit.
Then, if they want more
So a read-mostly request that loads a couple of thousand entities and then runs thirty queries in a normal transaction can do a full dirty check thirty times while writing nothing. I would turn on Hibernate statistics in a test environment to see entities loaded, flush counts and modifying statements per request.
Then I would fix it in order of cost. First, read paths get Transactional readOnly true; with Hibernate, Spring sets flush mode to manual and makes the session read-only, so no snapshots and no flushes. If a request mixes a small write with a big read, I split them.
Second, for screens and lists I load DTO projections instead of entities, so nothing is managed at all. Third, I reduce how many entities are loaded: count and page in the database, fetch only the associations needed, turn off open-in-view.
Only if write paths that really load many entities still show flush cost would I add bytecode enhancement with dirty tracking. And I would measure again and add tests that assert zero flushes on the main read endpoints.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Profiling shows a service spends 30 percent of CPU in Hibernate flush and dirty checking...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/d7d8e23bc1/