Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A batch job that updates 2 million entities in one transaction slows down progressively and then fails with OutOfMemoryError. What is happening and how do you fix it?

Every entity the job loads stays managed in the persistence context, along with a snapshot copy for dirty checking, so memory grows with each entity and every flush compares more and more objects until the JVM runs out of heap. We fix it by processing in chunks: flush() and clear() every N entities, or commit a transaction per chunk. For reading, a stream or scroll with DTO projections avoids managed entities altogether, a single bulk UPDATE avoids loading anything when the change is simple, and Spring Batch gives us chunking with restartability.

Why this question is asked

Batch jobs are where JPA's convenience turns against us. The same code that works perfectly for one request, load entities, change them, let dirty checking save them, becomes slower with every thousand rows and finally crashes when it runs over two million. Interviewers like this question because the symptoms, progressive slowdown and then OutOfMemoryError, point straight at how the persistence context works. In this answer, we will reproduce the problem, explain both symptoms, and then go through four fixes: chunking with flush and clear, streaming reads, bulk updates, and Spring Batch.

1Reproducing the Problem

Here is a typical job: reprice every product in one transaction.

Java
@Transactional
public void repriceAll() {
List<Product> all = productRepository.findAll(); // 2,000,000 managed entities
for (Product p : all) {
p.setPrice(p.getPrice().multiply(new BigDecimal("1.05")));
}
} // flush at commit: 2,000,000 dirty checks and UPDATEs
// Observed: first 100,000 rows quick, then steadily slower,
// then java.lang.OutOfMemoryError: Java heap space

Even a version that reads page by page, inside one transaction, fails the same way, because what fills memory is not the list but the persistence context behind it.

2Why Memory Grows and Everything Slows Down

Every entity loaded inside a transaction is managed: the persistence context keeps a reference to it in its map, and it keeps a snapshot of the values it was loaded with, so that dirty checking can compare them at flush. Neither is released until the context is cleared or closed, which in Spring means the end of the transaction. With two million products, that is two million entity objects plus two million snapshots, plus whatever associations were loaded. Nothing can be garbage collected, so the heap fills.

The slowdown comes from flushing. Each flush, at commit or before a query in AUTO flush mode, walks every managed entity and compares it with its snapshot. If the job runs any query in the loop, each flush checks all entities loaded so far: the first check covers 1,000 entities, a later one 1,000,000. The work per row keeps growing, so the job slows down long before it crashes. Garbage collection struggling with an almost full heap adds to it.

What the persistence context holds as the job runs
Rows processedManaged entitiesSnapshotsWork per flush
10,00010,00010,000Small
500,000500,000500,000Large
2,000,0002,000,0002,000,000Huge, then OutOfMemoryError
Any point, with clear() every 1,000at most 1,000at most 1,000Constant

3Fix 1: Process in Chunks With flush() and clear()

The direct fix is to keep the persistence context small. Every N entities, we flush, which sends the pending UPDATEs to the database, and clear, which detaches everything so it can be garbage collected. With JDBC batching enabled, each flush sends its updates in batches.

Java
spring.jpa.properties.hibernate.jdbc.batch_size=50
spring.jpa.properties.hibernate.order_updates=true
@Transactional
public void repriceInChunks() {
int size = 1_000;
for (int page = 0; ; page++) {
List<Product> chunk = em.createQuery("select p from Product p where p.id > :last order by p.id", Product.class)
.setParameter("last", lastId).setMaxResults(size).getResultList();
if (chunk.isEmpty()) break;
chunk.forEach(p -> p.setPrice(p.getPrice().multiply(RATE)));
lastId = chunk.get(chunk.size() - 1).getId();
em.flush(); // 1,000 UPDATEs sent in batches of 50
em.clear(); // context empty again; memory stays flat
}
}

Notice that we page by id rather than by offset, so each query is quick even near the end of the table. This version keeps memory flat, but it is still one transaction for two million rows, which holds locks and a long-running transaction on the database. Committing a transaction per chunk, for example by calling a @Transactional method on another bean for each chunk or using TransactionTemplate, keeps each transaction short and also makes progress durable: if the job fails at row 1.5 million, the first 1.5 million are saved. The job must then be safe to rerun, for example by remembering the last id processed.

4Fix 2: Read With a Stream and DTO Projections

If the job mostly reads, for an export or a report, it does not need managed entities at all. A query that selects into a record returns plain objects that the persistence context does not track, and a stream with a fetch size reads rows from the database in batches instead of all at once.

