Video in progress
How do you approach writing a large collection to a DB or sending it to an external API in batches, and where is it easy to go wrong?
I split the data into fixed-size chunks and send each one in a separate transaction or request. The main risks: subList windows being tied to the original list, loading everything into memory, one error rolling back the whole job, and duplicates on retry.
📖 Answer
The simple case is when the list is already in memory:
static <T> List<List<T>> chunks(List<T> src, int size) {
List<List<T>> out = new ArrayList<>((src.size() + size - 1) / size);
for (int i = 0; i < src.size(); i += size) {
out.add(List.copyOf(src.subList(i, Math.min(i + size, src.size()))));
}
return out;
}
List.copyOf is deliberate: subList is a window. If the chunks go to an asynchronous worker and the original list changes, you get a CME or wrong data. Guava's Lists.partition also returns windows, which is cheap and correct if you use them right away on one thread. If there may be null elements, List.copyOf throws an NPE, so use new ArrayList<>(...) in that case.
Chunk size is something you measure. In a JDBC batch, 500 to 1000 rows is usually good. With the PostgreSQL driver, unless reWriteBatchedInserts=true is set, every row in the batch runs as a separate INSERT. In Hibernate you need hibernate.jdbc.batch_size and a flush()/clear() after every chunk, otherwise the persistence context fills up with thousands of entities. For an external API, the size is set by their limits.
Where it is easy to go wrong:
- Loading millions of records into a full list first. If you read from the DB with keyset pagination and process chunk by chunk, memory stays at the size of one chunk.
- Everything in one transaction. A single error rolls back 2 million rows, and a long transaction holds locks. Make each chunk a separate transaction and save the progress (the last processed id).
- Retry. If a chunk fails when half written, a retry creates duplicates. You need idempotency:
ON CONFLICT DO NOTHING, an idempotency key for an external API. - Sending in parallel. Limit the number of chunks in flight (a
Semaphoreor a bounded pool), otherwise the DB connection pool or the receiving service chokes.
A chunk that fails, I write to a separate table or a DLQ, and the job continues. Later you can reprocess just that one.
Sign up to mark studied questions and save your progress.