Programming Search⌘K

Patterncore

Lazy Load

Also called lazy load pattern, lazy loading, deferred loading.

A Lazy Load is an object that does not hold all of its data yet but knows how to get it, so a related object is read from the database only when the program first uses it.

Family
architectural
Intent
An object that doesn't contain all of the data you need but knows how to get it.
Also called
deferred loading

Intent

A Lazy Load is "An object that doesn't contain all of the data you need but knows how to get it."1 The program loads an object without its related objects. The first time the program asks for a related object, the Lazy Load reads it from the database.

Problem

An order refers to a customer, the customer refers to an address and to other orders, and each of these refers to more objects. It is convenient to load the related objects together with the object of interest, because then the caller does not have to load each one explicitly. But Fowler warns that "if you take this to its logical conclusion, you reach the point where loading one object can have the effect of loading a huge number of related objects - something that hurts performance when only a few of the objects are actually needed."1

The program must decide, for each association, when to read it. Loading everything at once wastes queries and memory. Making each caller load the related objects by hand puts database code into the domain logic.

Solution

"A Lazy Load interrupts this loading process for the moment, leaving a marker in the object structure so that if the data is needed it can be loaded only when it is used."1 The object keeps the key of the related row, and a field or an object that stands for the related object. On first use, that stand-in runs the query and keeps the result.

  client                 Order 10 (loaded)                  database
  order.total    ----->  total = 30, no SELECT
  order.customer ----->  _customer is None (the marker)
                           SELECT ... FROM customer WHERE id = 1  --->  (1, Ann, Oslo)
                           _customer = Customer(1, Ann, Oslo)
  order.customer ----->  _customer is set: return it, no SELECT

The participants are the owner, the object that the program loaded, such as an order; the marker or stand-in for the related object; and the loader, the code that knows the key and the query.

Fowler names four varieties:12

  • Lazy initialization. It "uses a special marker value (usually null) to indicate a field isn't loaded. Every access to the field checks the field for the marker value and if unloaded, loads it."1
  • Virtual proxy. It "is an object with the same interface as the real object. The first time one of its methods are called it loads the real object and then delegates."1 See Proxy pattern.
  • Value holder. It "is an object with a getValue method. Clients call getValue to get the real object, the first call triggers the load."1
  • Ghost. It "is the real object without any data. The first time you call a method the ghost loads the full data into its fields."1

The following program uses lazy initialization on SQLite. It traces each SQL statement. Finding the order runs one SELECT. Reading order.total runs none. The first read of order.customer runs one more, and the second read runs none.

import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table customer (id integer primary key, name text, city text);
create table orders (id integer primary key, customer_id integer, total integer);
insert into customer values (1, 'Ann', 'Oslo'), (2, 'Bo', 'Rome');
insert into orders values (10, 1, 30), (11, 2, 45), (12, 1, 20);
""")
selects = []
db.set_trace_callback(selects.append)


class Customer:
    def __init__(self, id, name, city):
        self.id, self.name, self.city = id, name, city


class Order:
    def __init__(self, id, customer_id, total):
        self.id, self.customer_id, self.total = id, customer_id, total
        self._customer = None  # The marker: the customer is not loaded yet.

    @property
    def customer(self):
        if self._customer is None:
            sql = "select id, name, city from customer where id = ?"
            self._customer = Customer(*db.execute(sql, (self.customer_id,)).fetchone())
        return self._customer


def find_order(id):
    sql = "select id, customer_id, total from orders where id = ?"
    return Order(*db.execute(sql, (id,)).fetchone())


order = find_order(10)
print("find_order(10) | selects:", len(selects))
print("total:", order.total, "| selects:", len(selects))
print("customer:", order.customer.name, "| selects:", len(selects))
print("again:", order.customer.city, "| selects:", len(selects))
Output
find_order(10) | selects: 1
total: 30 | selects: 1
customer: Ann | selects: 2
again: Oslo | selects: 2

Example

Each example file loads the customer of an order in the four ways that Fowler names: lazy initialization, a virtual proxy, a value holder and a ghost. Each line prints the number of SELECT statements before and after the first use, and after a second use. The proxy and the ghost answer the key without a query, because they hold it from the start. The last two lines show the cost of a Lazy Load in a loop: three orders and their customers take four statements with lazy loading and one statement with a join. The Python file uses SQLite. The JavaScript, Java, Go and Rust files keep the tables in memory and count each call that stands for a SELECT.

PythonGitHub
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table customer (id integer primary key, name text, city text);
create table orders (id integer primary key, customer_id integer);
insert into customer values (1, 'Ann', 'Oslo'), (2, 'Bo', 'Rome');
insert into orders values (10, 1), (11, 2), (12, 1);
""")
selects = []
db.set_trace_callback(selects.append)


