accelerate fastapi coldstart for function as a service (AWS lambda, ...)
Project description
fastapi-lazyrouter
fastapi-lazyrouter improves the cold start of a FastAPI application that has hundreds of Pydantic models. FastAPI scans all models at startup and Pydantic must generate a schema for each of them. This operation takes time, especially on nested and complex models.
At some point, the loading time exceeds the allowed time for the host to start the application. For example, on AWS Lambda, the application must be able to start in less than 10 seconds.
fastapi-lazyrouter prevents FastAPI from scanning routes at startup by dynamically mounting routers as requests come in.
- startup time reduced by up to 3x
- minimal overhead on the first requests since only the used routers are loaded
- import strategy is preserved
- minimally intrusive
- API documentation loading is preserved: the first request to
/docsor/openapi.jsonwill take longer because all routers need to be loaded (not implemented yet)
Getting started
pip install fastapi-lazyrouter
The latest version
You can find the latest version to ...
git clone https://github.com/FabienArcellier/fastapi-lazyrouter.git
Usage
Auto (Recommended)
Configure Pydantic model
from pydantic import BaseModel, ConfigDict
class CustomBaseModel(BaseModel):
model_config = ConfigDict(defer_build=True) # enable defer_build, otherwise there is no effect
Enable FastAPI router
import fastapi
import fastapi_lazyrouter
app = fastapi.FastAPI()
fastapi_lazyrouter.autoconfigure(app)
Manual usage
If you want to understand what is happening under the hood.
Configure Pydantic model
from pydantic import BaseModel, ConfigDict
class CustomBaseModel(BaseModel):
model_config = ConfigDict(defer_build=True) # enable defer_build, otherwise there is no effect
Replace ApiRouter with LazyApiRouter
from fastapi_lazyrouter import LazyApiRouter
router = LazyApiRouter(prefix="/items")
@router.get("/")
def list_items():
return []
Add middleware to FastAPI
from fastapi import FastAPI
from fastapi_lazyrouter import LazyApiRouterMiddleware
app = FastAPI()
app.add_middleware(LazyApiRouterMiddleware)
Publish the library on pypi
The publication use a tag-based workflow to run the publication on github action. First, a developper tag a commit using alfred publish, then github action publish the library on pypi.
The alfred publish take the version number from pyproject.toml. The command will raise an error if the current branch is not master, if changes are in progress, or if the tag already exists, if the branch is not synchronized with remote branch
alfred publish
Run in gitpod
gitpod can be used as an IDE. You can load the code inside to try the code.
Developper guideline
Add a dependency
bash poetry add requests
Install development environment
Use make to instanciate a python virtual environment in ./venv and install the python dependencies.
poetry install
Update release dependencies
Use make to instanciate a python virtual environment in ./venv and freeze dependencies version
poetry update update
Activate the python environment
When you setup the requirements, a venv directory on python 3 is created.
To activate the venv, you have to execute :
source .venv/bin/activate
Run the continuous integration process
Before commit or send a pull request, you have to execute pylint to check the syntax
of your code and run the unit tests to validate the behavior.
$ poetry run alfred ci
Contributors
- Fabien Arcellier
License
MIT License
Copyright (c) 2026-2026 Fabien Arcellier
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file fastapi_lazyrouter-0.1.0rc4.tar.gz.
File metadata
- Download URL: fastapi_lazyrouter-0.1.0rc4.tar.gz
- Upload date:
- Size: 6.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.4.0 CPython/3.12.13 Linux/6.17.0-1010-azure
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3b3671f7fb26bf6d557d1a0472b9b20854ce7d3088b0b40c853350414aee7f01
|
|
| MD5 |
dd9a2537e1d1c81717bb3697a8b06702
|
|
| BLAKE2b-256 |
e0a23e037fc71b63912162de729c0bedfda263679209d018dbf19ba1e4936c3b
|
File details
Details for the file fastapi_lazyrouter-0.1.0rc4-py3-none-any.whl.
File metadata
- Download URL: fastapi_lazyrouter-0.1.0rc4-py3-none-any.whl
- Upload date:
- Size: 7.9 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: poetry/2.4.0 CPython/3.12.13 Linux/6.17.0-1010-azure
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
3f75c8cac9c73ffbcf924a08129f02bb21cbfbee4bf5b474ac3f9b24aca14334
|
|
| MD5 |
7b5437b09f2795cebd5f784fd8af2a39
|
|
| BLAKE2b-256 |
2935aefeebe219a06a2c84d0e3d9d60832602130ac2698f2b41f8515d860de8d
|