Quick revision
The short answer
I would stop loading whole documents into memory: large files are streamed with StAX and unmarshalled one element at a time, incoming files get size limits and are rejected or split when too large, and raw files are stored first and processed asynchronously in batches with checkpoints, for example with Spring Batch. The standards add hardened parser settings with entity expansion limits, memory monitoring per job, and tests with production-size files, so the next service does not repeat the incident.
What to remember
In this answer, we saw that unmarshalling a list of 500,000 elements builds every object at once and needs heap that grows with file size. We changed processing to StAX plus JAXB, one element at a time with batched writes, stored raw files and processed them asynchronously in checkpointed Spring Batch jobs, and added limits on file size and on the parser itself. To prevent repeats, we turned this into a standard with a shared template, memory monitoring per job, and tests with production-size files.
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.
I would stop loading whole documents into memory: large files are streamed with StAX and unmarshalled one element at a time, incoming files get size limits and are rejected or split when too large, and raw files are stored first and processed asynchronously in batches with checkpoints, for example with Spring Batch. The standards add hardened parser settings with entity expansion limits, memory monitoring per job, and tests with production-size files, so the next service does not repeat the incident.
Why this question is asked
Memory incidents from XML imports have a recognisable pattern: the code worked for years, files grew, and one night a service ran out of heap and took its other work down with it. When several services fail the same way, the fix is not a bigger heap for each one; it is a change of design and a company standard. Interviewers ask this scenario at senior level because it tests both: the streaming technique, and the judgement to turn one fix into rules that every team follows. In this answer, we will see why in-memory lists fail at this size, change the processing to streaming, design the file handling around storage and batches, add safety limits, and set the standards and tests that prevent a repeat.
1Why In-Memory Lists Fail at This Size
When JAXB unmarshals a document whose root holds a List of 500,000 elements, it creates all 500,000 objects and every object inside them before returning anything. A Java object takes several times the space of its XML text: each object has a header, each reference takes space, and each string is a separate object with its own array. An element that is 400 bytes of XML can easily take 2 KB of heap, so 500,000 of them need about 1 GB. On top of that, each time the ArrayList grows it copies its internal array into a bigger one, so for a moment both arrays are in memory.
Several things make it worse in production. Two files arriving at the same time double the peak. The service often also keeps a DOM or a copy of the raw text. And the garbage collector struggles when a large part of the heap is live, so the service slows down for minutes before it fails, affecting everything else running in it.
| Approach | Peak heap | Grows with file size? |
|---|---|---|
| JAXB unmarshal of the whole document | about 1 GB or more | yes, linearly |
| DOM parse, then JAXB | 2 GB or more | yes, linearly |
| StAX plus JAXB per element, batch of 1,000 | tens of MB | no |
2Streaming One Element at a Time
The fix in code is to combine StAX, the Java streaming XML API, with JAXB. StAX reads the document as a stream of events and keeps almost nothing in memory. When the reader reaches the start of an element we want, we hand it to JAXB, which unmarshals just that element and returns one object. We process it, add it to a batch, and let it go.
Notice that the loop only advances with next() when it did not just unmarshal, because unmarshal() already moves the reader past the element; calling next() again could skip a following element. With this change, memory is bounded by one element plus one batch, which is a constant, rather than by the file size, which is not.
3Store First, Process Asynchronously in Batches
Many of these services also receive the file in an HTTP request and process it inside that request. That makes the request slow, ties memory to the caller's timing, and means a failure halfway leaves no record of what was done. A sturdier design receives the file, stores it unchanged in object storage or a file share, records an import job, and returns immediately with a job id. A separate worker processes the job from the stored file.
Spring Batch provides the processing side ready-made: a StaxEventItemReader reads fragments of the file with a Jaxb2Marshaller, a chunk-oriented step writes items in chunks of, say, 1,000 and commits after each one, and the job repository records how far it got. If the job fails at element 320,000, it restarts from the last committed chunk instead of from the beginning, and we keep the raw file to re-run or investigate.
- Receive filestream to storage, never into memory
- Within the size limit?YesRecord an import jobNoReject or route to splitting
- Worker reads with StAX plus JAXBone element at a time
- Write in chunks of 1,000commit and checkpoint each chunk
- Failure?YesRestart from the last checkpointNoMark the job complete
- Report counts and rejected records
6 steps in order. Play them, or step through them one at a time.
4Limits on Size and on the Parser
Streaming removes the memory risk from size, but limits are still needed. Each integration declares the largest file it expects, with headroom, for example 2 GB or 2 million elements, and files above that are rejected with a clear error or routed to a splitting step. A file ten times larger than ever before is more likely to be a mistake or an attack than a real business event, and processing it would delay every other job.
The parser needs limits of its own, because XML can be small on disk and huge in memory. Entity expansion attacks, such as the 'billion laughs' document, define entities that refer to other entities and expand a few kilobytes into gigabytes. Our standard parser settings disable DTDs entirely, which removes entities, and keep the JDK's processing limits on through secure processing. The JDK also has system properties for limits such as jdk.xml.entityExpansionLimit, jdk.xml.totalEntitySizeLimit and jdk.xml.maxElementDepth; their defaults have changed across releases, so check your JDK version and set them explicitly where a service accepts XML from outside.
5Standards, Monitoring and Production-Size Tests
To stop the next team from repeating the incident, the design becomes a standard. Any XML input that can exceed a threshold, for example 50 MB, must be processed by streaming, not by unmarshalling the whole document. Parsers come from the shared hardened helper. Import jobs run in a worker separate from request handling, with a size limit declared per integration. We provide a small library or a Spring Batch template that does all of this, so following the standard is less work than not following it.
Each import job reports its memory use, item count and duration, and we alert on jobs whose heap use climbs with file size, which is the sign of something accumulating. Finally, every import is tested with a file of production size, or larger, in CI or a nightly job, with a fixed heap such as -Xmx512m. A test with ten sample elements proves the mapping; only a test with 500,000 proves the memory design, and it would have caught every one of these incidents before production.
6Follow-up questions
Why not just increase the heap?
It moves the failure to the next, slightly bigger file, and wastes memory the rest of the time. With several files at once or other work in the same service, the heap needed is unpredictable. Streaming makes memory constant, which is the only property that scales.
What if processing an element needs data from elsewhere in the file?
Then we stream twice or stage the data. A first pass can collect a small index, such as header values or referenced ids, and a second pass processes the elements. Alternatively we load the elements into a staging table and do the cross-element work in SQL.
How do you split an oversized file safely?
With the same StAX reader: stream through the file and write every N elements into a new, well-formed file with the same root and header. Each part is then an ordinary job, and the parts can run in parallel.
7Conclusion
In this answer, we saw that unmarshalling a list of 500,000 elements builds every object at once and needs heap that grows with file size. We changed processing to StAX plus JAXB, one element at a time with batched writes, stored raw files and processed them asynchronously in checkpointed Spring Batch jobs, and added limits on file size and on the parser itself. To prevent repeats, we turned this into a standard with a shared template, memory monitoring per job, and tests with production-size files.
Open with
The root cause is that JAXB builds the whole list before returning, and Java objects take several times the size of the XML, so half a million elements can need a gigabyte of heap that grows with every bigger file.
Then, if they want more
I would change three things in the design. First, stream: read with a hardened StAX XMLStreamReader and unmarshal one element at a time with unmarshal of the reader and the element class, writing in batches of about a thousand and releasing them, so memory is constant.
Second, decouple: receive the file, store it as-is, create an import job and process it asynchronously, ideally with Spring Batch, using a StaxEventItemReader, chunk commits and checkpoints so a failure restarts from the last chunk.
Third, limits: each integration declares a maximum file size and oversized files are rejected or split; parsers disable DTDs and keep entity expansion limits on, with the JDK's limits set explicitly. Then I would make it a standard, any XML input above a threshold must stream, with a shared template so it is the easy path.
And I would add memory monitoring per job and tests with production-size files under a fixed heap, because a ten-element test proves the mapping but only a full-size file proves the memory design.
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 official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
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 "Partner XML files contain lists with 500,000 elements, and services map them into...": https://scrivio-interview-library.netlify.app/java/jaxb/d0c42d0358/