def select_customer(id):
    sql = "select name, city from customer where id = ?"
    return db.execute(sql, (id,)).fetchone()


class Customer:
    def __init__(self, id, name, city):
        self.id, self.name, self.city = id, name, city


# 1. Lazy initialization: a marker value (None) means "not loaded".
class Order:
    def __init__(self, id, customer_id):
        self.id, self.customer_id, self._customer = id, customer_id, None

    @property
    def customer(self):
        if self._customer is None:
            self._customer = Customer(self.customer_id, *select_customer(self.customer_id))
        return self._customer


# 2. Virtual proxy: it looks like a Customer and loads the real one on first use.
class CustomerProxy:
    def __init__(self, id):
        self.id, self._real = id, None

    def __getattr__(self, attr):  # Called only for attributes that the proxy lacks.
        if self._real is None:
            self._real = Customer(self.id, *select_customer(self.id))
        return getattr(self._real, attr)


# 3. Value holder: the client asks the holder for the value.
class ValueHolder:
    def __init__(self, loader):
        self._loader, self._value, self._loaded = loader, None, False

    def get_value(self):
        if not self._loaded:
            self._value, self._loaded = self._loader(), True
        return self._value


# 4. Ghost: the real class, with only the key filled in until first use.
class GhostCustomer:
    def __init__(self, id):
        self.id, self._loaded = id, False

    def _load(self):
        if not self._loaded:
            self._name, self._city = select_customer(self.id)
            self._loaded = True

    @property
    def name(self):
        self._load()
        return self._name

    @property
    def city(self):
        self._load()
        return self._city


selects.clear()
order = Order(10, 1)
line = f"lazy initialization: selects {len(selects)} | {order.customer.name}"
line += f" | selects {len(selects)} | {order.customer.name} | selects {len(selects)}"
print(line)

selects.clear()
proxy = CustomerProxy(2)
line = f"virtual proxy: id {proxy.id} | selects {len(selects)} | {proxy.name}"
print(line + f" | selects {len(selects)} | {proxy.city} | selects {len(selects)}")

selects.clear()
holder = ValueHolder(lambda: Customer(1, *select_customer(1)))
print(f"value holder: selects {len(selects)} | {holder.get_value().name} | selects {len(selects)}")

selects.clear()
ghost = GhostCustomer(1)
line = f"ghost: id {ghost.id} | selects {len(selects)} | {ghost.name} {ghost.city}"
print(line + f" | selects {len(selects)}")

selects.clear()
orders = [Order(*row) for row in db.execute("select id, customer_id from orders order by id")]
names = ", ".join(o.customer.name for o in orders)
print(f"lazy: {names} | selects {len(selects)}")

selects.clear()
sql = "select name from orders join customer on customer.id = orders.customer_id order by orders.id"
names = ", ".join(name for (name,) in db.execute(sql))
print(f"eager: {names} | selects {len(selects)}")
Output
lazy initialization: selects 0 | Ann | selects 1 | Ann | selects 1
virtual proxy: id 2 | selects 0 | Bo | selects 1 | Rome | selects 1
value holder: selects 0 | Ann | selects 1
ghost: id 1 | selects 0 | Ann Oslo | selects 1
lazy: Ann, Bo, Ann | selects 4
eager: Ann, Bo, Ann | selects 1
  • Verdict: idiom. Lazy initialization is a property over a field that starts as None. The virtual proxy uses __getattr__, which Python calls only for attributes that the proxy does not have, so proxy.id needs no query and proxy.name loads the real customer.
  • The file uses SQLite, and the trace callback counts the statements. functools.cached_property could replace the hand-written check in Order.customer.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Supplier;

public class Main {
    // A stand-in for the database: the tables and a count of SELECT statements.
    static final Map<Integer, String[]> CUSTOMERS = Map.of(1, new String[] {"Ann", "Oslo"}, 2, new String[] {"Bo", "Rome"});
    static final int[][] ORDERS = {{10, 1}, {11, 2}, {12, 1}};
    static int selects = 0;

