Quick revision
The short answer
A high rate of LazyInitializationException tells me the data access boundaries are unclear: entities leak out of their transactions into web, messaging and async code that assumes it can still navigate them. The systemic fix is a rule that services return DTOs and that fetch plans are defined per use case, OSIV disabled in the shared starter with the failures fixed in tests, examples and review checklists for fetch joins and entity graphs, and the error rate tracked as a quality metric across services.
What to remember
In this answer, we read a high LazyInitializationException rate as a sign that entities leak out of their transactions into web, messaging, async and caching code. The systemic fix is a rule that boundaries return DTOs with fetch plans per use case, a shared starter that disables OSIV and keeps lazy loading outside transactions off, examples and a review checklist, and the error rate tracked as a quality metric until it reaches zero.
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.
A high rate of LazyInitializationException tells me the data access boundaries are unclear: entities leak out of their transactions into web, messaging and async code that assumes it can still navigate them. The systemic fix is a rule that services return DTOs and that fetch plans are defined per use case, OSIV disabled in the shared starter with the failures fixed in tests, examples and review checklists for fetch joins and entity graphs, and the error rate tracked as a quality metric across services.
Why this question is asked
When one exception type tops the error dashboards of most services, fixing each occurrence is like mopping the floor under a leaking pipe. Each fix is small, but new occurrences keep arriving, because the code keeps being written the same way. Interviewers ask this leadership question to see whether we can read an error pattern as a signal about architecture and change the conditions that produce it, across teams that each own their own code. In this answer, we will interpret what the exception says, set the rules that remove its cause, use a shared starter to make the right default automatic, support teams with examples and review, and measure progress.
1What the Exception Is Really Telling Us
LazyInitializationException is thrown when code touches a lazy association, a proxy or collection that loads on first access, after the persistence context, the session that could load it, has closed. That always means one thing: an entity has travelled beyond the transaction in which it was loaded, and code out there assumed it could still reach the database through it.
Look at where the stack traces point. Some come from controllers and JSON serialization, where an entity was returned directly. Some come from Kafka or RabbitMQ listeners that receive an entity from a service and pass it on. Some come from @Async methods and CompletableFuture tasks, which run on another thread with no session at all. And some come from caches holding entities that are read later. Each is a place where the boundary between data access and the rest of the system is blurry. So the error rate is a measure of how often our entities leak.
| Leak | Typical trace location | Why no session |
|---|---|---|
| Entity returned from controller | Jackson serializer | transaction ended in service |
| Entity passed to async task | @Async method, executor thread | new thread, no persistence context |
| Entity in a message or event | listener or event handler | different transaction or none |
| Entity cached | cache read later | loaded in an old, closed session |
| Entity to a template | view rendering | OSIV disabled or not a web request |
2The Rules That Remove the Cause
Two rules address the cause directly. The first: service methods that cross a boundary, to the web layer, to messaging, to another thread or to a cache, return DTOs, plain immutable objects built inside the transaction, never entities. A DTO has no lazy associations, so nothing can fail later. The second: each use case defines its fetch plan, the associations it needs, in the repository with a fetch join, an entity graph or a projection, so that building the DTO does not itself cause N+1.
With both rules in place, the exception becomes nearly impossible to write by accident: entities exist only inside transactional service methods, and they leave as DTOs.
The event published to Kafka carries data, not a live entity, so the listener on the other side never touches a closed session.
3Making the Right Default Automatic
Most organisations with many services have a shared Spring Boot starter, an internal library that sets common defaults. That is the place to set spring.jpa.open-in-view=false, so every service runs without open session in view, which otherwise hides leaks into the web layer by keeping the session open during rendering. The starter can also set a sensible hibernate.default_batch_fetch_size and make sure hibernate.enable_lazy_load_no_trans stays off, since that setting hides the exception by opening a new session for every lazy access.
Turning OSIV off will expose failures in services that relied on it. So each service adopts the new starter version with its integration tests run first, and fixes the failures they reveal with fetch plans and DTOs. Teams that need longer get a documented, temporary override with an end date, rather than a silent exception.
- Team codeservices return DTOs, fetch plans per use case
- Review checklist and examplesfetch joins, entity graphs, projections
- Shared starterOSIV off, batch size set, no_trans off
- Metrics
LazyInitializationExceptionrate per service
4 layers, from the top down. Step through them one at a time.
4Supporting Teams With Examples and Review
Rules without examples produce workarounds. So the platform or a small guild provides a short guide with real before-and-after examples from our own services: a controller returning an entity turned into a DTO, a listener receiving an id and loading what it needs, an async task given a DTO instead of an entity, and a list screen fixed with a fetch join and a statement-count test. Pairing with a team on its first fix spreads the habit faster than documents do.
Code review gets a checklist item: does any entity cross a transaction boundary, and does each new query state its fetch plan? Reviewers who see Hibernate.initialize in a loop or a new EAGER mapping know to ask. An ArchUnit rule can help too, for example flagging controller methods or listener methods whose return or parameter types are entity classes.
5Measuring Progress
Finally, the error rate itself becomes a quality metric. Each service's LazyInitializationException count per day, from the error tracking or log platform, goes on a shared dashboard next to statements per request. The goal is not a ranking of teams but a visible trend: after the starter change, the count typically rises briefly as hidden problems appear in testing, then falls steadily as they are fixed. A target such as zero occurrences in production for the top twenty services within two quarters gives the effort a clear end.
If one service keeps producing the error, the dashboard shows it, and it is a prompt for help rather than blame: usually that team has a pattern, such as entities in messages, that the guide does not cover yet, and fixing it improves the guide for everyone.
6Follow-up questions
Why not just enable OSIV everywhere and be done with it?
Because OSIV only covers web requests and hides the leak instead of removing it. Async tasks, listeners and caches would still fail, and the web layer would run N+1 queries during serialization while holding a database connection for the whole request. It moves the cost around rather than fixing the boundary.
How do you handle async processing that needs entity data?
Pass an id or a DTO to the async task, never an entity. If the task needs more data, it opens its own transaction and loads it with a fetch plan for its own use case. That also avoids sharing a non-thread-safe persistence context across threads.
Is the DTO rule too much ceremony for small services?
Records make DTOs very cheap: one line per type. The cost is a little mapping code, and the benefit is that the API, events and caches are independent of the persistence model. For small services that is still a good trade.
7Conclusion
In this answer, we read a high LazyInitializationException rate as a sign that entities leak out of their transactions into web, messaging, async and caching code. The systemic fix is a rule that boundaries return DTOs with fetch plans per use case, a shared starter that disables OSIV and keeps lazy loading outside transactions off, examples and a review checklist, and the error rate tracked as a quality metric until it reaches zero.
Open with
To me that error rate is a signal about architecture, not a run of bad luck. The exception happens when code touches a lazy association after the session that loaded the entity has closed, so every occurrence means an entity escaped its transaction: returned from a controller and serialized by Jackson, passed to an async task on another thread, put into a message or an event, or cached and read later.
Then, if they want more
So the codebase has unclear data access boundaries.
The systemic fix starts with two rules: anything that crosses a boundary, to the web, messaging, another thread or a cache, is a DTO built inside the transaction, never an entity; and each use case defines its fetch plan in the repository with a fetch join, an entity graph or a projection, so building the DTO is efficient.
Then I would make the right default automatic in our shared starter: open-in-view off, a sensible batch fetch size, and enable_lazy_load_no_trans kept off. Services adopt it with their integration tests run first and fix the failures they reveal, with time-boxed overrides where needed.
I would back it with a short guide of real before-and-after examples, pairing, and a review checklist item about entities crossing boundaries. And I would track the exception rate per service as a quality metric on a shared dashboard, aiming for zero in production on the top services within two quarters.
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
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
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 "LazyInitializationException is one of the most common production errors across your...": https://scrivio-interview-library.netlify.app/databases/jpa-performance/49dd90bb2c/