Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A flame graph of a slow Spring Data JPA endpoint shows most time inside Hibernate flush and dirty checking. What is likely happening and how would you fix it?

Most likely the persistence context holds a very large number of managed entities, and at every flush Hibernate compares each one with the snapshot it took when loading it, which is dirty checking. If the endpoint only reads, we use @Transactional(readOnly = true) or DTO projections so the entities are not tracked; if it writes in bulk, we flush and clear every few dozen entities. We also check whether queries in the same transaction trigger repeated auto-flushes, and we enable Hibernate statistics in a test to count entities, flushes and queries.

Why this question is asked

A flame graph that is wide in Hibernate's flush code surprises people, because the endpoint may not even write anything. The cost comes from bookkeeping Hibernate does on our behalf, and it grows with how many entities we load. Interviewers ask this debugging question to see whether we understand the persistence context and can link a profile to the code that causes it. In this answer, we will recap the persistence context and dirty checking, reproduce the cost, and go through the fixes for reads, batch writes and auto-flush, with statistics to confirm each one.

1A Quick Recap: The Persistence Context and Dirty Checking

In JPA, an EntityManager, which in Hibernate is a Session, keeps a persistence context: a map of every entity it has loaded or saved in the current transaction. Entities in it are called managed. The persistence context guarantees that loading the same row twice gives the same object, and it tracks changes so we never have to call update ourselves.

To track changes, Hibernate keeps a snapshot of each managed entity's state as it was loaded, an array of its field values. At flush time, when it sends pending changes to the database, it walks through every managed entity and compares the current values with the snapshot. Any difference becomes an UPDATE. That comparison is dirty checking. Flush happens before commit, and also before some queries, as we will see.

2Reproducing the Cost

Here is a typical endpoint that becomes slow. It loads orders with their lines to build a report, and the method runs in an ordinary read-write transaction.

Java
@Transactional // read-write, the default
public ReportDto monthlyReport(YearMonth month) {
List<Order> orders = orderRepository.findWithLines(month); // 20,000 orders, 180,000 lines
// 200,000 managed entities, each with a snapshot of its fields
return ReportDto.from(orders);
} // commit -> flush -> dirty check of 200,000 entities (no changes found)
// Hibernate statistics for one call:
// entities loaded: 200,000 flushes: 1 statements: 2
// flame graph: DefaultFlushEntityEventListener.dirtyCheck ... wide

Notice that nothing was changed, yet Hibernate still compared 200,000 entities field by field. The snapshots also double the memory the entities use, which adds GC pressure that shows up elsewhere in the flame graph. The more entities we load, the worse it gets, and if the same transaction flushes several times, the cost repeats each time.

3Fix 1: Read-Only Transactions and DTO Projections

If the endpoint only reads, we tell Spring and Hibernate so. With @Transactional(readOnly = true), Spring sets the Hibernate session to read-only and the flush mode to manual. Entities loaded in a read-only session have no snapshot, and there is no automatic flush, so dirty checking disappears.

Even better for reports is not to load entities at all. A DTO projection, a query that selects only the needed columns into a plain record, creates no managed entities, takes less memory and usually fetches less data.

Java
@Transactional(readOnly = true) // no snapshots, no flush
public ReportDto monthlyReport(YearMonth month) { ... }
// Or a projection: plain records, nothing managed
public record OrderTotal(long orderId, LocalDate day, BigDecimal total) {}
@Query("""
select new com.shop.OrderTotal(o.id, o.day, sum(l.price * l.quantity))
from Order o join o.lines l
where o.day between :from and :to
group by o.id, o.day""")
List<OrderTotal> totals(LocalDate from, LocalDate to);
// statistics: entities loaded: 0 flushes: 0

The projection also moves the summing into the database, which returns 20,000 small rows instead of 200,000 entity rows. That is often a bigger win than avoiding the dirty check.

4Fix 2: Flush and Clear in Batch Work

If the endpoint writes many entities, for example importing 100,000 rows, the persistence context keeps all of them, and each flush checks everything inserted so far. We flush and clear every batch: flush sends the pending inserts, and clear removes the entities from the persistence context, so the next flush only sees the next batch.

Java
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_inserts=true
@Transactional
public void importRows(List<RowDto> rows) {
for (int i = 0; i < rows.size(); i++) {
entityManager.persist(rows.get(i).toEntity());
if ((i + 1) % 50 == 0) {
entityManager.flush(); // 50 inserts in one JDBC batch
entityManager.clear(); // context back to empty
}
}
} // managed entities at any time: at most 50 instead of 100,000