    static String[] selectCustomer(int id) {
        selects++;
        return CUSTOMERS.get(id);
    }

    interface Customer {
        int id();
        String name();
        String city();
    }

    record RealCustomer(int id, String name, String city) implements Customer {
        static RealCustomer load(int id) {
            String[] row = selectCustomer(id);
            return new RealCustomer(id, row[0], row[1]);
        }
    }

    // 1. Lazy initialization: a marker value (null) means "not loaded".
    static class Order {
        final int id;
        final int customerId;
        private Customer customer = null;

        Order(int id, int customerId) {
            this.id = id;
            this.customerId = customerId;
        }

        Customer customer() {
            if (customer == null) customer = RealCustomer.load(customerId);
            return customer;
        }
    }

    // 2. Virtual proxy: it implements Customer and loads the real one on first use.
    static class CustomerProxy implements Customer {
        private final int id;
        private Customer real = null;

        CustomerProxy(int id) {
            this.id = id;
        }

        private Customer real() {
            if (real == null) real = RealCustomer.load(id);
            return real;
        }

        public int id() { return id; }
        public String name() { return real().name(); }
        public String city() { return real().city(); }
    }

    // 3. Value holder: the client asks the holder for the value.
    static class ValueHolder<T> {
        private final Supplier<T> loader;
        private boolean loaded = false;
        private T value;

        ValueHolder(Supplier<T> loader) {
            this.loader = loader;
        }

        T getValue() {
            if (!loaded) {
                value = loader.get();
                loaded = true;
            }
            return value;
        }
    }

    // 4. Ghost: the real class, with only the key filled in until first use.
    static class GhostCustomer implements Customer {
        private final int id;
        private String name;
        private String city;
        private boolean loaded = false;

        GhostCustomer(int id) {
            this.id = id;
        }

        private void load() {
            if (!loaded) {
                String[] row = selectCustomer(id);
                name = row[0];
                city = row[1];
                loaded = true;
            }
        }

        public int id() { return id; }
        public String name() { load(); return name; }
        public String city() { load(); return city; }
    }

    public static void main(String[] args) {
        selects = 0;
        Order order = new Order(10, 1);
        String line = "lazy initialization: selects " + selects + " | " + order.customer().name();
        System.out.println(line + " | selects " + selects + " | " + order.customer().name() + " | selects " + selects);

        selects = 0;
        Customer proxy = new CustomerProxy(2);
        line = "virtual proxy: id " + proxy.id() + " | selects " + selects + " | " + proxy.name();
        System.out.println(line + " | selects " + selects + " | " + proxy.city() + " | selects " + selects);

        selects = 0;
        ValueHolder<Customer> holder = new ValueHolder<>(() -> RealCustomer.load(1));
        System.out.println("value holder: selects " + selects + " | " + holder.getValue().name() + " | selects " + selects);

        selects = 0;
        Customer ghost = new GhostCustomer(1);
        line = "ghost: id " + ghost.id() + " | selects " + selects + " | " + ghost.name() + " " + ghost.city();
        System.out.println(line + " | selects " + selects);

        selects = 1; // One SELECT reads the orders.
        List<String> names = new ArrayList<>();
        for (int[] row : ORDERS) names.add(new Order(row[0], row[1]).customer().name());
        System.out.println("lazy: " + String.join(", ", names) + " | selects " + selects);

        selects = 1; // One SELECT with a JOIN reads the orders and their customers.
        names.clear();
        for (int[] row : ORDERS) names.add(CUSTOMERS.get(row[1])[0]);
        System.out.println("eager: " + String.join(", ", names) + " | selects " + selects);
    }
}
Output
lazy initialization: selects 0 | Ann | selects 1 | Ann | selects 1
virtual proxy: id 2 | selects 0 | Bo | selects 1 | Rome | selects 1
value holder: selects 0 | Ann | selects 1
ghost: id 1 | selects 0 | Ann Oslo | selects 1
lazy: Ann, Bo, Ann | selects 4
eager: Ann, Bo, Ann | selects 1
  • Verdict: idiom. Customer is an interface, so RealCustomer, CustomerProxy and GhostCustomer can stand in for one another. The value holder takes a Supplier.
  • A Map stands in for the customer table, and selectCustomer counts the statements. Java evaluates the parts of a string concatenation from left to right, so each line shows the count before and after the load.
