Skip to content

Conversation

dolfinus
Copy link
Contributor

@dolfinus dolfinus commented Aug 6, 2025

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:
profile_proxy_with_auth_and_cache

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

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.

@dolfinus dolfinus force-pushed the feature/cache-inspect-result branch 5 times, most recently from 1e3a3c0 to b558ae2 Compare August 6, 2025 11:23
@dolfinus dolfinus changed the title ✨ Cache callable inspect result ✨ Cache callable inspection result Aug 6, 2025
@dolfinus dolfinus force-pushed the feature/cache-inspect-result branch from b558ae2 to cb4f5e0 Compare August 6, 2025 13:39
@dolfinus dolfinus changed the title ✨ Cache callable inspection result ⚡️ Cache callable inspection result Aug 6, 2025
@dolfinus dolfinus force-pushed the feature/cache-inspect-result branch from cb4f5e0 to 06a0b1e Compare August 6, 2025 15:42
@dolfinus dolfinus marked this pull request as ready for review August 7, 2025 09:37
@alejsdev alejsdev added the feature New feature or request label Aug 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feature New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants