liveBook · Manning

Lazy initialization

As explained in Grokking Software Architecture

Lazy loading is a loading strategy that retrieves related data only when the application first accesses it.

Lazy loading retrieves related data when code first accesses a navigation property, such as person.Address. That convenient-looking property read can secretly send a database query across the network. section 8.3.2

The convenience has production costs:

  • A slow network or exhausted connection pool can make a simple property access stall a request and end in a timeout. section 8.3.2
  • Accessing user.Orders in a loop over 1,000 users can issue 1,000 extra queries after the initial query—the N+1 problem. section 8.3.2
  • For performance-critical paths, make data access explicit: use eager loading or DTO queries to fetch the needed object graph together. section 8.3.2
Figure 8.7 The N+1 Problem: Fetching data in a loop is like making a separate trip to the kitchen for every single french fry. Always fetch in batches!

The kitchen-trip analogy illustrates why fetching related data one item at a time creates unnecessary round-trips. section 8.3.2

How Grokking Software Architecture covers it

How deep it goes
Traces hidden queries through timeouts and N+1 failures, then recommends explicit fetching without detailing its implementation.
Examples
Uses person.Address and user.Orders in a 1,000-user loop to illustrate hidden and repeated queries.
What you can do after
Diagnose hidden database I/O and avoid lazy loading in performance-critical paths by fetching data explicitly.
How it connects
Connects ORM navigation properties with eager loading, DTO queries, and the N+1 query problem.

Also explained in

Compare how 12 books explain lazy initialization →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Software Architecture. The section links point to the parts of the book it draws on.