JavaScriptGitHub
// A stand-in for the database, because Node has no SQL driver in its standard library.
const customerTable = new Map([[1, ["Ann", "Oslo"]], [2, ["Bo", "Rome"]]]);
const orderTable = [[10, 1], [11, 2], [12, 1]];
let selects = 0;

function selectCustomer(id) {
  selects++;
  return customerTable.get(id);
}

class Customer {
  constructor(id, name, city) {
    Object.assign(this, { id, name, city });
  }
}

// 1. Lazy initialization: a marker value (null) means "not loaded".
class Order {
  #customer = null;
  constructor(id, customerId) {
    Object.assign(this, { id, customerId });
  }
  get customer() {
    this.#customer ??= new Customer(this.customerId, ...selectCustomer(this.customerId));
    return this.#customer;
  }
}

// 2. Virtual proxy: a Proxy object that loads the real customer on first use.
function customerProxy(id) {
  let real = null;
  return new Proxy({ id }, {
    get(target, prop) {
      if (prop === "id") return target.id;
      real ??= new Customer(id, ...selectCustomer(id));
      return real[prop];
    },
  });
}

// 3. Value holder: the client asks the holder for the value.
class ValueHolder {
  #loader;
  #loaded = false;
  #value;
  constructor(loader) {
    this.#loader = loader;
  }
  getValue() {
    if (!this.#loaded) {
      this.#value = this.#loader();
      this.#loaded = true;
    }
    return this.#value;
  }
}

// 4. Ghost: the real class, with only the key filled in until first use.
class GhostCustomer {
  #name;
  #city;
  #loaded = false;
  constructor(id) {
    this.id = id;
  }
  #load() {
    if (!this.#loaded) {
      [this.#name, this.#city] = selectCustomer(this.id);
      this.#loaded = true;
    }
  }
  get name() {
    this.#load();
    return this.#name;
  }
  get city() {
    this.#load();
    return this.#city;
  }
}

selects = 0;
const order = new Order(10, 1);
let line = `lazy initialization: selects ${selects} | ${order.customer.name}`;
console.log(`${line} | selects ${selects} | ${order.customer.name} | selects ${selects}`);

selects = 0;
const proxy = customerProxy(2);
line = `virtual proxy: id ${proxy.id} | selects ${selects} | ${proxy.name}`;
console.log(`${line} | selects ${selects} | ${proxy.city} | selects ${selects}`);

selects = 0;
const holder = new ValueHolder(() => new Customer(1, ...selectCustomer(1)));
console.log(`value holder: selects ${selects} | ${holder.getValue().name} | selects ${selects}`);

selects = 0;
const ghost = new GhostCustomer(1);
console.log(`ghost: id ${ghost.id} | selects ${selects} | ${ghost.name} ${ghost.city} | selects ${selects}`);

selects = 1; // One SELECT reads the orders.
const orders = orderTable.map(([id, customerId]) => new Order(id, customerId));
console.log(`lazy: ${orders.map((o) => o.customer.name).join(", ")} | selects ${selects}`);

selects = 1; // One SELECT with a JOIN reads the orders and their customers.
const names = orderTable.map(([, customerId]) => customerTable.get(customerId)[0]);
console.log(`eager: ${names.join(", ")} | selects ${selects}`);
Output
lazy initialization: selects 0 | Ann | selects 1 | Ann | selects 1
virtual proxy: id 2 | selects 0 | Bo | selects 1 | Rome | selects 1
value holder: selects 0 | Ann | selects 1
ghost: id 1 | selects 0 | Ann Oslo | selects 1
lazy: Ann, Bo, Ann | selects 4
eager: Ann, Bo, Ann | selects 1
  • Verdict: idiom. Lazy initialization is a getter over a private field with ??=. The virtual proxy is a built-in Proxy with a get trap, so the caller cannot tell it from a Customer.
  • Node has no SQL driver in its standard library, so a Map stands in for the customer table and selectCustomer counts the statements.
package main

import (
	"fmt"
	"strings"
)

// A stand-in for the database: the tables and a count of SELECT statements.
var customerTable = map[int][2]string{1: {"Ann", "Oslo"}, 2: {"Bo", "Rome"}}
var orderTable = [][2]int{{10, 1}, {11, 2}, {12, 1}}
var selects = 0

func selectCustomer(id int) [2]string {
	selects++
	return customerTable[id]
}