Notice that after clear() any entity we still hold is detached, no longer tracked, so we must not modify it and expect an update. Also note that JDBC batching of inserts does not work with IDENTITY id generation in Hibernate, because Hibernate needs each generated id immediately; a sequence with an allocation size works better for bulk inserts.

5Fix 3: Check for Repeated Auto-Flush

With the default flush mode, AUTO, Hibernate flushes before running a query if pending changes might affect that query's result, so the query sees our own changes. Before a native SQL query, Hibernate cannot always tell which tables are involved and may flush everything (the exact rules vary by version, so check yours).

So a loop that modifies an entity and then runs a query in each iteration triggers a flush, and a full dirty check, on every iteration. With 2,000 managed entities and 2,000 iterations, that is four million comparisons.

Step throughAuto-flush inside a loop
Service loopHibernate sessionDatabase
change entity 1
run query for the next item
auto-flush: dirty check all managed entities
UPDATE entity 1
SELECT ...
change entity 2, run query again
auto-flush: dirty check all again

7 messages in order. Play them, or step through them one at a time.

Every query after a change can trigger a full dirty check of the persistence context.

The fix is to restructure: run the queries first and load what the loop needs in one go, then make the changes, so there is only one flush at the end.

6Confirm With Hibernate Statistics

To prove a fix, we count rather than guess. Hibernate statistics, turned on in a test, report entities loaded, flushes and statements per session. A test can assert on them, which also stops the problem from coming back.

Java
# test profile
spring.jpa.properties.hibernate.generate_statistics=true
Statistics stats = entityManagerFactory.unwrap(SessionFactory.class).getStatistics();
stats.clear();
reportService.monthlyReport(YearMonth.of(2026, 10));
assertThat(stats.getEntityLoadCount()).isZero(); // projection: 0
assertThat(stats.getFlushCount()).isLessThanOrEqualTo(1); // no repeated auto-flush
assertThat(stats.getPrepareStatementCount()).isEqualTo(1);

7Follow-up questions

Does readOnly = true stop all writes?

Not on its own at the database level unless the driver and database honour a read-only connection. In Spring with Hibernate, it sets the session to read-only and manual flush, so changes to entities are simply not flushed. Some setups also route read-only transactions to replicas. It is a strong hint and an optimisation, not a security control.

Is bytecode enhancement an alternative?

Hibernate's bytecode enhancement can add dirty tracking to entities, so each entity records which fields changed when a setter runs and flush does not need to compare every field. It helps for large write transactions, but it adds build complexity, and for read-only work avoiding managed entities is simpler and gives a bigger win.

When would you use a StatelessSession?

For large batch jobs that read or write many rows without needing a persistence context at all. A StatelessSession has no first-level cache, no dirty checking and no cascades, so each operation goes straight to the database. It suits imports and exports where we control every statement.

8Conclusion

In this answer, we saw that time spent in Hibernate's flush and dirty checking comes from a large persistence context: at every flush Hibernate compares each managed entity with its snapshot. For reads, @Transactional(readOnly = true) or DTO projections avoid tracking entities; for batch writes, flushing and clearing every few dozen entities keeps the context small; repeated auto-flushes before queries in a loop should be removed by restructuring; and Hibernate statistics in a test count entities, flushes and statements to confirm the fix.

What to say in the interviewAbout 80 seconds aloud

Open with

Time in flush and dirty checking means the persistence context is large. Hibernate keeps a snapshot of every managed entity, and at each flush it compares every one with its snapshot to find changes, even if nothing changed.

Then, if they want more

So if the endpoint loads, say, 200,000 orders and lines in a normal read-write transaction, commit triggers a dirty check of all of them, and the snapshots double memory and GC.

If the endpoint only reads, I would use Transactional with readOnly true, which in Spring makes the Hibernate session read-only with manual flush, so there are no snapshots and no flush, or better a DTO projection that selects only the needed columns and creates no managed entities at all.

If it writes in bulk, I would flush and clear every 50 entities with JDBC batching, keeping the context small. I would also look for auto-flush: with the default AUTO mode, a query after a change triggers a flush, so a loop that changes and queries does a full dirty check on every iteration.

And I would enable Hibernate statistics in a test to count entities loaded, flushes and statements, and assert on them so the problem does not come back.

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 official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
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 "A flame graph of a slow Spring Data JPA endpoint shows most time inside Hibernate flush...": https://scrivio-interview-library.netlify.app/spring-boot/service-performance/d4e09af8c6/