In FastAPI, why does a dependency used by both a sub-dependency and the endpoint run once per request, and what does use_cache=False change?
answer
- one dictionary per request
- keyed by the dependable object
- same returned object everywhere
- per declaration, not global
basics
~20 sFastAPI keeps a cache for each request, keyed by the dependable callable, so a dependency declared in several places in one request is called once and every consumer receives the same returned object. Depends(f, use_cache=False) makes that declaration call f again.
solid answer
~40 sWhile solving one request, FastAPI stores each dependency's result in a per-request dictionary keyed by the dependable itself (plus any security scopes its subtree uses and a yield dependency's `scope`). When `require_admin` depends on `get_current_user` and the endpoint also asks for `CurrentUser`, the first resolution calls `get_current_user`, and the second finds the entry and reuses the very same object. The cache is thrown away with the request, so the next request calls it again. `use_cache` defaults to `True`; `Depends(get_current_user, use_cache=False)` makes only that declaration skip the lookup and call the function again, which you want for something meant to be fresh at each use, such as a timestamp or a nonce.
code
python · 41 linesfrom typing import Annotated
from fastapi import Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient
app = FastAPI()
calls = 0
def get_current_user() -> dict:
global calls
calls += 1
return {"name": "ana", "role": "admin", "call": calls}
CurrentUser = Annotated[dict, Depends(get_current_user)]
def require_admin(user: CurrentUser) -> dict:
if user["role"] != "admin":
raise HTTPException(status_code=403)
return user
@app.get("/reports")
def reports(admin: Annotated[dict, Depends(require_admin)], user: CurrentUser):
return {"same_object": admin is user, "call": user["call"]}
@app.get("/reports-fresh")
def reports_fresh(
admin: Annotated[dict, Depends(require_admin)],
user: Annotated[dict, Depends(get_current_user, use_cache=False)],
):
return {"same_object": admin is user, "call": user["call"]}
client = TestClient(app)
print(client.get("/reports").json())
print(client.get("/reports").json())
print(client.get("/reports-fresh").json())go deeper
Remember that a dependency declared twice in one request runs once by default, and that use_cache=False makes a declaration call it again.
Explain the per-request dictionary, what forms its key, the depth-first order that decides which declaration resolves first, and that all consumers share one object.
Diagnose dependencies that run too often or too rarely from the tree, spot shared-object mutation bugs, and keep per-process caching out of request dependencies.
Set conventions for which dependencies may be relied on as once per request and which must be explicitly fresh, so permission checks and endpoints never disagree.
## The scenario A listing endpoint needs the current user, and so does a permission check that guards it: ```python CurrentUser = Annotated[dict, Depends(get_current_user)] def require_admin(user: CurrentUser) -> dict: ... @app.get("/reports") def reports(admin: Annotated[dict, Depends(require_admin)], user: CurrentUser): ... ``` `get_current_user` appears twice in the tree: once under `require_admin`, once directly on the endpoint. It typically decodes a token and loads a user row, so running it twice would double the work and could even return two different objects if the row changed in between. ## How the per-request cache works FastAPI resolves the tree **depth-first, in declaration order**. While doing so it carries a dictionary, the **dependency cache**, that lives for exactly one request: 1. It reaches `require_admin`, which needs `get_current_user`. 2. `get_current_user` is not in the cache, so FastAPI calls it and stores the result. 3. `require_admin` runs with that user. 4. It reaches the endpoint's own `user` parameter, finds `get_current_user` in the cache and reuses the stored value without calling the function. The endpoint therefore receives the **same Python object** in `admin` and `user`; in the example `admin is user` is `True`. The **cache key** is built from: - the dependable object itself, the function, class or instance you passed to `Depends`; - the OAuth2 security scopes in play, but only when that dependency's subtree uses scopes (covered with FastAPI's scope checks); - a yield dependency's `scope` (covered with yield teardown). Two declarations share an entry only when those parts are equal. Declaring the same function through an alias or spelled out makes no difference; passing a *different* object does. ## Lifetime: one request, never longer The dictionary is created when FastAPI starts solving a request and discarded with it. It is **not** a memo across requests: the next request calls `get_current_user` again, which is exactly what you want for per-user data. If you need a value computed once per process (settings, a loaded model), that is a different tool, such as the lifespan or `functools.lru_cache` on a settings function, covered with lifespan and settings. ## What `use_cache=False` changes `Depends` takes `use_cache: bool = True`. Setting it to `False` affects **only the declaration that carries it**: | Declaration | Behaviour in one request | |---|---| | `Depends(get_current_user)` (default) | reuse the stored value if present, else call and store | | `Depends(get_current_user, use_cache=False)` | always call again, ignoring any stored value | Two details worth knowing: - Other declarations of the same dependable keep sharing among themselves; one `use_cache=False` does not switch caching off for the whole request. - The flag stops that declaration from *reading* the cache. If a `use_cache=False` declaration happens to resolve first, FastAPI still records its result, and a later default declaration reuses it. Declaration order therefore decides which call the cached consumers see. Use it when each use must be fresh: a timestamp, a random nonce, a counter that must advance. Do not use it to "fix" a stale value across requests; the cache never spans requests anyway. ## Why it matters in practice - **Cost**: a token decode plus a database lookup happens once per request however many checks need the user. - **Consistency**: every consumer sees one user object, so a permission check and the endpoint cannot disagree about who is calling. - **Shared mutation**: because it is the same object, a dependency that mutates the value mutates it for every other consumer in that request. Return immutable data or copy deliberately. ## Diagnosing it When a dependency seems to run "too few" times, look for a second declaration higher in the tree that already resolved it. When it runs "too many" times, look for `use_cache=False` or for two different callable objects that look identical, such as two separately created instances. A quick way to see the behaviour is a counter, as in the example below: - Two requests to `/reports` print `call` 1 and then 2: one call per request, and a new cache each time. - `/reports-fresh` advances the counter by two in one request, and `admin is user` turns `False`, because the `use_cache=False` declaration produced a second object. Assert on such a counter in a test when the once-per-request guarantee matters, for example when the dependency writes an audit row or consumes a quota.
- In FastAPI, does the dependency cache keep a value between two requests from the same client?No. FastAPI creates a fresh dependency cache when it starts solving each request and discards it afterwards. Caching across requests needs something else, such as a lifespan-created object or `functools.lru_cache` on a settings function, and per-user data should not be cached that way at all.
- If a FastAPI dependency declared with use_cache=False resolves before a default declaration of the same function, how many calls happen?One. `use_cache=False` only stops that declaration from reading the cache; its result is still stored when no entry exists yet. The later default declaration then finds the entry and reuses it. Reverse the order and you get two calls, because the uncached declaration runs again after the first one stored its value.
- In FastAPI, why can a dependency that mutates its returned dict surprise other consumers in the same request?Every consumer of a cached dependency receives the same object, not a copy. If the permission check adds a key to the user dict, the endpoint sees that key too. Return immutable values, such as a frozen model, or copy explicitly when one consumer needs a modified view.
- Thinks FastAPI caches dependency results across requests by default.
- Says use_cache=False disables caching for every declaration in the request.
- Believes each consumer receives its own copy of a cached dependency's value.
- Expects a dependency used in two places to run twice per request by default.
- Uses use_cache=False to refresh data that went stale between requests.