Quick revision
The short answer
The endpoint is slow because it loads all 100,000 rows into a list, builds 100,000 objects, and then serializes them into one big buffer, so memory holds several copies of the data at once. We fix it by streaming: page the results, or write rows to the response one by one with Jackson's JsonGenerator while reading them from the database with a cursor. We also reuse ObjectMapper and ObjectWriter, return smaller DTOs with only the needed fields, and ask whether the client really needs all the rows.
What to remember
In this answer, we saw that the slow endpoint holds the full data set several times, in the driver, the persistence context, the DTO list and the output buffer. We sent smaller DTOs and reused the ObjectMapper and an ObjectWriter, paged results for screens, streamed full exports with JsonGenerator and a database cursor in a transaction on the writing thread, and asked whether the client needs all the rows at all.
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 endpoint is slow because it loads all 100,000 rows into a list, builds 100,000 objects, and then serializes them into one big buffer, so memory holds several copies of the data at once. We fix it by streaming: page the results, or write rows to the response one by one with Jackson's JsonGenerator while reading them from the database with a cursor. We also reuse ObjectMapper and ObjectWriter, return smaller DTOs with only the needed fields, and ask whether the client really needs all the rows.
Why this question is asked
Large JSON responses are a classic production problem. They work in testing with 500 rows, then a real customer asks for a full export and the service spends seconds in garbage collection or dies with an OutOfMemoryError, taking other users' requests with it. Interviewers like this scenario because a good answer moves from measuring to the data flow, the database, Jackson and the API contract. In this answer, we will see where the memory goes, then fix the problem in steps: smaller DTOs and reused writers, paging, streaming with JsonGenerator, and finally the question of whether the client needs all of it.
1Where the Memory Goes
Let us start with the typical slow version. The controller asks a repository for all orders, maps them to DTOs, and returns the list. Spring MVC hands the list to Jackson, which writes it to the response.
- JDBC result setWhole result buffered by the driver
- Hibernate entities100,000 managed objects plus snapshots
- DTO listAnother 100,000 objects
- JSON outputTens of MB of text produced at once
4 layers, from the top down. Step through them one at a time.
Each layer holds the full data set at the same time; streaming keeps only one row in each.
Count the copies. The JDBC driver may buffer the whole result set, PostgreSQL's driver does unless we set a fetch size inside a transaction. Hibernate creates 100,000 entities and keeps them all in the persistence context, its first-level cache, with a snapshot of each for dirty checking. Then we create 100,000 DTOs. Then the JSON text is produced, often 50 MB or more for wide rows. If any lazy association is touched during mapping, we also run extra queries per row. Measuring with a profiler or the JFR allocation view usually shows exactly this picture: the time is spent allocating and collecting, not serializing.
So the fix is not a faster JSON library. The fix is to avoid holding everything at once.
2Fix 1: Smaller DTOs and Reused Writers
The cheapest improvement is to send less. If the export screen shows six columns, the DTO should have six fields, not the forty fields of the entity with nested customer and address objects. A query that selects only those columns into a record, a projection, also avoids creating managed entities at all.
Next, reuse Jackson's objects. ObjectMapper is expensive to create because it builds and caches serializers; creating one per request throws that cache away every time. A mapper is thread-safe once configured, so we inject Spring Boot's mapper. For repeated writes of the same type, an ObjectWriter from mapper.writerFor(OrderRow.class) is also immutable, thread-safe and cheap to reuse, and it skips looking up the serializer for each call.
3Fix 2: Paging the Results
For most client screens, paging is the right answer: the client asks for 500 rows at a time and follows a link or a cursor to the next page. Each request then holds at most 500 rows, which is fast and predictable. Keyset paging, where the next page starts after the last id we returned, stays fast deep into the data, while OFFSET paging gets slower as the offset grows because the database still walks the skipped rows.
4Fix 3: Streaming the Response With JsonGenerator
When the client really needs everything in one response, for example a nightly export job, we stream. Instead of building a list, we open a database cursor and write each row to the HTTP output as soon as we read it. Jackson's streaming API, JsonGenerator, writes tokens directly to an OutputStream, so memory holds one row at a time. Spring MVC's StreamingResponseBody gives us that stream and runs our code on an async thread.
7 messages in order. Play them, or step through them one at a time.
Memory holds one batch of rows at a time, whatever the total size.
Notice a few details. The transaction is opened inside the lambda with a TransactionTemplate, because StreamingResponseBody runs on a different thread from the controller, and a @Transactional on the controller method would already have ended. The PostgreSQL driver only honours the fetch size when autocommit is off, which the transaction gives us. And we use plain JDBC rather than entities, so nothing accumulates in a persistence context; with JPA streams we would have to detach or clear entities as we go.
But there is a catch: once we have started writing, the status code 200 is already sent. If the database fails halfway, the client receives truncated JSON. Clients must therefore check that the document is complete, and for very large exports newline-delimited JSON, one object per line, makes partial results easier to handle and resume.
5Asking Whether the Client Needs All the Rows
Before we build any of this, it is worth asking the product owner or the client team what they do with 100,000 rows. Often the answer is that a screen shows 50 and the rest was loaded just in case, or that a report sums them, in which case the server can return the sum. For a genuine bulk export, an asynchronous job that writes a file to object storage and returns a link is often better than a long-running HTTP response: it survives client disconnects, can be retried, and keeps request threads free. Streaming is the right tool when a synchronous full response is truly needed.
6Follow-up questions
Why not just increase the heap?
Because the cost grows with the data and with concurrency. Ten users exporting at the same time need ten times the memory, and larger heaps mean longer garbage collection work. Streaming makes memory per request constant, so the service stays stable however large the export grows.
Does returning a Stream<OrderDto> from a Spring MVC controller stream the response?
Not by itself. Spring MVC treats a Stream like any other object and Jackson serializes it, but the surrounding code usually still needs an open transaction and connection for the whole write, and error handling is unclear. An explicit StreamingResponseBody with a generator makes the lifecycle visible, which is why I prefer it.
Would gzip compression help?
It reduces the bytes on the network, often by five to ten times for JSON, which helps slow clients and costs some CPU. It does not reduce the memory used to build the response, so it complements streaming rather than replacing it.
7Conclusion
In this answer, we saw that the slow endpoint holds the full data set several times, in the driver, the persistence context, the DTO list and the output buffer. We sent smaller DTOs and reused the ObjectMapper and an ObjectWriter, paged results for screens, streamed full exports with JsonGenerator and a database cursor in a transaction on the writing thread, and asked whether the client needs all the rows at all.
Open with
First I would measure, but in this situation the cause is almost always that we hold everything at once: the driver buffers 100,000 rows, Hibernate keeps 100,000 entities and their snapshots, we build 100,000 DTOs, and Jackson writes tens of megabytes in one go.
Then, if they want more
So the fixes are about the data flow. I would make the DTO as small as the client needs and load it with a projection instead of entities, and make sure we reuse the injected ObjectMapper and an ObjectWriter built once, never a new mapper per request.
For screens I would page, preferably with keyset paging, so each call holds a few hundred rows.
If the client really needs the full set in one response, I stream it: StreamingResponseBody, a JsonGenerator on the output stream, and a JDBC query with a fetch size inside a TransactionTemplate on the writer thread, so we hold one batch at a time.
I would mention that once streaming starts the status is already 200, so failures show up as truncated output, and NDJSON helps there. And I would ask whether the client needs 100,000 rows at all; often a summary, a filter, or an asynchronous export file is the better product.
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
- Spring Framework reference, Spring Web MVC
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 JSON endpoint is slow and uses a lot of memory for large responses of 100,000 rows....": https://scrivio-interview-library.netlify.app/spring-boot/json-serialization/a48575dc28/