skip to content

As the lead of a FastAPI inference service, would you create its model, outbound HTTP client and settings at import time, in the lifespan or through an app factory, and why?

level: principalimportance: should knowfreq 30%

answer

  1. import time runs for every importer
  2. the lifespan runs per serving process
  3. close after yield
  4. a factory takes settings as an argument
  5. fastapi run imports an app object

basics

~20 s

Heavy or closable resources go in the lifespan: created before yield, handed over as state, closed after it. A create_app(settings) factory lets tests pass their own settings. Import-time globals load for every importer, tests and tools included.

solid answer

~40 s

Import time is the easiest place to write and the worst to live with: every importer, from the test collector to a script that exports the OpenAPI schema, loads the model, and nothing closes the client. The lifespan ties both to a process that is about to serve: before `yield` runs once per worker at startup, the yielded dict reaches handlers through `request.state`, and after `yield` closes the client at shutdown. Settings decide what it loads, so I wrap the app in `create_app(settings)` and let the lifespan close over them. Production calls `app = create_app()` at module level, because `fastapi run` imports an app object and has no factory option; tests call `create_app(Settings(...))` with no environment patching or cache clearing. Module level keeps only cheap definitions.

code

python · 37 lines
python
from contextlib import asynccontextmanager

from fastapi import FastAPI, Request
from pydantic import BaseModel


class Settings(BaseModel):
    model_path: str = "/models/prod.bin"


class Model:
    def __init__(self, path: str):
        self.path = path  # a real service loads weights here

    def predict(self, text: str) -> str:
        return f"{self.path}: {text[:20]}"


def create_app(settings: Settings | None = None) -> FastAPI:
    settings = settings or Settings()

    @asynccontextmanager
    async def lifespan(app: FastAPI):
        model = Model(settings.model_path)  # once per serving process
        yield {"model": model}
        # close outbound clients here, at shutdown

    app = FastAPI(lifespan=lifespan)

    @app.post("/predict")
    async def predict(request: Request, text: str):
        return {"result": request.state.model.predict(text)}

    return app


app = create_app()  # the object `fastapi run main.py` imports

go deeper

for a junior

Know that the lifespan runs startup code before serving and shutdown code after its yield.

for a middle

Explain why module-level resources load for every importer and how yielded state reaches handlers.

for a senior

Show the factory pattern, how tests pass settings to it, and why fastapi run still needs a module-level app.

for a principal

Set the team rule for where resources live, the exceptions it allows, and how review and a test keep heavy work out of import time.

## The decision An inference service has three things to set up: the **model** (large, slow to load), an **outbound HTTP client** (holds a connection pool and must be closed), and the **settings** that say which model and which endpoints. Where they are created decides how tests run, what every import costs and whether shutdown is clean. A lead picks one pattern and makes the codebase follow it. ## The places, compared | Where | Runs | Closes cleanly | Tests can choose the values | |---|---|---|---| | Module level (import time) | on every import of the module | no hook | only by patching globals or the environment before import | | Lifespan, before `yield` | once per serving process, before requests | yes, after `yield` | only if the lifespan can be given settings | | App factory `create_app(settings)` + lifespan | when the factory is called | yes | yes, by passing settings | | Lazily, in a dependency | on the first request that needs it | no natural hook | via a dependency override | ## What import time costs Module-level code runs whenever the module is imported, whoever imports it: the test collector, a script that writes `openapi.json` for a client generator, a migration tool that only wants a model class. Each of them pays for loading the model and opens a client nobody closes. A missing environment variable becomes an import error in places that never serve a request. Import time is the easiest place to write and the most expensive to live with. ## What the lifespan gives The lifespan runs once in each process that is about to serve. The code before `yield` loads the model and opens the client; the yielded dict reaches handlers as `request.state`; the code after `yield` closes the client when the server shuts down. Under `TestClient` it runs only inside a `with` block, so a test that does not need the model does not pay for it. Resources now have a start and an end that match the server's, which also makes startup failures loud: the process refuses to serve instead of failing on the first request. ## Why a factory on top A lifespan defined at module level still reads its settings from somewhere global, usually a cached `get_settings()`. Wrapping the app in `create_app(settings)` lets the lifespan close over the settings it was given: - production calls it once at module level, `app = create_app()`, because `fastapi run` imports an app object and has no factory option (Uvicorn's own `--factory` flag can call a factory directly); - tests call `create_app(Settings(model_path=...))` and get an app with a tiny model, with no environment patching and no cache to clear; - two differently configured apps can exist in one process, which helps contract tests. The cost is one level of indirection: routes are registered inside a function or included from routers, and readers must find the factory to see how the app is built. ## Lazy creation, when it fits Creating a resource on first use inside a dependency suits something optional and rarely needed, such as a client for one admin report. It costs latency on that first request, a race when two first requests arrive together (so creation needs a lock), and it still needs the lifespan for shutdown. It is a supplement, not the main pattern. ## How I would decide - **Anything expensive or closable** goes in the lifespan. - **Anything that varies by environment** reaches the lifespan as an argument, through a factory. - **Module level** keeps only cheap, pure definitions: models, routers, constants. - **Lazy creation** needs a stated reason and a lock. I would write this down with an example `create_app`, add a test that imports the app module and asserts that nothing heavy was created, and treat a new module-level client in review as a defect rather than a style choice.

  • When would you create a resource lazily inside a FastAPI dependency instead of in the lifespan?
    When it is optional, rarely used and costly to start, such as a client for one admin report. The price is latency on the first request that needs it, a race when two first requests arrive at once, so creation needs a lock, and no shutdown hook unless the lifespan still closes it.
  • With settings captured by the lifespan at startup, how does a FastAPI service pick up a changed setting?
    By restarting: roll the worker processes so each lifespan runs again with the new values. Mutating a shared settings object while requests are in flight gives some requests old values and some new ones; a value that must change at runtime belongs in a source read per request, not in startup settings.

It is the difference between a shop that switches on its ovens when the doors open and turns them off at closing, and one whose ovens come on whenever anyone walks past the building.

  • Loading the model at import time is free because Python caches modules
  • One lifespan's resources are shared by all worker processes
  • fastapi run detects a create_app function and calls it
  • Tests should patch module globals rather than pass settings in
  • Creating a client lazily on the first request needs no lock