type Customer interface {
	ID() int
	Name() string
	City() string
}

type realCustomer struct {
	id         int
	name, city string
}

func (c *realCustomer) ID() int      { return c.id }
func (c *realCustomer) Name() string { return c.name }
func (c *realCustomer) City() string { return c.city }

func loadCustomer(id int) *realCustomer {
	row := selectCustomer(id)
	return &realCustomer{id, row[0], row[1]}
}

// 1. Lazy initialization: a marker value (nil) means "not loaded".
type Order struct {
	ID, CustomerID int
	customer       Customer
}

func (o *Order) Customer() Customer {
	if o.customer == nil {
		o.customer = loadCustomer(o.CustomerID)
	}
	return o.customer
}

// 2. Virtual proxy: it implements Customer and loads the real one on first use.
type customerProxy struct {
	id   int
	real Customer
}

func (p *customerProxy) load() Customer {
	if p.real == nil {
		p.real = loadCustomer(p.id)
	}
	return p.real
}

func (p *customerProxy) ID() int      { return p.id }
func (p *customerProxy) Name() string { return p.load().Name() }
func (p *customerProxy) City() string { return p.load().City() }

// 3. Value holder: the client asks the holder for the value.
type ValueHolder[T any] struct {
	loader func() T
	loaded bool
	value  T
}

func (h *ValueHolder[T]) GetValue() T {
	if !h.loaded {
		h.value, h.loaded = h.loader(), true
	}
	return h.value
}

// 4. Ghost: the real type, with only the key filled in until first use.
type ghostCustomer struct {
	id         int
	name, city string
	loaded     bool
}

func (g *ghostCustomer) load() {
	if !g.loaded {
		row := selectCustomer(g.id)
		g.name, g.city, g.loaded = row[0], row[1], true
	}
}

func (g *ghostCustomer) ID() int      { return g.id }
func (g *ghostCustomer) Name() string { g.load(); return g.name }
func (g *ghostCustomer) City() string { g.load(); return g.city }

func main() {
	// Each step reads the counter before and after the call that may load.
	selects = 0
	order := &Order{ID: 10, CustomerID: 1}
	before := selects
	name := order.Customer().Name()
	after := selects
	again := order.Customer().Name()
	fmt.Printf("lazy initialization: selects %d | %s | selects %d | %s | selects %d\n", before, name, after, again, selects)

	selects = 0
	var proxy Customer = &customerProxy{id: 2}
	id, before := proxy.ID(), selects
	name, after = proxy.Name(), selects
	city := proxy.City()
	fmt.Printf("virtual proxy: id %d | selects %d | %s | selects %d | %s | selects %d\n", id, before, name, after, city, selects)

	selects = 0
	holder := &ValueHolder[Customer]{loader: func() Customer { return loadCustomer(1) }}
	before = selects
	name = holder.GetValue().Name()
	fmt.Printf("value holder: selects %d | %s | selects %d\n", before, name, selects)

	selects = 0
	var ghost Customer = &ghostCustomer{id: 1}
	id, before = ghost.ID(), selects
	name, city = ghost.Name(), ghost.City()
	fmt.Printf("ghost: id %d | selects %d | %s %s | selects %d\n", id, before, name, city, selects)

	selects = 1 // One SELECT reads the orders.
	var names []string
	for _, row := range orderTable {
		o := &Order{ID: row[0], CustomerID: row[1]}
		names = append(names, o.Customer().Name())
	}
	fmt.Printf("lazy: %s | selects %d\n", strings.Join(names, ", "), selects)

	selects = 1 // One SELECT with a JOIN reads the orders and their customers.
	names = nil
	for _, row := range orderTable {
		names = append(names, customerTable[row[1]][0])
	}
	fmt.Printf("eager: %s | selects %d\n", strings.Join(names, ", "), selects)
}
Output
lazy initialization: selects 0 | Ann | selects 1 | Ann | selects 1
virtual proxy: id 2 | selects 0 | Bo | selects 1 | Rome | selects 1
value holder: selects 0 | Ann | selects 1
ghost: id 1 | selects 0 | Ann Oslo | selects 1
lazy: Ann, Bo, Ann | selects 4
eager: Ann, Bo, Ann | selects 1
  • Verdict: idiom. Customer is an interface, and the proxy and the ghost implement it with pointer receivers, because they change their own fields on the first load. ValueHolder is generic.
  • sync.OnceValue gives the same "load once" behaviour and is also safe for concurrent calls. The file reads the counter into variables before each load, so the order of evaluation is explicit.
