Quick revision
The short answer
I would start by measuring allocation with JFR, then look at the structure: nested groupingBy creates a map per group at every level and boxes every number, so millions of records turn into millions of small objects. The fixes, in order of impact, are to question whether the aggregation belongs in the database or a stream processing system, to stream records from the source in batches instead of loading them all, and to aggregate into flat keys with primitive state, such as summarizingLong or a custom collector with long fields, measuring each change.
What to remember
In this answer, we reviewed a memory-heavy aggregation. Nested groupingBy builds a map per group at every level and boxes every value, and loading all records first doubles the cost. We measure allocation and GC with JFR, flatten keys into one map with primitive accumulators such as summarizingLong or a custom class, stream records from the source in batches, and, most importantly, ask whether a database, warehouse or stream processor should do the aggregation instead, measuring each change against the baseline.
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 start by measuring allocation with JFR, then look at the structure: nested groupingBy creates a map per group at every level and boxes every number, so millions of records turn into millions of small objects. The fixes, in order of impact, are to question whether the aggregation belongs in the database or a stream processing system, to stream records from the source in batches instead of loading them all, and to aggregate into flat keys with primitive state, such as summarizingLong or a custom collector with long fields, measuring each change.
Why this question is asked
In-memory aggregation with streams is pleasant to write: one expression with groupingBy inside groupingBy, and the report is done. It is also one of the most common causes of services that need ever larger heaps and spend a large share of their time in garbage collection. Interviewers ask this design review question at a senior level to see whether we diagnose with data, understand where the memory actually goes, and know when the right fix is not in Java at all. In this answer, we will recap what nested groupingBy builds, see how to measure it, reduce the cost inside Java, stop loading everything at once, and decide when the aggregation should move elsewhere.
1A Quick Recap: What Nested groupingBy Builds
groupingBy creates a map from each key to the result of a downstream collector. When the downstream collector is another groupingBy, every group at the first level gets its own map, and so on down the levels. With a summing collector at the bottom, every leaf holds a boxed Long, an object of 16 bytes wrapping an 8-byte number.
- Input listevery record loaded as an object
- Level 1 mapone entry per region
- Level 2 mapsone map per region, entries per product
- Level 3 mapsone map per region and product
- Leaf valuesa boxed Long and a key object per cell
5 layers, from the top down. Step through them one at a time.
Each level multiplies the number of small objects the GC must track.
Let us estimate. With 20 regions, 5,000 products and 30 days, there can be up to 3 million leaf entries. Each HashMap entry costs roughly 32 to 48 bytes, the table slots add more, and each leaf has a Long plus a LocalDate key, and the intermediate state of summingLong is a small array per group. That is easily a few hundred megabytes for the result alone. And this is on top of the input: if 10 million records were loaded into a List first, at around 80 to 100 bytes each, the heap holds roughly a gigabyte before aggregation even starts. These numbers vary by JVM and settings, which is exactly why we measure.
2Measure First With JFR
Before changing anything, we record what the job really allocates. Java Flight Recorder, built into the JDK, samples allocations with low overhead and records garbage collection pauses.
In JDK Mission Control the allocation view shows which classes and which stack traces allocate most. In a job like this we would expect to see HashMap$Node, Long, the record class and the list's backing array near the top, and GC time as a significant fraction of wall time. These measurements give us a baseline to compare each change against, so we change one thing at a time and keep what helps.
3Make the Aggregation Itself Cheaper
The first improvement inside Java is to flatten the keys. A single map keyed by a small record replaces thousands of nested maps. The second is primitive accumulation: instead of a boxed Long per cell, each group holds one object with primitive fields. summarizingLong does this out of the box, giving a LongSummaryStatistics with count, sum, min and max as long fields; a custom collector or a plain loop can hold exactly the fields we need.
Notice what changed: one map instead of a tree of maps, no boxing on every addition, and a pre-sized table that does not resize repeatedly. In a review we would also check for intermediate collections that are built only to be grouped, and for keys made of long strings that could be interned or replaced by ids. Each of these is a modest gain; together they often cut the aggregation's allocation severalfold. Again, we confirm the gain with a new recording instead of assuming it.
4Stop Loading Everything First
Often the bigger cost is the input, not the result. If the job loads all records into a List with findAll() and then streams over it, the whole data set is in memory at once. Streaming from the source keeps only one batch in memory: a JDBC query with a fetch size, a Spring Data repository method that returns a Stream inside a read-only transaction, or reading files line by line. The aggregation state then grows with the number of groups, not with the number of records.
Note that some JDBC drivers need a specific fetch size or settings before they really stream instead of loading everything, so check your driver's documentation.
5Does the Aggregation Belong in Java at All?
The most important review question is architectural. A GROUP BY in the database does the same work next to the data, uses indexes, and returns only the aggregated rows, perhaps thousands instead of millions, so nothing large crosses the network or lands on our heap. For analytical workloads over historical data, a data warehouse is built for exactly this. For continuously updated aggregates, a stream processing system such as Kafka Streams or Flink maintains the totals incrementally as events arrive, so nobody recomputes them from scratch.
- Record a baseline with JFRallocation, GC time, heap
- Can the database or warehouse aggregate it?YesMove it thereNoKeep it in Java
- Is the data continuously updated?YesConsider a stream processorNoBatch job is fine
- Stream from the source in batchesno full load into a list
- Flatten keys, use primitive stateone map, no boxing
- Measure againkeep only changes that help
6 steps in order. Play them, or step through them one at a time.
Java in-memory aggregation remains a good choice when the data is bounded and already loaded for another reason, or when the logic is genuinely hard to express in SQL. The review should end with a recorded decision and the measurements behind it.
6Follow-up questions
Would a parallel stream fix the performance problem?
Usually not. A parallel groupingBy builds a full set of maps per thread and merges them, which increases allocation and memory. groupingByConcurrent avoids merging but adds contention. The problem here is allocation and data volume, which parallelism does not reduce.
Is tuning the garbage collector a valid fix?
It can buy time, for example a larger young generation or a different collector, but it treats the symptom. Reducing the number of objects created helps every collector, and moving the aggregation to the data removes the problem entirely.
How do we keep the totals correct after changing the code?
Run the old and new implementations on the same sample data set and compare the results exactly, as an automated test. Aggregations are easy to verify this way, and it makes each optimisation safe to merge.
7Conclusion
In this answer, we reviewed a memory-heavy aggregation. Nested groupingBy builds a map per group at every level and boxes every value, and loading all records first doubles the cost. We measure allocation and GC with JFR, flatten keys into one map with primitive accumulators such as summarizingLong or a custom class, stream records from the source in batches, and, most importantly, ask whether a database, warehouse or stream processor should do the aggregation instead, measuring each change against the baseline.
Open with
I'd start with data, not opinions: run the job with Java Flight Recorder, look at allocation by class and stack trace in Mission Control, and note GC time and heap.
Then, if they want more
Then I'd look at the structure. Nested groupingBy creates a separate map for every group at every level, and summing collectors box every value, so millions of records become millions of HashMap nodes, Longs and key objects. On top of that, the job usually loads all records into a list first, which can be a gigabyte before aggregation starts.
My first question would be architectural: does this belong in the database, where a GROUP BY runs next to the data and returns a few thousand rows, or in a warehouse for historical analytics, or in a stream processor like Kafka Streams if the totals are updated continuously?
If it stays in Java, I'd stream from the source in batches, for example a repository method returning a Stream with a proper fetch size, so memory grows with the number of groups, not records.
Then I'd flatten the nested maps into one map keyed by a record, pre-size it, and use primitive accumulation, either summarizingLong or a small accumulator class with long fields, instead of boxed values. I wouldn't expect parallel streams to help, since the problem is allocation.
And I'd measure each change against the baseline and compare results with the old version on the same data.
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.util.stream, package documentation, java.util.function, 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 "Your analytics team aggregates millions of records in memory with groupingBy on several...": https://scrivio-interview-library.netlify.app/java/streams/9a84f7fc3a/