Scrivio Interview library
LeadershipAdvanced6 min read · updated 12 November 2026

Your organisation's JPA entities were written with EAGER fetching everywhere ten years ago, and each change risks performance regressions. How would you plan the move to lazy-by-default across many teams?

I would first add statement-count tests to the key use cases so that any regression is visible, then switch associations to LAZY one aggregate at a time, adding fetch joins or entity graphs where the tests or production show the data is needed. The plan must expect LazyInitializationException in code that relied on eager loading outside transactions, and include disabling open session in view. Production SQL metrics decide which aggregates go first, and once proven, lazy-by-default becomes a standard enforced in review.

Why this question is asked

An EAGER-everywhere model is like a building where every room is wired to every other: nothing can be changed without something unexpected happening elsewhere. After ten years, teams are afraid to touch the entities, performance problems are fixed with caches instead of at the source, and new features inherit the slowness. Changing fetch types is technically a one-line edit per association, but done all at once it breaks code across many teams. Interviewers ask this leadership question to see whether we can turn a risky, cross-team change into a controlled programme. In this answer, we will look at why the change is risky, how to make regressions visible first, how to sequence the work, how to handle the failures it exposes, and how to keep the new standard in place.

1Why a Simple Change Is Risky

Switching @ManyToOne(fetch = EAGER) to LAZY changes behaviour in two directions. Some code becomes faster, because data it never used is no longer loaded. Other code becomes slower or breaks. If a service loads 100 orders and then reads each order's customer, the customers used to arrive with the orders, often in a join, and now each one triggers a separate select, a classic N+1. And code that reads an association after the transaction has ended, in a controller, a scheduled job or an async task, used to work because the data was already loaded, and now throws LazyInitializationException.

Neither effect shows up at compile time, and in a ten-year-old codebase nobody knows every place that relies on eager data. That is why the plan starts with visibility, not with the change.

2Make Regressions Visible

Before touching any mapping, we add statement-count tests around the most important use cases: the order list, the checkout, the nightly invoice job. Each test runs the use case against a real database, usually with Testcontainers, counts SQL statements through Hibernate statistics or datasource-proxy, and asserts the current number. These tests do not judge the numbers; they record them, so any change is noticed.

Java
@Test
void orderListPage_statementCount() {
stats.clear();
orderService.listOpenOrders(PageRequest.of(0, 50));
assertThat(stats.getPrepareStatementCount()).isEqualTo(3); // today's baseline, written down
}

In parallel, we collect production numbers: statements per request, slow queries, and which entities load most often, from database statistics such as pg_stat_statements and from tracing. These tell us where the eager graph hurts most, which decides the order of the work.

3Switch One Aggregate at a Time

An aggregate is a cluster of entities treated as a unit, such as Order with its lines and payments. We take the aggregate with the worst production numbers, switch all its associations to LAZY in one change, and run the tests. Tests that now show more statements or fail with LazyInitializationException point exactly at code that needs a fetch plan, which we add with a join fetch, an entity graph or a DTO query. Then we release, watch the production metrics for that aggregate for a week, and move on to the next.

Doing it per aggregate keeps each change small enough to review and roll back, and it lets one team own each step. A cross-team guild or a small enabling team can help with the first few aggregates and write down the patterns, so later teams copy rather than reinvent.

Step throughThe loop for each aggregate
  1. Pick the worst aggregatefrom production SQL metrics
  2. Baseline statement-count testsfor its key use cases
  3. Switch associations to LAZYone change per aggregate
  4. Tests fail or counts rise?
    YesAdd fetch joins, graphs or DTOsNoRelease
  5. Release and watch metricsa week of production numbers
  6. Next aggregate

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

4Handle LazyInitializationException and OSIV

Many old codebases run with open session in view, Spring Boot's spring.jpa.open-in-view, which is enabled by default and keeps the persistence context open until the web response is written. With it, lazy loads in controllers and JSON serialization still succeed, so the switch to LAZY moves queries into the view layer instead of exposing the missing fetch plans. That hides exactly the problems the programme is supposed to fix.

So the plan includes disabling OSIV, ideally per service as part of its first aggregate, and fixing the failures it reveals by fetching the data inside the service and returning DTOs. Code outside web requests, such as jobs and message listeners, never had OSIV, so it is the place to look for exceptions first. We should agree in advance that the fix is a fetch plan, never going back to EAGER or enabling hibernate.enable_lazy_load_no_trans, which opens a new session for every lazy access.

5Make It the Standard

Once two or three aggregates have moved and the metrics show the benefit, for example the order list dropping from 120 statements to 3 and p95 latency halving, we have the evidence to make lazy-by-default a standard. The standard says that every association declares fetch = LAZY explicitly, that each use case defines its fetch plan in the repository, and that new code adds a statement-count test for its main paths.

Enforcement is cheap: a review checklist item, and an ArchUnit or reflection test that fails if any @ManyToOne or @OneToOne lacks an explicit LAZY. A dashboard of remaining eager associations per service keeps the progress visible to engineering leadership, which matters when the programme runs for several quarters.

A typical programme timeline
QuarterFocusEvidence
1count tests, metrics, first aggregatebaseline numbers, first win
2three worst aggregates, OSIV off in two servicesstatements per request down
3remaining aggregates, standard agreedeager association count falling
4enforced by checks, long tailregressions caught in tests

6Follow-up questions

How do you convince teams to spend time on this instead of features?

With their own numbers. Show the statements per request for their slowest screen, the incidents caused by it, and the result from the first aggregate. Framing it as reducing incident load and making future changes safe usually lands better than framing it as clean code.

What if a team cannot finish its aggregate in time?

The per-aggregate design means partial progress is still safe. Unfinished aggregates stay EAGER, the standard applies to new code, and the dashboard shows where the remaining work is. Nothing depends on a big-bang switch.

Would you add a global batch fetch size during the migration?

Yes, hibernate.default_batch_fetch_size around 16 to 50 is a good safety net: it turns many N+1 cases created by the switch into a few IN queries. But it is a net, not a fix, so hot paths still get explicit fetch plans.

7Conclusion

In this answer, we planned the move from EAGER to lazy-by-default as a controlled programme: statement-count tests and production metrics first, then one aggregate at a time with fetch joins and entity graphs added where tests show the need, OSIV disabled and lazy loading failures fixed with fetch plans and DTOs, and finally a standard enforced by review and automated checks.

What to say in the interviewAbout 90 seconds aloud

Open with

I would treat it as a programme, not a refactoring. The risk is that switching to LAZY causes N+1 queries in code that used the associations and LazyInitializationException in code that read them outside a transaction, and none of that shows at compile time.

Then, if they want more

So first I make regressions visible: statement-count tests on the key use cases, using Hibernate statistics or datasource-proxy against a real database, recording today's numbers. I would also use production SQL metrics, from pg_stat_statements and tracing, to rank aggregates by how much the eager graph costs.

Then we switch one aggregate at a time, all its associations to LAZY, and use the failing tests to add fetch joins, entity graphs or DTO queries where data is really needed, release, and watch metrics before moving on.

OSIV must be part of the plan, because with open-in-view enabled the lazy loads just move into the web layer, so we disable it per service and fix failures by fetching in the service and returning DTOs, never by going back to EAGER or enabling lazy loading without a transaction.

A global batch fetch size is a good safety net meanwhile. Once the first aggregates show the gain, we agree lazy-by-default as a standard, enforced in review and by an automated check that every to-one association declares LAZY.

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 "Your organisation's JPA entities were written with EAGER fetching everywhere ten years...": https://scrivio-interview-library.netlify.app/databases/jpa-performance/ec92f55596/