RustGitHub
use std::cell::{Cell, OnceCell, RefCell};
use std::collections::HashMap;

// A stand-in for the database: the tables and a count of SELECT statements.
struct Db {
    customers: HashMap<u32, (&'static str, &'static str)>,
    orders: Vec<(u32, u32)>,
    selects: Cell<u32>,
}

impl Db {
    fn select_customer(&self, id: u32) -> (&'static str, &'static str) {
        self.selects.set(self.selects.get() + 1);
        self.customers[&id]
    }
    fn selects(&self) -> u32 {
        self.selects.get()
    }
}

trait Customer {
    fn id(&self) -> u32;
    fn name(&self) -> String;
    fn city(&self) -> String;
}

struct RealCustomer {
    id: u32,
    name: String,
    city: String,
}

impl RealCustomer {
    fn load(db: &Db, id: u32) -> RealCustomer {
        let (name, city) = db.select_customer(id);
        RealCustomer { id, name: name.to_string(), city: city.to_string() }
    }
}

impl Customer for RealCustomer {
    fn id(&self) -> u32 {
        self.id
    }
    fn name(&self) -> String {
        self.name.clone()
    }
    fn city(&self) -> String {
        self.city.clone()
    }
}

// 1. Lazy initialization: an empty OnceCell means "not loaded".
struct Order<'a> {
    db: &'a Db,
    customer_id: u32,
    customer: OnceCell<RealCustomer>,
}

impl Order<'_> {
    fn customer(&self) -> &RealCustomer {
        self.customer.get_or_init(|| RealCustomer::load(self.db, self.customer_id))
    }
}

// 2. Virtual proxy: it implements Customer and loads the real one on first use.
struct CustomerProxy<'a> {
    db: &'a Db,
    id: u32,
    real: OnceCell<RealCustomer>,
}

impl CustomerProxy<'_> {
    fn real(&self) -> &RealCustomer {
        self.real.get_or_init(|| RealCustomer::load(self.db, self.id))
    }
}

impl Customer for CustomerProxy<'_> {
    fn id(&self) -> u32 {
        self.id
    }
    fn name(&self) -> String {
        self.real().name()
    }
    fn city(&self) -> String {
        self.real().city()
    }
}

// 3. Value holder: the client asks the holder for the value.
struct ValueHolder<T, F: Fn() -> T> {
    loader: F,
    value: OnceCell<T>,
}

impl<T, F: Fn() -> T> ValueHolder<T, F> {
    fn get_value(&self) -> &T {
        self.value.get_or_init(&self.loader)
    }
}

// 4. Ghost: the real type, with only the key filled in until first use.
struct GhostCustomer<'a> {
    db: &'a Db,
    id: u32,
    data: RefCell<Option<(String, String)>>,
}

impl GhostCustomer<'_> {
    fn load(&self) {
        if self.data.borrow().is_none() {
            let (name, city) = self.db.select_customer(self.id);
            *self.data.borrow_mut() = Some((name.to_string(), city.to_string()));
        }
    }
}

impl Customer for GhostCustomer<'_> {
    fn id(&self) -> u32 {
        self.id
    }
    fn name(&self) -> String {
        self.load();
        self.data.borrow().as_ref().unwrap().0.clone()
    }
    fn city(&self) -> String {
        self.load();
        self.data.borrow().as_ref().unwrap().1.clone()
    }
}

