Quick revision
The short answer
The PostgreSQL JDBC driver only honours the fetch size, by reading through a server-side cursor, when the connection's auto-commit is off; in auto-commit mode it loads all 5 million rows into memory before the loop sees the first one. The fix is to run the query inside a transaction, with a forward-only result set and a positive fetch size, and to process each row without collecting them into a list. MySQL Connector/J has its own streaming rules, and heavy reports are often better run against a replica.
What to remember
In this answer, we saw that setFetchSize is only a hint and that the PostgreSQL driver honours it only when auto-commit is off, the result set is forward-only and the statement is a single query, because its cursor needs an open transaction. In auto-commit mode it loads all rows first, which caused the OutOfMemoryError. We fixed it by running the export in a read-only transaction and processing rows with a callback instead of a list, noted MySQL's different streaming switches, and moved heavy reports to a replica.
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 PostgreSQL JDBC driver only honours the fetch size, by reading through a server-side cursor, when the connection's auto-commit is off; in auto-commit mode it loads all 5 million rows into memory before the loop sees the first one. The fix is to run the query inside a transaction, with a forward-only result set and a positive fetch size, and to process each row without collecting them into a list. MySQL Connector/J has its own streaming rules, and heavy reports are often better run against a replica.
Why this question is asked
This bug is confusing because the code looks right: it sets a fetch size, it processes one row at a time, and yet the heap fills up before the first row is printed. Interviewers like it because the answer depends on knowing what the driver does underneath the JDBC API, and because the same lesson applies to any large export or batch job. In this answer, we will recap what fetch size means, reproduce the problem, see why the PostgreSQL driver ignores the setting, fix it in plain JDBC and with JdbcTemplate, cover MySQL's different rules, and look at where such reports should run.
1A Quick Recap of Fetch Size
When a query returns rows, the driver has two choices. It can read the whole result from the network into memory and then hand rows to our loop, or it can read the rows in chunks as the loop asks for them. setFetchSize(n) is a hint from the JDBC API asking for the second behaviour, with n rows per chunk. It is only a hint: the JDBC specification lets each driver decide how, or whether, to honour it.
In PostgreSQL, reading in chunks needs a cursor, a server-side pointer into the query result from which the client can fetch the next n rows. A PostgreSQL cursor of this kind lives inside a transaction. That single fact explains the whole bug.
2Reproducing the Problem
Here is the report code. It runs from a Spring service method without @Transactional, so the connection is in its default auto-commit mode.
Notice where the error happens: inside executeQuery, before our loop runs at all. A heap dump shows millions of byte arrays held by the driver's result buffer. Our loop was never the problem.
3Why the Driver Ignores the Fetch Size
The PostgreSQL driver (pgjdbc) uses a cursor-based fetch only when several conditions hold together: auto-commit is off, the result set is forward-only (TYPE_FORWARD_ONLY, the default), the fetch size is greater than zero, and the statement is a single query rather than several separated by semicolons. If any condition fails, it falls back to reading the entire result.
The reason for the auto-commit rule is the cursor's lifetime. In auto-commit mode, every statement is its own transaction, committed as soon as it completes, and committing would close the cursor. So the driver cannot leave a cursor open between our next() calls; the only safe way to give us all the rows is to read them all at once.
- Is auto-commit off?the cursor needs an open transactionYesNext checkNoLoad the whole result into memory
- Forward-only result set?
TYPE_FORWARD_ONLYis the defaultYesNext checkNoLoad the whole result into memory - Fetch size above 0?
setFetchSizeordefaultRowFetchSizeYesFetch through a cursor, 1000 rows at a timeNoLoad the whole result into memory
3 steps in order. Play them, or step through them one at a time.
Our code failed the first check, so the fetch size never mattered.
4The Fix: Stream Inside a Transaction
We run the query with auto-commit off. In plain JDBC that means setAutoCommit(false) and a commit at the end; in Spring it means a @Transactional(readOnly = true) method, so the transaction manager switches auto-commit off for us.
Notice that we use a RowCallbackHandler instead of a RowMapper. jdbcTemplate.query with a RowMapper returns a List, which collects all 5 million rows into memory on our side and brings the problem straight back. A callback, or jdbcTemplate.queryForStream used inside try-with-resources, processes each row and lets it go. JPA has the same trap: getResultList() collects everything, while getResultStream() with a fetch-size hint can stream if the driver does.
The defaultRowFetchSize connection property sets a fetch size for every statement on the connection, which is handy for a dedicated reporting data source. And the transaction stays open for the whole export, so on a busy primary a long report also holds back vacuum cleanup; that is one more reason for the next section.
5MySQL Has Different Rules
MySQL Connector/J also reads the whole result into memory by default, but its switches are different. One way to stream is a forward-only, read-only statement with setFetchSize(Integer.MIN_VALUE), which streams rows one at a time but locks the connection until the result set is fully read or closed. The other is the connection property useCursorFetch=true together with a positive fetch size, which uses a server-side cursor in chunks. The details vary by version, so check the Connector/J documentation for the one you use. The general lesson is that fetch size is a driver behaviour, never something the JDBC API guarantees.
6Where Heavy Reports Should Run
Even when it streams correctly, a report that reads 5 million rows competes with live traffic for CPU, I/O and buffer cache on the primary database, and its long transaction delays cleanup of old row versions. For regular heavy reports, a read replica is the better home: it serves the same data with a small delay, and its load does not slow down customer requests. For very large or frequent analytical work, an export to a data warehouse may be better still. In Spring we can point a separate DataSource and JdbcTemplate at the replica, with its own small pool and a default fetch size.
7Follow-up questions
Would increasing the heap fix it?
Only until the table grows. The memory needed is proportional to the number of rows, so a report that fits in 4 GB today will fail again later, and a huge heap makes garbage collection pauses longer for the rest of the service. Streaming keeps memory proportional to the fetch size, which does not grow with the data.
Does queryForStream solve this on its own?
No. queryForStream gives us a Java Stream backed by the ResultSet, which is the right shape for streaming, but the driver still decides how rows arrive. On PostgreSQL it still needs auto-commit off and a fetch size, and the stream must be closed, ideally in try-with-resources, to release the connection.
What fetch size should we choose?
A few hundred to a few thousand rows is typical. Too small, and we make many round trips; with 5 million rows and a fetch size of 10, that is 500,000 round trips. Too large, and memory per chunk grows. We measure: start around 1000 and adjust based on row width and observed throughput.
8Conclusion
In this answer, we saw that setFetchSize is only a hint and that the PostgreSQL driver honours it only when auto-commit is off, the result set is forward-only and the statement is a single query, because its cursor needs an open transaction. In auto-commit mode it loads all rows first, which caused the OutOfMemoryError. We fixed it by running the export in a read-only transaction and processing rows with a callback instead of a list, noted MySQL's different streaming switches, and moved heavy reports to a replica.
Open with
The key is that setFetchSize is only a hint, and the PostgreSQL driver honours it only in certain conditions. To fetch in chunks it uses a server-side cursor, and that cursor lives inside a transaction.
Then, if they want more
If the connection is in auto-commit mode, each statement commits immediately, which would close the cursor, so the driver reads the entire result into memory before returning from executeQuery. That is why the service runs out of memory even though the loop handles one row at a time: the error happens inside executeQuery, before the loop starts.
So I would run the query inside a transaction, in Spring a @Transactional(readOnly = true) method, keep the result set forward-only, which is the default, and keep a fetch size of around a thousand.
I would also check that the code does not collect rows: jdbcTemplate.query with a RowMapper returns a list of all five million, so I would use a RowCallbackHandler or queryForStream in try-with-resources and write each row out as it comes.
For MySQL the rules are different, either a fetch size of Integer.MIN_VALUE for row-by-row streaming or useCursorFetch with a positive fetch size, so I would check the Connector/J docs. Finally, a five-million-row report on the primary competes with customer traffic and holds a long transaction, so I would run it against a read replica with its own data source.
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
- java.sql, package documentation
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 report query on PostgreSQL that returns 5 million rows makes the service run out of...": https://scrivio-interview-library.netlify.app/databases/jdbc/1936b3e35a/