⚡ Decrease import time with deferred OpenAPI model building#10546
⚡ Decrease import time with deferred OpenAPI model building#10546sam-mosleh wants to merge 2 commits intofastapi:masterfrom
Conversation
|
These files contain import time measurements that can be viewed to gain insight into the performance improvements achieved by this pull request: |
|
Thanks you, @sam-mosleh! |
YuriiMotov
left a comment
There was a problem hiding this comment.
@sam-mosleh, thanks for working on this!
Can confirm significant improvement in import time (i got ~25% decrease).
If this is helpful for those who are using FastAPI on AWS Lambda or similar, I don't see any blockers to merge this.
If the idea is accepted, we will need to document it
| return with_info_plain_validator_function(cls._validate) | ||
|
|
||
|
|
||
| _FASTAPI_OPENAPI_DEFER_BUILD = "FASTAPI_OPENAPI_DEFER_BUILD" in os.environ |
There was a problem hiding this comment.
As an alternative:
_FASTAPI_OPENAPI_DEFER_BUILD = (
os.environ.get("FASTAPI_OPENAPI_DEFER_BUILD", "").lower() in ("1", "true", "yes")
)
I think this would be a bit better since in current implementation it might be confusing if people set variable to "0" or "false"
|
This pull request has a merge conflict that needs to be resolved. |

This pull request introduces a performance improvement for importing FastAPI, with the potential for up to a 40% reduction in import times. This optimization is particularly crucial for environments like AWS Lambda, where OpenAPI schemas are typically not required to get built during cold starts. The key enhancement in this PR is the utilization of the
defer_buildoption in Pydantic, which has been available since version 2.3.0.Performance Difference:
To quantify the impact of these changes, performance measurements were taken:
python -X importtime -c "import fastapi"FASTAPI_OPENAPI_DEFER_BUILD=true python -X importtime -c "import fastapi"