skip to content

A FastAPI app mounts a second FastAPI app with app.mount(), and the mounted app's lifespan never loads its model; why, and how do you fix it?

level: seniorimportance: nice to knowfreq 18%

answer

  1. who receives lifespan messages
  2. mounts route requests only
  3. routers merge, mounts do not
  4. app.router.lifespan_context

basics

~20 s

Only the application the server runs receives lifespan events; app.mount() never forwards them, so a mounted app's lifespan does not run. Use an APIRouter with lifespan= and include_router, which merges it, or enter the sub-app's lifespan from the parent's.

solid answer

~40 s

The server sends the ASGI lifespan messages to the top-level app only, and FastAPI enters that app's lifespan. `app.mount()` adds a route that forwards HTTP and WebSocket connections, not lifespan messages, so the mounted app's `lifespan` and any `on_event` handlers on it never run; the FastAPI docs say lifespan events run only for the main application. Confusingly, requests to the mount still see the parent's yielded state. Fixes: turn the sub-app into an `APIRouter(lifespan=...)` and `include_router` it, since FastAPI merges a router's lifespan into the parent's, with the parent's keys winning on a clash; or keep the mount and enter `embed_app.router.lifespan_context(embed_app)` inside the parent's lifespan, yielding its state onward; or load the resource in the parent.

code

python · 47 lines
python
from contextlib import asynccontextmanager

from fastapi import APIRouter, FastAPI, Request
from fastapi.testclient import TestClient


@asynccontextmanager
async def embed_lifespan(app):
    print("embedding model loaded")
    yield {"embedder": "embedding-model"}
    print("embedding model released")


@asynccontextmanager
async def main_lifespan(app: FastAPI):
    yield {"model": "classifier"}


# The trap: a mounted sub-application's own lifespan is never entered.
embed_app = FastAPI(lifespan=embed_lifespan)


@embed_app.get("/embed")
async def embed(request: Request) -> dict:
    return {"embedder": getattr(request.state, "embedder", None)}


mounted = FastAPI(lifespan=main_lifespan)
mounted.mount("/v2", embed_app)

with TestClient(mounted) as client:
    print(client.get("/v2/embed").json())  # {'embedder': None}

# A fix: make it a router; include_router merges the router's lifespan into the app's.
embed_router = APIRouter(lifespan=embed_lifespan)


@embed_router.get("/embed")
async def embed_v2(request: Request) -> dict:
    return {"embedder": request.state.embedder, "model": request.state.model}


app = FastAPI(lifespan=main_lifespan)
app.include_router(embed_router, prefix="/v2")

with TestClient(app) as client:
    print(client.get("/v2/embed").json())  # both keys present

go deeper

for a junior

Remember that only the main application's lifespan runs when the server starts; a sub-application attached with app.mount() never has its lifespan run.

for a middle

Explain why: lifespan messages go to the app the server runs, and a mount forwards only HTTP and WebSocket connections.

for a senior

Pick a fix: an APIRouter whose lifespan include_router merges, entering the sub-app's lifespan_context from the parent, or moving the resource up, and know how merged state resolves clashes.

for a principal

Weigh whether a second API should be a mounted app at all; separate apps bring separate docs and settings but also separate startup you must wire by hand.

