intermediate

Lazy vs eager loading

Choose when related data loads on demand or upfront, and account for query count, memory, and serialization boundaries.

Lazy loading fetches related data when first accessed. Eager loading (join, include, preload) fetches relationships upfront. Choice depends on request shape, cardinality, serialization, and memory.

| Strategy | Pays off when | Risk | |----------|---------------|------| | Lazy | Relationship rarely used | N+1, queries after transaction closed | | Eager | Relationship always needed in response | Over-fetch, wide joins, memory |

On interviews: connect loading strategy to N+1 prevention, API DTO shape, and boundaries between persistence models and response objects.

Common pitfalls: lazy loading during JSON serialization; eager loading broad graphs nobody uses; loading inside loops without batching.

The trade-off is query count and latency versus memory and response size.

Checklist:

  • Know relationship cardinality.
  • Measure query count per endpoint.
  • Map loaded data to response needs.
  • Prefer explicit includes over implicit lazy access.