Video in progress

Should aggregation be done in Java with groupingBy or in SQL with GROUP BY? What rule do you set for the team?

The default: aggregate where the data is. For data in the database, SQL, because only the result comes over the network and indexes work. groupingBy in Java makes sense when the data is already in memory, comes from several sources, or the logic is too complex to express in SQL.

📖 Answer

The classic anti-pattern:

Map<Long, BigDecimal> totals = orderRepo.findAll().stream()
        .collect(groupingBy(Order::customerId,
                reducing(BigDecimal.ZERO, Order::amount, BigDecimal::add)));

On dev with 500 orders it's fast. On prod with 8 million, findAll turns the whole table into Hibernate entities, and the heap fills up or the query runs for minutes. The same thing in SQL:

select customer_id, sum(amount) from orders
where created_at >= :from
group by customer_id;

The database reads only the needed columns, can use an index, and a few thousand rows come over the network.

Cases where aggregating in Java makes sense:

  • the data is already in memory (a cache, the result of a previous step, a small reference table);
  • the result is gathered from several sources (two different services, DB + an external API);
  • the business logic is complex and changes fast: written in SQL it's hard to test and read;
  • you need to reduce load on the database, and the application layer scales while the database doesn't.

The last case matters at the staff level: sometimes the database is the most expensive and hardest-to-scale part of the system. Moving heavy aggregations to a read replica, an analytical database (ClickHouse) or a precomputed table (a materialized view refreshed overnight) works better than doing it in application memory.

As a rule for the team:

  1. findAll() + stream aggregation gets a "why?" in code review.
  2. Reporting queries use projections (interface CustomerTotal { Long getCustomerId(); BigDecimal getTotal(); }) or native SQL.
  3. If Java aggregation stays, put a volume limit and a test on it (say, at most 10,000 rows, otherwise an error).

The decision is each time based on data volume and its growth, not on "which looks nicer".