Once you know what makes a function's init slow, which changes shrink it, and when does lazy loading only move the cost?
answer
- remove work or move work
- import narrowly, bundle small
- who pays on first use
- what nearly every request needs
basics
~20 sTrim init by removing unused dependencies, importing narrowly, bundling and moving reflection to build time; lazy-load only what most requests skip, because a deferred dependency is paid by the first request on each instance that needs it.
solid answer
~50 sTrimming removes work: drop unused dependencies, import the one client you call instead of a whole SDK, bundle and tree-shake, strip test and build-time files from the package, replace runtime reflection or scanning with build-time generation, and parallelise or cache init-time fetches. Lazy loading moves work: the dependency loads on the first request on each instance that needs it. That is a clear gain for a rarely used path such as an export library, and no gain for something nearly every request uses, such as the database client, because the cold request just pays the same cost inside the handler. It is a loss on instances initialised ahead of traffic, where init was already off the request path, and on request-concurrent instances it needs a once-only guard. I change one thing at a time and compare cold penalty per version.
code
pseudocode · 12 lines// init: what nearly every request needs stays eager
paymentClient = createPaymentClient(config)
// rare path: loaded on first use, then kept for the instance's life
exporter = null
exporterLock = newOnceGuard()
handler(event):
if event.path == "/export":
exporterLock.runOnce(() => exporter = loadModule("report-export"))
return exporter.render(event)
return paymentClient.charge(event)go deeper
Recall the two levers: trimming removes init work, lazy loading delays it until a code path first needs it.
Explain who pays for a lazily loaded dependency, the first request per instance taking that path, and why that is no gain for a dependency every request uses.
Show you choose per dependency from measured use, avoid lazy loading on pre-initialised instances, guard concurrent first loads and test deferred paths.
Set the team's default: a package-size and init budget in the pipeline, and a rule for which dependencies may be deferred.
## Two ways to cut init **Init** is the work a function instance does once, when it starts: loading its code package, starting the runtime, importing modules, bootstrapping a framework, building clients and fetching configuration. Once measurement has shown which of those steps dominate, there are two kinds of change: - **Trimming** removes work: the instance simply does less. - **Lazy loading** moves work: it runs later, the first time a code path needs it, instead of during init. Trimming is almost always a gain. Lazy loading is a gain only when the moved work is skipped by most requests. ## Trimming the dependency tree and bundle - **Remove unused dependencies.** Audit the dependency tree; heavy packages often arrive transitively through one convenience library. - **Import narrowly.** Load the one client or submodule you call instead of a whole SDK or utility suite. - **Bundle and tree-shake** where the runtime has a bundler: fewer, smaller files to read and parse at start. - **Strip the package.** Test and build-time dependencies, documentation, and native binaries for platforms you do not run on all add download and unpack time. - **Move work to build time.** In a runtime whose **heavy framework uses reflection or class scanning at start**, that work is a large share of init; build-time code generation or ahead-of-time compilation, where the runtime offers it, removes it from every instance. - **Cut init-time network calls.** Run independent fetches in parallel, cache what can be cached, and read non-secret configuration from the deployment rather than over the network. ## Lazy loading: moving cost to first use A lazily loaded dependency is imported or constructed the first time a request needs it, then kept for the life of the instance. The cost does not disappear; it lands on the **first request on each instance that takes that path**. | How often requests need it | Effect of lazy loading | |---|---| | rarely (an export library used by a small share of requests) | most cold starts skip it; a few first-hits pay it; clear gain | | sometimes | gain depends on how often cold starts meet the path | | nearly always (the database client) | the first request pays the same cost inside the handler; no gain | ## When lazy loading only moves the cost - **A dependency nearly every request needs.** The cost moves from init into the first request's handler time. The user who triggered the cold start waits just as long. - **Instances initialised ahead of traffic.** With pre-provisioned capacity or a minimum instance count, init already runs before any request arrives. Deferring a dependency there pushes its cost back onto a request that would otherwise have been fast. - **A rare path with its own latency target.** Lazy loading concentrates the penalty on that path's first hit per instance, so its tail grows even as the main path's improves. - **Request-concurrent instances.** On a platform that sends many requests to one instance, two first requests can try to load the same dependency at once. Guard it with a once-only initialiser so the work runs a single time. ## Measuring the result 1. Record the **init breakdown** and the **cold penalty** for the current version as the baseline. 2. Change **one thing**: one dependency removed, or one module deferred. 3. Compare init duration and cold penalty per version, using cold invocations only. 4. For each lazily loaded path, check the latency of its **first hit per instance**, not only its overall percentiles. 5. Track **package size** in the pipeline so a later release does not quietly undo the work. A worked example: a function imports a report-export library that a small share of requests use, a payment client that every request uses, and a large SDK of which it calls one client. The right moves are to trim the SDK import to that one client, defer the export library, and leave the payment client in init. Deferring the payment client would only shift its cost into every cold request's handler. ## A note on correctness Moving code changes **when** it fails. A dependency that fails to load during init fails the instance before it takes traffic, and the platform's health signals show it. The same failure in a lazily loaded path surfaces as an error on whichever request first takes that path, possibly hours later. Keep a test that exercises every deferred path, and log a clear error when a deferred load fails. Neither technique replaces the measurement: trim what the profile names, defer what most requests skip, and keep everything else where it is.
- What changes about failures when you move a dependency from init to lazy loading?When it fails. A dependency that fails during init stops the instance before it serves traffic, and the platform's health signals show it. The same failure in a deferred path appears as an error on whichever request first takes that path, possibly hours later. Keep a test that exercises every deferred path and log a clear error when a deferred load fails.
- Why can trimming the code package help even when imports are already fast?Before any of your code runs, the platform downloads and unpacks the package, and that part grows with package size. Test and build-time dependencies, documentation and native binaries for platforms you do not run on all add to it. Estimate that share as the platform's init duration minus your own timed steps; if it is large, trimming the package is the fix.
A plumber's van is packed each morning with the tools used on every job, while the rare specialist kit stays at the depot. Packing less gets the van out sooner; the first job of the day that needs the kit waits while someone fetches it, and it stays in the van after that. Leaving the wrench at the depot saves nothing, because the first job of every day needs it.
- Lazy loading makes a dependency's cost disappear.
- Lazy-loading the database client speeds up the cold requests that use it.
- Deferring imports always helps, even on instances initialised ahead of traffic.
- A lazily loaded module is re-imported on every request that uses it.
- Package size cannot matter once the code is deployed.