fn main() {
    let db = Db {
        customers: HashMap::from([(1, ("Ann", "Oslo")), (2, ("Bo", "Rome"))]),
        orders: vec![(10, 1), (11, 2), (12, 1)],
        selects: Cell::new(0),
    };

    db.selects.set(0);
    let order = Order { db: &db, customer_id: 1, customer: OnceCell::new() };
    let before = db.selects();
    let name = order.customer().name();
    let after = db.selects();
    let again = order.customer().name();
    println!("lazy initialization: selects {before} | {name} | selects {after} | {again} | selects {}", db.selects());

    db.selects.set(0);
    let proxy: &dyn Customer = &CustomerProxy { db: &db, id: 2, real: OnceCell::new() };
    let (id, before) = (proxy.id(), db.selects());
    let (name, after) = (proxy.name(), db.selects());
    let city = proxy.city();
    println!("virtual proxy: id {id} | selects {before} | {name} | selects {after} | {city} | selects {}", db.selects());

    db.selects.set(0);
    let holder = ValueHolder { loader: || RealCustomer::load(&db, 1), value: OnceCell::new() };
    let before = db.selects();
    let name = holder.get_value().name();
    println!("value holder: selects {before} | {name} | selects {}", db.selects());

    db.selects.set(0);
    let ghost: &dyn Customer = &GhostCustomer { db: &db, id: 1, data: RefCell::new(None) };
    let (id, before) = (ghost.id(), db.selects());
    let (name, city) = (ghost.name(), ghost.city());
    println!("ghost: id {id} | selects {before} | {name} {city} | selects {}", db.selects());

    db.selects.set(1); // One SELECT reads the orders.
    let names: Vec<String> = db
        .orders
        .iter()
        .map(|&(_, customer_id)| Order { db: &db, customer_id, customer: OnceCell::new() }.customer().name())
        .collect();
    println!("lazy: {} | selects {}", names.join(", "), db.selects());

    db.selects.set(1); // One SELECT with a JOIN reads the orders and their customers.
    let names: Vec<&str> = db.orders.iter().map(|&(_, customer_id)| db.customers[&customer_id].0).collect();
    println!("eager: {} | selects {}", names.join(", "), db.selects());
}
Output
lazy initialization: selects 0 | Ann | selects 1 | Ann | selects 1
virtual proxy: id 2 | selects 0 | Bo | selects 1 | Rome | selects 1
value holder: selects 0 | Ann | selects 1
ghost: id 1 | selects 0 | Ann Oslo | selects 1
lazy: Ann, Bo, Ann | selects 4
eager: Ann, Bo, Ann | selects 1
  • Verdict: idiom. OnceCell is the marker: it is empty until get_or_init runs the loader once. The ghost uses a RefCell<Option<...>>, because it fills its own fields through a shared reference.
  • The database is a struct with a Cell counter, so the loaders can count statements through a shared &Db.

Consequences

Benefits.

  • Less work for data that is not used. As Fowler puts it, "if you're lazy about doing things you'll win when it turns out you don't need to do them at all."1 A screen that shows only orders never reads their customers.
  • The domain code stays simple. The caller writes order.customer and does not know whether the customer is in memory. In SQLAlchemy, "Lazy loading is the default loading style for all relationship() constructs that don’t otherwise indicate the relationship."3
  • The load can be delayed or cut off. Lazy loading lets an ORM reduce "the complexity and time spent within object fetches", because "attributes for related tables don’t need to be addressed immediately."4

Liabilities.

The N plus one problem. A loop over N objects that uses a lazy association on each one runs one query for the list and one query for each object: "for any N objects loaded, accessing their lazy-loaded attributes means there will be N+1 SELECT statements emitted."3 Entity Framework Core warns that "Lazy loading can cause unneeded extra database roundtrips to occur (the so-called N+1 problem), and care should be taken to avoid this."5

This code runs but gives a wrong answer on purpose.

