← Back to FastAPI, page 4

fastapi-0073 · Medium mid

How does FastAPI cache dependency results per request, and how do use_cache, router-level and application-level dependencies work?

Within one request, FastAPI calls each dependency once and reuses the result everywhere the same callable appears in the dependency tree (use_cache=True is the default). Depends(fn, use_cache=False) forces a fresh call. Dependencies can also be attached to a decorator (dependencies=[...]), to an APIRouter or include_router call, or to the whole FastAPI app: they run for every matching route and their return values are ignored.

Full answer

Per-request caching: if get_db is needed by get_current_user and by the endpoint, FastAPI calls get_db once and passes the same session to both. This keeps one session and one transaction per request, and avoids repeated work (decoding a JWT twice).

python
def audit(user=Depends(get_current_user)): ...
@app.get("/x", dependencies=[Depends(audit)])
def x(user=Depends(get_current_user)): ...      # get_current_user runs once

use_cache=False makes FastAPI call the dependency again each time it is declared (for counters, random IDs or fresh timestamps per use). The cache lives only for the current request; shared state across requests must be explicit (module-level objects, lru_cache, or app.state).

Attaching dependencies that do not return anything useful for the endpoint (checks, audits, rate limits):

  • Path operation: @app.get("/x", dependencies=[Depends(check)]).
  • Router: APIRouter(dependencies=[Depends(require_login)]) applies to every route in it, and include_router(router, dependencies=[...]) adds more at inclusion time.
  • Application: FastAPI(dependencies=[Depends(log_request)]) applies to all routes (including those in routers).

Order: application dependencies run first, then router, then path decorator, then parameters of the function; yield dependencies exit in reverse order. Exceptions raised in a dependency stop the chain and return the error response.

Caveats: decorator-level dependencies cannot inject values into the function; declare the dependency also as a parameter when you need its value (it is still cached). Global dependencies do not apply to mounted sub-apps. Sync dependencies run in the thread pool, async ones on the event loop; mixing is fine but blocking work in async dependencies stalls the loop.

python
from typing import Annotated

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

log = []


def get_db():
    log.append("get_db")
    return "session"


def current_user(db: Annotated[str, Depends(get_db)]):
    log.append("current_user")
    return "asha"


def audit(user: Annotated[str, Depends(current_user)]):
    log.append("audit")


def request_log():
    log.append("app-level")


def require_login(user: Annotated[str, Depends(current_user)]):
    log.append("router-level")


def stamp():
    log.append("stamp")
    return len(log)


router = APIRouter(prefix="/students", dependencies=[Depends(require_login)])
app = FastAPI(dependencies=[Depends(request_log)])


@router.get("/", dependencies=[Depends(audit)])
def students(db: Annotated[str, Depends(get_db)], user: Annotated[str, Depends(current_user)]):
    log.append("endpoint")
    return {"db": db, "user": user}


@router.get("/stamps")
def stamps(a: Annotated[int, Depends(stamp)], b: Annotated[int, Depends(stamp)],
           c: Annotated[int, Depends(stamp, use_cache=False)]):
    return {"a": a, "b": b, "c": c}


app.include_router(router)
c = TestClient(app)
c.get("/students/")
print(log)
log.clear()
print(c.get("/students/stamps").json(), log)

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): ['app-level', 'get_db', 'current_user', 'router-level', 'audit', 'endpoint'] {'a': 5, 'b': 5, 'c': 6} ['app-level', 'get_db', 'current_user', 'router-level', 'stamp', 'stamp']

Key points

  • Dependencies are cached per request by default
  • use_cache=False forces a fresh call
  • dependencies=[...] on a route, router or app runs without injecting values
  • Order: app, router, path decorator, then function parameters
  • Mounted sub-apps do not inherit global dependencies

Common mistakes

  • Expecting dependencies to run again for each use within one request
  • Expecting decorator-level dependencies to provide values to the function
  • Assuming global dependencies apply to mounted sub-apps
  • Sharing mutable state between requests through default arguments
  • Doing blocking work in async dependencies

Follow-ups

  • How do yield dependencies and caching interact?
  • In what order do dependencies exit?
  • How would you apply authentication to every route except health checks?

Tips

  • Explain per-request caching
  • List the three attachment levels
  • State the run order