Video in progress
You need to recalculate 10 million rows overnight. When is it right to give up rich domain objects and the ORM?
A domain model is built for decisions about one or a few objects. In bulk processing (batch, migration, reporting), loading every row into an object, calling a method and saving is very expensive in both memory and time. For that, set-level SQL or streaming is right, but the business rule must not end up duplicated in two places.
📖 Answer
The usual first attempt:
for (Subscription s : subscriptionRepo.findAll()) { // 10 million entities into memory
s.recalculatePrice(tariffs);
} // flush: 10 million UPDATEs
The result: OutOfMemoryError, or dirty checking in the persistence context runs for hours.
The options, in order of speed:
- A single SQL statement, if the rule is simple:
UPDATE subscription SET price = ... WHERE tariff_id = ?. Seconds. But the rule is now in SQL, so you have two copies together with the rule in Java. - Chunks, with objects, if the rule is complex and has to stay in the domain code: read 1000 at a time (keyset pagination), call the domain method, write with JDBC batch, and call
EntityManager.clear()after each chunk. Spring Batch gives you this template. - Projection + a pure function: instead of the entity, read only the needed columns into a record and call the rule as a stateless function:
static Money price(TariffSnapshot t, UsageSnapshot u) { ... } // a domain rule, no ORM
That way one rule is used both online (inside the aggregate) and in batch.
How I decide: I weigh how complex the rule is and the risk of duplication. The third option is often the best balance: the rule is in one place (a pure function in the domain module), while loading and saving are optimized for batch.
There is one catch: don't bypass invariants in batch. If you update with SQL, domain events aren't emitted and caches go stale, so you have to handle that deliberately (for example, clear the cache at the end or emit a "bulk recalculated" event).
Sign up to mark studied questions and save your progress.