Video in progress

What is JDBC `fetchSize`, and how do you read a million rows from PostgreSQL without filling up memory?

By default PgJDBC loads the whole result into memory. To fetch rows in chunks (with a cursor) you need to set fetchSize and turn autocommit off, otherwise fetchSize is ignored. In Spring, a query that returns a Stream inside @Transactional does this.

📖 Answer

An export job crashed a service with a 2 GB heap with OutOfMemoryError:

List<Row> rows = jdbc.query("SELECT * FROM payments WHERE year = 2025", mapper);

8 million rows into a list. There was no need to keep them in memory; they only had to be written to a CSV.

The right way:

@Transactional(readOnly = true)              // autocommit is turned off
public void export(Writer out) {
    var jdbc = new JdbcTemplate(dataSource);  // so we don't modify the shared bean
    jdbc.setFetchSize(1000);                  // 1000 rows per round trip
    jdbc.query("SELECT id, amount, created_at FROM payments WHERE year = 2025",
        rs -> {                               // RowCallbackHandler: doesn't keep the row
            writeCsvLine(out, rs);
        });
}

The conditions for PgJDBC:

  • the connection must not be in autocommit mode;
  • the result must be TYPE_FORWARD_ONLY (the default);
  • the query must be a single statement.

In Spring Data JPA: Stream<Payment> streamAllByYear(int year) + @QueryHints(@QueryHint(name = HINT_FETCH_SIZE, value = "1000")), closing the stream with try-with-resources, and calling entityManager.detach() or clear() from time to time so entities don't pile up in the Hibernate session.

One thing: reading like this keeps a transaction open for a long time. If it runs for hours, it blocks VACUUM, so I do a very large export on a replica or split it by id ranges.