import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table customer (id integer primary key, name text);
create table orders (id integer primary key, customer_id integer);
insert into customer values (1, 'Ann'), (2, 'Bo');
insert into orders values (10, 1), (11, 2), (12, 1);
""")
selects = []
db.set_trace_callback(selects.append)


class Order:
    def __init__(self, id, customer_id):
        self.id, self.customer_id, self._name = id, customer_id, None

    @property
    def customer_name(self):  # A lazy load: one SELECT on first use.
        if self._name is None:
            sql = "select name from customer where id = ?"
            (self._name,) = db.execute(sql, (self.customer_id,)).fetchone()
        return self._name


orders = [Order(*row) for row in db.execute("select id, customer_id from orders")]
print([o.customer_name for o in orders], "| selects:", len(selects))
Output
['Ann', 'Bo', 'Ann'] | selects: 4

Loading after the session is closed. The loader needs a database connection. In SQLAlchemy, a lazy load uses the Session of the object; "If the object is in the detached state and not associated with any Session , this is considered to be an error state and an informative exception is raised."4 An object that leaves its session, for example to be rendered after the request ends, cannot load its associations.

A marker that is also a value. Lazy initialization uses null as the marker. Wikipedia notes that "if null is a legitimate return value, it may be necessary to use a placeholder object to signal that it has not been initialized."6 A customer that is really absent then looks unloaded, and each access runs the query again. The value holder in the examples keeps a separate loaded flag for this reason.

Threads. "If this method is used in a multithreaded application , synchronization must be used to avoid race conditions ."6 Two threads that find the marker at the same time both run the query, and each may keep a different object.

Identity. A proxy is a different object from the real one, so a test such as proxy is customer is false even for the same row. A Lazy Load that does not go through the Identity Map can also load a second copy of a row that is already in memory.

When not to use it

When the caller always needs the related data. If every use of an order reads its customer, the Lazy Load only adds a second query. Load both with a join. Django's select_related "works by creating an SQL join and including the fields of the related object in the SELECT statement."7

In loops over many objects. Load the association for the whole list in one or two queries. SQLAlchemy's select IN loading "assembles the primary key identifiers of the parent objects into an IN clause, so that all members of related collections / scalar references are loaded at once by primary key."3 Django's prefetch_related retrieves the related objects "in a single batch".7

When the object leaves its session. Data that is sent to a template, a cache or another thread after the database work ends must be loaded before that point.

How to fix it

To find unplanned lazy loads, make them fail. SQLAlchemy's raise loading "is triggered at the same time a lazy load would normally occur, except it raises an ORM exception in order to guard against the application making unwanted lazy loads."3 Then load what each use case needs with a join or a batch query.

Eager loading. The opposite strategy loads the related objects with the owner. SQLAlchemy's joined loading "applies a JOIN to the given SELECT statement so that related rows are loaded in the same result set."3 "Eager loading is the opposite of lazy loading ."4

Proxies made by the framework. Entity Framework Core can generate virtual proxies. With UseLazyLoadingProxies, it enables "lazy loading for any navigation property that can be overridden--that is, it must be virtual and on a class that can be inherited from." Without proxies, an entity can receive an ILazyLoader service, or a delegate, and call it in the getter of the navigation property.5

Lazy values in the standard libraries. Some languages have a lazy initialization helper. Python's functools.cached_property turns a method into "a property whose value is computed once and then cached as a normal attribute for the life of the instance."8 Go's sync.OnceValue "returns a function that invokes f only once and returns the value returned by f."9 Rust's OnceCell is "A cell which can nominally be written to only once."10 These helpers give the marker and the check, and the program supplies the query.

Identity Map. A Lazy Load of a single object by its key can look in the identity map first and skip the query. See Identity Map.

Proxy. The virtual proxy is the Proxy pattern used to delay the creation of an expensive object. See Proxy pattern.

Known uses

  • SQLAlchemy: in LazyLoader._load_for_state in strategies.py at 2.0.57, a load by primary key first calls session._identity_lookup; the comment says it will "check the identity map without generating a Query at all". Only if the object is not there does it call _emit_lazyload.11
  • Django: ForwardManyToOneDescriptor.get in related_descriptors.py at 5.2.8 implements child.parent. The comment says: "The related instance is loaded from the database and then cached by the field on the model instance state."12 This is lazy initialization with the field cache as the marker.
  • Entity Framework Core, for .NET: lazy loading with proxies, or with an injected ILazyLoader.5

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Lazy Load, pattern summary and the note on the four varieties
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 11, Object-Relational Behavioral Patterns, Lazy Load
  3. SQLAlchemy 2.0 documentation, Relationship Loading Techniques, Summary of Relationship Loading Styles; Preventing unwanted lazy loads using raiseload
  4. SQLAlchemy 2.0 documentation, Glossary, lazy load; N plus one problem
  5. Entity Framework Core documentation, Lazy Loading of Related Data, Lazy loading with proxies; Lazy loading without proxies
  6. Lazy loading, Wikipedia, Methods
  7. Django 5.2 documentation, QuerySet API reference, select_related(); prefetch_related()
  8. The Python Standard Library, functools, functools.cached_property
  9. Go standard library, package sync, func OnceValue
  10. Rust standard library, struct std::cell::OnceCell, the type description
  11. SQLAlchemy 2.0.57 source, lib/sqlalchemy/orm/strategies.py, LazyLoader._load_for_state, lines 878 to 995
  12. Django 5.2.8 source, django/db/models/fields/related_descriptors.py, ForwardManyToOneDescriptor.__get__, lines 226 to 275

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/W7GEKN/text.yaml