fastapi-cache-di¶
Speed up FastAPI startup by caching its dependency-tree introspection.
At startup, FastAPI introspects every route's dependency tree — calling
get_typed_signature, get_dependant and, up to FastAPI 0.140,
get_flat_dependant — with no caching. Dependencies shared across many
routes (auth checks, DB handles, role guards …) are re-introspected from scratch
for every route. On a large API this dominates import/boot time.
fastapi-cache-di monkeypatches those functions to memoize their results for
the duration of route loading, then restores the originals. On FastAPI ≤ 0.140
the heavy one is get_flat_dependant, called once per route in
APIRoute.__init__: caching its recursive results turns
O(routes × tree-depth) into O(routes + unique-deps). FastAPI 0.141 removed
it, so only the other two are cached there.
Install¶
Install fastapi-cache-di with pip:
Or add it to your project with uv:
Quickstart¶
Wrap the code that loads your routes with the context manager:
from fastapi import APIRouter, FastAPI
from fastapi_cache_di import fastapi_deps_cache
app = FastAPI()
users = APIRouter()
orders = APIRouter()
billing = APIRouter()
with fastapi_deps_cache(warm_up=app):
# Registering routes introspects each dependency tree; caching is active here.
app.include_router(users)
app.include_router(orders)
app.include_router(billing)
# included routes built, originals restored here; cache memory freed
That is all it takes: introspection results are memoized while routes are being registered, and FastAPI's original functions are restored when the block exits.
See the usage guide for manual patching, sharing and inspecting a cache, thread-safety notes, and the opt-in runtime patches that call loop-safe dependencies on the event loop, skip re-walking the sub-tree of dependencies already cached for a request, and solve each route from a plan compiled once. See how it works for the caching internals, and the API reference for the full public API.
Requirements¶
- Python ≥ 3.12
- FastAPI ≥ 0.112.4
Note
0.112.4 is the floor: that is when FastAPI started calling
get_flat_dependant during route construction, which is the hot path this
library caches. Validated in CI up to FastAPI 0.143.1.
Support¶
This project is hosted on GitHub. Feel free to open an issue if you think you have found a bug or something is missing.
License¶
fastapi-cache-di is licensed under the MIT license.