The 30 second answer
You burn a lot of heap on entities, the persistence context, and the JSON buffer, which leads to GC pressure or out-of-memory, a slow query and transfer, timeouts, and a client that cannot render the payload. Paginate with Pageable, prefer keyset pagination for deep pages, project only the columns you need, cap the max page size, and for exports stream in a read-only transaction or write asynchronously to a file.
Large heap usage (entities + persistence context + JSON buffer) → GC pressure/OOM, slow DB query and transfer, timeouts, client can't render it. Fix: pagination (Pageable; prefer keyset/seek pagination for deep pages since OFFSET scans skipped rows), project only needed columns (DTO projections), limit max page size; for exports, stream (Stream<T> with fetch size in a read-only transaction, or async export to file).
Alternate interview scenarios
"How would you process 1 million records without loading them all into memory?"
Here nothing goes back to a client, so the risk is the job, not the response. I read in chunks with keyset pagination: fetch the next thousand rows where the id is greater than the last one I saw, process them, commit, and repeat. Each chunk is its own short transaction, so a failure restarts from the last committed id instead of from zero. With JPA I flush and clear the persistence context after each chunk, otherwise every entity stays managed and the heap grows anyway. If I stream from a single query instead, I check the driver: the PostgreSQL JDBC driver only uses a cursor when autocommit is off, the result set is forward-only and a fetch size is set. Otherwise it silently loads the whole result set. For large recurring jobs, Spring Batch gives chunking, restart and skip handling out of the box.
Sources (4)
- Spring Data JPA — Paging and sortingdocs.spring.io
- PostgreSQL — LIMIT and OFFSETpostgresql.org
- PostgreSQL JDBC: Getting results based on a cursorjdbc.postgresql.org
- Spring Batch reference: Chunk-oriented processingdocs.spring.io