Scrivio Interview library
LeadershipPrincipal6 min read · updated 12 November 2026

Over years, more aggregation logic moved from SQL into Java stream code, and some services now load large data sets to group them in memory. How would you decide where aggregation belongs in your architecture, and what would you standardise?

Aggregation over large data belongs close to the data: in the database, a data warehouse or a stream processor, because loading large sets into Java to group them costs memory, GC time and network transfer for results that are often a few hundred rows. In-memory streams are right for bounded data that is already loaded for other reasons. I would standardise limits, such as a maximum number of rows loaded per request with reviewed exceptions, and require that business rules stay testable whichever layer runs them.

Why this question is asked

Logic drifts. Over years, a query that grouped in SQL gets replaced by findAll() and a stream because it was easier to unit test, or because the ORM made it natural, or because a rule needed a little Java. Each step is reasonable, and together they produce services that load millions of rows to show a dashboard of twenty numbers. Interviewers ask this at the most senior level because it is about setting architectural direction, not writing a query. In this answer, we will recap how the drift happens and what it costs in numbers, build a way to decide where an aggregation belongs, look at what stays in Java, and then set the standards that keep the architecture from drifting again.

1How the Drift Happens

The usual story has three causes. First, object-relational mappers make it easy to load entities and hard to write custom aggregate queries, so developers load entities. Second, Java code is easier to unit test than SQL, so business rules migrate into Java to be testable. Third, data grows: a group-in-memory that handled 10,000 rows in the first year handles 5 million rows five years later, and nobody revisits it because it still works, just slowly.

Aggregation here means any computation that reduces many rows to fewer results: sums, counts, averages, top-N lists, group totals. The question is which component does that reduction.

2What Loading to Aggregate Really Costs

Let us put numbers on one example. A report needs revenue per region per month for a year: 20 regions times 12 months gives 240 result rows. The source table has 5 million order rows.

Java
-- In the database: the work happens next to the data
SELECT region, date_trunc('month', created_at) AS month, sum(amount)
FROM orders
WHERE created_at >= now() - interval '1 year'
GROUP BY region, month; -- 240 rows cross the network
// In Java: everything crosses the network first
List<Order> all = repo.findAllSince(oneYearAgo); // 5,000,000 entities
Map<RegionMonth, BigDecimal> totals = all.stream()
.collect(groupingBy(o -> new RegionMonth(o.region(), YearMonth.from(o.createdAt())),
reducing(BigDecimal.ZERO, Order::amount, BigDecimal::add)));

At even 200 bytes per row on the wire, the Java version moves about a gigabyte over the network, materialises 5 million entities on the heap, likely several gigabytes with ORM overhead, and creates garbage that the collector must clean up, all to produce 240 numbers. The database version reads the same rows but, with suitable indexes, does it next to the storage, in optimised native code, and returns kilobytes. The difference is usually one or two orders of magnitude in time and memory.

3Deciding Where an Aggregation Belongs

We decide by asking a few questions in order. How large is the input, and is it bounded? Large or growing inputs go to the data. Where does the data live? If it is in one database, that database can aggregate it. How fresh must the result be? Continuously updated totals, such as live counters over event streams, belong in a stream processor such as Kafka Streams or Flink, which maintain them incrementally instead of recomputing. Is it analytical, over history and across systems? Then a data warehouse is the right home. Only when the input is small and bounded, or already in memory, does Java aggregation win.

Step throughWhere should this aggregation run?
  1. Is the input large or unbounded?
    YesAggregate near the dataNoJava may be fine
  2. Continuously updated from events?
    YesStream processorNoCheck where the data lives
  3. Historical, across many systems?
    YesData warehouseNoDatabase query, view or materialized view
  4. Small, bounded and already loaded?
    YesJava streamsNoBack to the database

4 steps in order. Play them, or step through them one at a time.

Most aggregations over large data never need to reach the application heap.

4What Rightly Stays in Java

In-memory streams are the right tool when the data is bounded and already loaded for another reason. For example, the service has loaded one customer's 40 open orders to display them, and the page also shows totals per status; grouping those 40 orders in Java is cheaper and simpler than a second query. Another case is logic that is genuinely awkward in SQL, such as complex rules over small result sets that the database has already reduced.

