⚡️ Cache callable inspection result #13974
Open
+171
−35
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Currently FastAPI calls
inspect.signature
,inspect.isgeneratorfunction
,inspect.isasyncgenfunction
,inspect.iscoroutinefunction
, etc for each callable found in dependency tree, and this is done for each received request.This can be avoided by introducing a cache for methods result. As callable objects are usually created once and never change after that, this cache can be bound to endpoint or even whole application. Using WeakKeyDictionary helps to avoid memory leaks then callables are created in runtime (e.g. by using
functools.partial
).This cache is different from dependency cache - dependency cache stores values of resolved dependencies (non reusable between requests), then callable info cache stores signatures and other information about code (reusable between requests).
Before -

app (fastapi/routing.py)
takes 68.27% of all method calls:After -

app (fastapi/routing.py)
takes 54.52% of all method calls:The code is ugly as walking on dependency tree requires passing cache deep into dependency resolvers. Also lots of intermediate functions have default argument values, which are not used in most cases, but I have to follow this pattern.