How to Implement Lazy Loading for Expensive Resources
Load expensive resources only when needed: defer, memoize, and invalidate, so work happens at most once and never for a caller that does not need it.
On this page
Introduction
Some resources are expensive to create: a database connection pool, a large in-memory index, a machine-learning model, a client for an external service. Creating them at startup is simple but pays the cost even when a process never uses them, and creates a startup dependency that can fail the whole service. Lazy loading defers creation to first use, so a caller that never touches the resource pays nothing, and the expensive work happens exactly when it is first needed.
This tutorial implements lazy loading with memoization and single-flight, so the resource is created at most once and only when first used, and provides invalidation so a changed source can be reloaded. It covers deferring a pool, an index, and a model, and tests the defer, reuse, concurrency, and reset paths.
Defer initialisation to first use
Instead of creating the resource at module load or startup, create it on first access. Wrap the creation in a getter that checks whether the resource exists and creates it if not. The benefit is two-fold: an unused resource costs nothing, and a failing dependency fails the code path that uses it rather than the whole process at boot. The cost is that the first caller pays the creation time.
Keep the deferral in one accessor, so every caller goes through it and the resource is created consistently. Do not scatter lazy checks across call sites, because one will create a second instance. The accessor is the single owner of the resource and of its lifecycle.
let pool: Pool | undefined;
function getPool(): Pool {
if (!pool) {
pool = createPool({ max: 10 }); // created on first use, not at startup
}
return pool;
}
// a caller that never calls getPool pays nothing for the pool
export function query(sql: string, params: unknown[]) {
return getPool().query(sql, params);
}
Memoize the value, not just check for it
A check-then-create has a race: two callers can both see the resource absent and both create it. For a synchronous creation the check is atomic enough, but for an async creation, which most expensive resources are, the race is real. Store the in-flight promise as the memoized value, so the second caller receives the same promise and awaits it rather than starting a second creation.
This is the same single-flight idea applied to initialisation. The memo holds a promise, not a resolved value, and every caller awaits it. When it resolves, the resource is ready for all. If it rejects, clear the memo so a later caller can retry, rather than caching a rejection that would fail every future caller.
let modelPromise: Promise<Model> | undefined;
function getModel(): Promise<Model> {
if (!modelPromise) {
modelPromise = loadModel().catch((err) => {
modelPromise = undefined; // allow a retry after a failure
throw err;
});
}
return modelPromise; // concurrent callers share one load
}
Invalidate when the source changes
A memoized resource is stale the moment its source changes. A configuration-backed index must reload when the config updates; a cached model must reload when a new version is published. Provide a reset that clears the memo so the next access recreates the resource, and call it on the event that changes the source. Without a reset, the resource lives until the process restarts, which is fine for immutable data and wrong for anything that changes.
Decide whether a reset should drop the old resource immediately or swap it after the new one is ready. For a connection pool, closing the old pool on reset is correct; for an index, building the new one and swapping avoids a gap where no index is available. Keep the reset in the same accessor so the lifecycle, create and destroy, lives in one place.
export function resetPool() {
const old = pool;
pool = undefined; // next getPool() creates a fresh pool
if (old) void old.end(); // release the old pool
}
// config watcher: reload the index when the config changes
config.on('change', async () => {
const next = await buildIndex(config.current());
index = next; // swap after the new one is ready
});
Move CPU-heavy init off the request path
Some resources take so long to create that even the first caller’s delay is unacceptable, such as a model that takes seconds to load. Options are to warm the resource in the background after startup, so it is ready before the first request, or to move its creation to a worker thread and keep the event loop free. A background warm-up keeps the benefit of not blocking startup while avoiding a first-request stall.
Warming is eager-with-benefit: start the creation after the process is serving, so liveness checks pass and the resource is ready soon. If the resource is used rarely and is huge, lazy with a loading state may be better than holding it always. Match the strategy to the resource’s size and how often it is used, and measure the first-use delay to decide.
Test defer, reuse, and reset
Test that the resource is not created until first use, by instrumenting the creation and asserting zero creations after startup. Test that two calls create it once, proving the memo. Test that concurrent first calls share one creation, proving the promise memo and single-flight. Test that a reset drops the resource and the next call recreates it, proving invalidation. Test that a failed creation does not poison the memo, so a retry succeeds.
node -e '
const mod = require("./resource");
// after import, creation count must be 0
// after two calls, creation count must be 1
// after reset + call, creation count must be 2
'
Common pitfalls
Creating the resource at startup so unused processes pay the cost, a check-then-create that races and creates two instances, memoizing a rejection so every later call fails, no reset so a changed source is never reloaded, and a lazy load that stalls the first request by seconds without a warm-up are the recurring mistakes. A single accessor, a promise memo with single-flight, a clear on rejection, a reset on change, and a background warm-up address them.
Conclusion
Lazy loading defers an expensive resource to first use, so unused processes pay nothing. Defer creation in a single accessor, memoize the promise so concurrent callers share one creation, clear the memo on failure so a retry works, and provide a reset for a changed source. Self-check by asserting zero creations after startup, one creation after two calls, one creation for concurrent calls, and a recreation after reset. Then expensive work happens at most once and only when needed.
Sources: MDN: Lazy loading, MDN: Promise and async functions, Node.js: Worker threads (for expensive off-thread work).
FAQ
- Lazy loading or eager loading?
- Lazy loading defers the cost until a resource is needed and avoids paying for unused work, but adds a delay on first use. Eager loading pays up front so first use is fast. Choose based on whether the resource is usually used and whether a first-use delay is acceptable.
- How do I avoid two lazy loads at once?
- Cache the promise, not just the value. The first caller starts the load and stores the in-flight promise; a second caller during the load receives the same promise and awaits it, so the expensive work happens once.
Report a problem with this articleOpens a pre-filled issue on GitHub.