## The symptom An inference service grows a second API, say an embeddings endpoint, built as its own `FastAPI` instance with its own lifespan that loads an embedding model. The main app attaches it with `app.mount("/v2", embed_app)`. Requests reach the sub-application's routes, but its model is never loaded: the startup log line never appears, and `request.state.embedder` is missing. ## Why it happens The ASGI **lifespan protocol** is delivered to one application: the one the server runs. The server sends `lifespan.startup` to the main app; FastAPI enters the main app's lifespan and nothing else. `app.mount()` adds a `Mount` route, and routes are only consulted for HTTP and WebSocket connections. No lifespan message is ever forwarded to a mounted application, so its `lifespan` argument (and any deprecated `on_event` handler on it) never runs. The FastAPI documentation states it directly: lifespan events run only for the main application, not for sub-applications mounted with `app.mount`. Two details make the bug confusing: - **The sub-application still sees the parent's lifespan state.** Mounting passes the request scope down, including the per-request copy of the parent's yielded dict, so `request.state.model` from the parent works inside the sub-app while the sub-app's own keys never appear. - **Nothing fails at startup.** The server reports startup complete; the gap shows up only when a request reaches code that needs the missing resource. ## Fixes | Fix | How | When it fits | |---|---|---| | Use a router instead of a mount | `APIRouter(lifespan=...)` plus `app.include_router(...)` | the second API does not need to be a separate app | | Enter the sub-app's lifespan from the parent's | `async with embed_app.router.lifespan_context(embed_app) as sub_state:` around the parent's `yield` | the sub-app must stay a mounted app with its own docs and settings | | Move the resource into the parent | load the embedding model in the main lifespan | both apps share it anyway | **Router with its own lifespan.** `APIRouter` accepts the same `lifespan` parameter as `FastAPI`. When you call `include_router`, FastAPI **merges** the router's lifespan into the including app's: the parent's lifespan is entered first, then the router's, and they exit in reverse order. If both yield dicts, they are combined into one lifespan state, and the **parent's value wins** on a key both define. Nested routers merge upward the same way. **Entering the sub-app's lifespan by hand.** Each FastAPI app keeps its lifespan context factory on `app.router.lifespan_context`. The parent's lifespan can enter it and pass the result on: ```python @asynccontextmanager async def main_lifespan(app: FastAPI): async with embed_app.router.lifespan_context(embed_app) as sub_state: yield {"model": load_model(), **(sub_state or {})} ``` Because the parent's yielded dict is copied into requests that reach the mount, the sub-app's endpoints then find their keys on `request.state`. The cost is coupling: the parent must know about every mounted app's startup. ## What to check when reviewing a mounted app - Does the mounted application define a `lifespan` or `on_event` handlers? If so, something in the parent must run them, or they are dead code. - Does code inside the sub-app read `app.state` of the sub-app? The sub-app's `app.state` is its own object; values the parent set on its `app.state` are not there. - In tests, use `with TestClient(main_app)`: entering the main app's lifespan is the only startup that happens, exactly as in production, so the test reproduces the gap instead of hiding it. ## Confirming the diagnosis A quick way to prove the mounted lifespan is not running: 1. Add a log line or a counter at the top of the sub-application's lifespan. 2. Start the main app, or enter `with TestClient(main_app)`, and watch for the line; it never appears. 3. Request a route under the mount and read `request.state`: the parent's keys are there, the sub-application's are not. 4. Start the sub-application on its own, or enter `with TestClient(embed_app)`; now its lifespan runs, which shows the code itself is fine and the mount is the cause. ## Where this sits How `app.mount` routes paths, how `include_router` applies prefixes and tags, and when to mount a whole application rather than include a router are covered with routers and mounted apps. The lifespan-specific rule to carry away: **only the app the server runs gets lifespan events; included routers' lifespans are merged into it, mounted apps' lifespans are not.**

  • When a FastAPI app includes a router that has its own lifespan, in what order do they run and whose state wins?
    The app's lifespan is entered first and the router's inside it, so startup runs parent then router and shutdown runs router then parent. Their yielded dicts are merged into one lifespan state, and on a key both define the parent's value wins.
  • Why does an endpoint in a mounted FastAPI app see request.state.model from the parent's lifespan?
    The mount passes the request scope down unchanged in that respect, including the per-request copy of the parent's lifespan state. So the sub-app reads the parent's keys through `request.state`, while its own lifespan, which never ran, contributes none.

  • app.mount() runs the mounted app's lifespan just like include_router does.
  • A mounted app's lifespan runs lazily on the first request it receives.
  • Any lifespan problem would fail at startup, so a clean boot proves it ran.
  • Values set on the parent's app.state are visible on the sub-app's app.state.