Video in progress
A batch job that processes 20 million records every night is written with Hibernate and keeps dying with OOM. How do you redesign it?
I split the job into chunks: each chunk is its own transaction, reading with keyset pagination, and a clear at the end of the chunk. ScrollableResults or a DTO projection for reading, JDBC batch or StatelessSession for writing. Progress is saved so the job can be restarted.
📖 Answer
The usual cause is a single big @Transactional method: everything piles up in one persistence context, and every entity and its snapshot stays out of the GC's reach.
In the redesign I change four things.
Reading. Paging with OFFSET gets slower with every page. Keyset is better:
List<Long> ids = jdbc.sql("""
select id from invoice where id > :last and status = 'NEW'
order by id limit 1000""")
.param("last", lastId).query(Long.class).list();
Or stream with ScrollableResults and a fetch size inside a single transaction, but then the connection is busy for hours and the long transaction blocks vacuum on PostgreSQL. I prefer keyset.
Transaction boundary. Every 1000 records is a separate transaction. If it fails, only one chunk is rolled back.
Memory. If you use entities, em.clear() at the end of each chunk. In many cases you don't need entities at all: StatelessSession or JdbcClient + batch update.
Restart. The last processed ID is written to a separate table. If the job dies, it continues from there. Spring Batch gives you this out of the box (JobRepository, chunks, skip/retry policy), and at 20 million rows I choose it over rolling my own.
If you need parallelism, I partition by ID ranges: each worker takes its own range, so they don't fight over locks. Just don't forget to size the connection pool to the number of workers.
Sign up to mark studied questions and save your progress.