The pattern to aim for is reduce first, then refine: let the database do the heavy reduction from millions of rows to thousands, and let Java apply the business logic to that small result.

5What I Would Standardise

Principles drift without enforcement, so I would turn them into a few concrete standards. A maximum number of rows a request may load into memory, for example 10,000 for online requests, enforced by a repository wrapper or query review, with exceptions approved and recorded in the design review. A rule that reports and dashboards over large tables use database aggregation, views or the warehouse. Monitoring that makes violations visible: rows fetched per request and heap allocation per endpoint as metrics, with alerts for outliers. And a review step in the architecture forum for any new service that aggregates over more than a set size.

Standards for aggregation
StandardExample valueEnforced by
Max rows loaded per online request10,000repository wrapper, review
Large reports and dashboardsSQL, views or warehousearchitecture review
Continuous totals over eventsstream processordesign review
Rows fetched and allocation per endpointmetrics with alertsobservability
Exceptions to the limitsapproved and recordedarchitecture forum

These limits work because they make the cost visible at design time instead of in production. The exceptions process matters as much as the limit: a team with a good reason gets an approved exception quickly, and we learn which cases our standards do not cover.

6Keeping Business Rules Testable in Every Layer

The legitimate reason logic moved into Java was testability, so the standard must keep rules testable wherever they run. For SQL, that means integration tests against a real database, for example with Testcontainers running the same PostgreSQL version as production, with small fixture data sets and expected results. Rules defined in views or queries live in version control with migrations, are reviewed like code, and have tests.

A useful technique when moving an aggregation from Java to SQL is to keep the Java version as a reference implementation in the tests: run both on the same generated data and assert that the results match. That catches subtle differences, such as rounding, time zones at month boundaries or null handling, before the change reaches production.

7Follow-up questions

Does pushing aggregation into the database just overload the database?

It can, which is why heavy analytical queries go to replicas or a warehouse rather than the primary. But the database does the reading in either case; the Java approach adds transfer and memory cost on top. Moving the reduction to the data almost always reduces total load.

What about microservices, where the data for one aggregation lives in several services?

That is a strong signal for a warehouse or a stream processor that collects events from all services, rather than one service calling the others and aggregating in memory. Cross-service in-memory aggregation is the drift problem in its most expensive form.

How do you deal with the existing services that already load large data sets?

Measure them first, using rows fetched and allocation per endpoint, and rank by cost. Fix the worst few by moving their aggregation to queries or the warehouse, with the old Java logic as a test oracle, and apply the standards to new code so the problem stops growing.

8Conclusion

In this answer, we saw how aggregation drifts from SQL into Java and what that costs: a 240-row report that moves a gigabyte and fills the heap with 5 million entities. Large aggregations belong near the data, in the database, a warehouse or a stream processor, while Java streams fit bounded data that is already loaded. We would standardise a row limit per request with recorded exceptions, use metrics to make violations visible, and keep business rules testable in every layer with real-database tests and reference implementations.

What to say in the interviewAbout 90 seconds aloud

Open with

My principle would be that aggregation over large data belongs close to the data. If a dashboard needs 240 numbers from 5 million rows, loading the rows into Java means a gigabyte over the network, millions of entities on the heap and a lot of GC work, while a GROUP BY next to the data returns kilobytes.

Then, if they want more

So I'd decide by a few questions: is the input large or growing, then aggregate near the data; is it continuously updated from events, then a stream processor like Kafka Streams or Flink; is it historical analytics across systems, then a warehouse; otherwise a database query, view or materialized view.

In-memory streams are right for bounded data that's already loaded for other reasons, like totals over the 40 orders we loaded to show a customer's page. The pattern is reduce in the database, refine in Java.

To stop the drift, I'd standardise a maximum number of rows a request can load, say 10,000 for online requests, enforced by a repository wrapper and review, with exceptions approved and recorded, plus metrics for rows fetched and allocation per endpoint so violations show up.

And since logic usually moved to Java for testability, I'd require that rules stay testable wherever they run: SQL tested with Testcontainers against the real database version, and when migrating, the old Java logic kept as a reference implementation in tests to compare results.

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.
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 "Over years, more aggregation logic moved from SQL into Java stream code, and some...": https://scrivio-interview-library.netlify.app/java/streams/2cd14474ff/