Java
record PriceRow(long id, BigDecimal price) {}
@Transactional(readOnly = true)
public void export(Writer out) {
try (Stream<PriceRow> rows = em.createQuery(
"select new com.example.PriceRow(p.id, p.price) from Product p", PriceRow.class)
.setHint("org.hibernate.fetchSize", 1_000)
.getResultStream()) {
rows.forEach(r -> write(out, r)); // DTOs are not managed: no snapshots, nothing to clear
}
}

The stream must be closed, which try-with-resources does, and the JDBC driver must actually stream. PostgreSQL's driver only does so with a fetch size inside a transaction with auto-commit off; MySQL needs its own settings, so check your driver. Hibernate's ScrollableResults gives the same streaming with more control.

5Fix 3: Use a Bulk UPDATE When the Change Is Simple

Our repricing is the same arithmetic for every row. There is no reason to load two million objects to do it. A single bulk UPDATE runs entirely in the database.

Java
@Transactional
public int repriceInDatabase() {
return em.createQuery("update Product p set p.price = p.price * 1.05")
.executeUpdate(); // 2000000: one statement, no entities loaded
}

This is often seconds instead of an hour. Two cautions: bulk statements bypass the persistence context, so any entities already loaded in the same context are now stale, and they bypass entity callbacks and the @Version increment unless we write it into the statement. For a very large table, running the update in ranges of ids keeps each transaction and its locks smaller.

6Fix 4: Spring Batch for Chunking With Restartability

For jobs that run regularly and must survive failures, Spring Batch provides all of this as a framework. A chunk-oriented step reads items, processes them, and writes them in chunks of a configured size, with one transaction per chunk. The job repository records how far each step got, so a failed job restarts from the last committed chunk instead of from the beginning, and skip and retry policies handle bad rows.

Java
@Bean
Step repriceStep(JobRepository repo, PlatformTransactionManager tx,
JpaPagingItemReader<Product> reader, JpaItemWriter<Product> writer) {
return new StepBuilder("reprice", repo)
.<Product, Product>chunk(1_000, tx) // one transaction per 1,000 items
.reader(reader)
.processor(p -> { p.setPrice(p.getPrice().multiply(RATE)); return p; })
.writer(writer)
.build();
}

The chunk-size API changed in Spring Batch 6, so check your version for the exact builder method. The idea stays the same: a bounded amount of work per transaction, and a recorded position for restarts.

7Follow-up questions

How do we choose the chunk size?

Large enough that the overhead per chunk is small, small enough that memory and transaction length stay modest. Between 500 and 5,000 entities is a common range. It should be a multiple of the JDBC batch size, and we measure: if doubling the chunk barely changes throughput, the smaller one is better because it holds locks for less time.

Would a StatelessSession help?

Yes. Hibernate's StatelessSession has no persistence context at all: no snapshots, no dirty checking, no cascading, and updates are explicit. That makes it well suited to bulk processing of entities, at the cost of losing JPA conveniences. It is a good middle ground when the logic per row is too complex for a bulk UPDATE.

8Conclusion

In this answer, we saw that a two-million-entity job in one transaction keeps every entity and its snapshot in the persistence context, so memory grows until OutOfMemoryError, and each flush has more entities to dirty check, so the job slows down first. We fixed it by flushing and clearing every N entities, ideally with a transaction per chunk, by streaming DTO projections for reads, by replacing per-entity work with a bulk UPDATE when the change is simple, and by using Spring Batch for chunking with restartability.

What to say in the interviewAbout 90 seconds aloud

Open with

The problem is the persistence context. Every entity loaded in the transaction stays managed until the transaction ends, together with a snapshot of its loaded values for dirty checking.

Then, if they want more

With two million products that is two million objects plus two million snapshots that can never be garbage collected, so the heap eventually runs out.

The progressive slowdown comes first, because every flush, at commit or before a query in auto flush mode, has to compare every managed entity with its snapshot, so the cost per row keeps rising and garbage collection struggles too. My fixes depend on the job.

In general I process in chunks: load a thousand rows by id range, change them, call flush to send the updates, with JDBC batching on, and clear to detach them, and preferably commit each chunk in its own transaction so progress is durable and locks are short.

If the job only reads, I select into DTO records with a stream and a fetch size, so nothing is managed at all. If the change is the same for every row, like a five percent price increase, one bulk UPDATE statement does it without loading any entities, keeping in mind that it bypasses the persistence context and version checks.

For a regular, important job, I would use Spring Batch chunk steps, which give one transaction per chunk and restart from the last committed chunk.

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.
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 batch job that updates 2 million entities in one transaction slows down progressively...": https://scrivio-interview-library.netlify.app/databases/jpa-fundamentals/ba8d91ab89/