# FastAPI Async Safe Dependencies
# Installation
```bash
pip install fastapi-async-safe-dependencies
```
# Introduction
FastAPI is a great framework for building APIs and the main purpose of this library is to make it a little bit better.
I guess someone (as I do) has a lot of class-based dependencies in your project.
But FastAPI comes with one little problem that will make your application slower than it could be.
Let's take a look at the following example from FastAPI documentation:
```python
from fastapi import Depends, FastAPI
app = FastAPI()
fake_items_db = [
{"item_name": "Foo"},
{"item_name": "Bar"},
{"item_name": "Baz"},
]
class CommonQueryParams:
def __init__(
self,
q: str | None = None,
skip: int = 0,
limit: int = 100,
) -> None:
self.q = q
self.skip = skip
self.limit = limit
@app.get("/items/")
async def read_items(commons: CommonQueryParams = Depends()):
response = {}
if commons.q:
response.update({"q": commons.q})
items = fake_items_db[commons.skip: commons.skip + commons.limit]
response.update({"items": items})
return response
```
This example is pretty simple and it works fine, but it has one little problem.
Whenever FastAPI tries to resolve `CommonQueryParams` dependency it will delegate object creation to
the thread-pool executor, which is not good for performance. It will happen with every request.
FastAPI logic is pretty simple, if `asyncio.iscoroutinefunction` returns `True` for the dependency, it will be called
as a simple coroutine, otherwise, it will be delegated to a thread-pool executor.
FastAPI is using `anyio.to_thread.run_sync` function to delegate object creation to the thread-pool executor.
`anyio` thread-pool executor has a limited number of threads (40 by default) which means that if you have more than 40
requests at the same time, some of them might be blocked until one of the threads from the pool is released.
Thread will be blocked by simple class instantiation, this is not CPU intensive operation,
that is not the type of task you want to delegate to the thread-pool executor.
This library provides a simple solution for this problem, that will avoid unnecessary thread-pool executor usage
for class-based dependencies and it should improve your application performance.
# Usage
Let's take a look at the same example, but with `fastapi-async-safe-dependencies` library:
```python
from fastapi import Depends, FastAPI
from fastapi_async_safe import async_safe, init_app
app = FastAPI()
init_app(app) # don't forget to initialize application
fake_items_db = [
{"item_name": "Foo"},
{"item_name": "Bar"},
{"item_name": "Baz"},
]
@async_safe # you just need to add this decorator to your dependency
class CommonQueryParams:
def __init__(
self,
q: str | None = None,
skip: int = 0,
limit: int = 100,
) -> None:
self.q = q
self.skip = skip
self.limit = limit
@app.get("/items/")
async def read_items(commons: CommonQueryParams = Depends()):
response = {}
if commons.q:
response.update({"q": commons.q})
items = fake_items_db[commons.skip: commons.skip + commons.limit]
response.update({"items": items})
return response
```
That's it, now your dependency will be called as simple coroutine, and it will not be delegated to the thread-pool.
Code above is equivalent to the following code:
```python
from fastapi import Depends, FastAPI
app = FastAPI()
fake_items_db = [
{"item_name": "Foo"},
{"item_name": "Bar"},
{"item_name": "Baz"},
]
class CommonQueryParams:
def __init__(
self,
q: str | None = None,
skip: int = 0,
limit: int = 100,
) -> None:
self.q = q
self.skip = skip
self.limit = limit
async def _common_query_params(
q: str | None = None,
skip: int = 0,
limit: int = 100,
) -> CommonQueryParams:
return CommonQueryParams(q=q, skip=skip, limit=limit)
@app.get("/items/")
async def read_items(commons: CommonQueryParams = Depends(_common_query_params)):
response = {}
if commons.q:
response.update({"q": commons.q})
items = fake_items_db[commons.skip: commons.skip + commons.limit]
response.update({"items": items})
return response
```
# Documentation
All you need to do is to add `@async_safe` decorator to your dependency class or synchronous function that
should not be delegated to the thread-pool executor.
```python
from typing import Any
from dataclasses import dataclass
from fastapi_async_safe import async_safe
@dataclass
@async_safe
class CommonQueryParams:
q: str | None = None
skip: int = 0
limit: int = 100
@async_safe
def common_query_params(
q: str | None = None,
skip: int = 0,
limit: int = 100,
) -> dict[str, Any]:
return {"q": q, "skip": skip, "limit": limit}
```
Both `CommonQueryParams` class and `common_query_params` function will not be delegated to the thread-pool executor.
If your class inherits from a class that is decorated with `@async_safe` decorator then this class will be `async-safe` too.
```python
from dataclasses import dataclass
from fastapi_async_safe import async_safe
@dataclass
@async_safe
class BaseQueryParams:
q: str | None = None
@dataclass # this class will be async-safe too
class CommonQueryParams(BaseQueryParams):
skip: int = 0
limit: int = 100
```
If you don't want your inherited class to be `async-safe` you can use `@async_unsafe` decorator.
```python
from dataclasses import dataclass
from fastapi_async_safe import async_safe, async_unsafe
@dataclass
@async_safe
class BaseQueryParams:
q: str | None = None
@dataclass
@async_unsafe # this class no longer will be async-safe
class CommonQueryParams(BaseQueryParams):
skip: int = 0
limit: int = 100
```
Also, don't forget to initialize your application with `init_app` function, otherwise, `@async_safe` decorator will not
have any effect. `init_app` function will monkey-patch `Dependant` instances on application startup.
```python
from fastapi import FastAPI
from fastapi_async_safe import init_app
app = FastAPI()
init_app(app) # don't forget to initialize application !!!
```
If you want to wrap all your class-based dependencies with `@async_safe` decorator you can pass `all_classes_safe=True`
argument to `init_app` function. It will wrap all your class-based dependencies expect those that are decorated with
`@async_unsafe` decorator.
```python
from fastapi import FastAPI
from fastapi_async_safe import init_app
app = FastAPI()
init_app(app, all_classes_safe=True)
```
# Benchmarks
Please take a look at the [benchmark](https://github.com/uriyyo/fastapi-async-safe-dependencies/tree/main/benchmark) directory for more details.
Performance boost depends on the number of class-based dependencies in your application, the more dependencies you have,
the more performance boost you will get.
Raw data
{
"_id": null,
"home_page": "https://github.com/uriyyo/fastapi-async-safe-dependencies",
"name": "fastapi-async-safe-dependencies",
"maintainer": "",
"docs_url": null,
"requires_python": ">=3.9,<4.0",
"maintainer_email": "",
"keywords": "",
"author": "Yurii Karabas",
"author_email": "1998uriyyo@gmail.com",
"download_url": "https://files.pythonhosted.org/packages/a6/01/df0498e7e88fe1babaee98f5f46ad6001db9c5eb7f3e5cc91121031148de/fastapi_async_safe_dependencies-0.1.1.tar.gz",
"platform": null,
"description": "# FastAPI Async Safe Dependencies\n\n# Installation\n\n```bash\npip install fastapi-async-safe-dependencies\n```\n\n# Introduction\n\nFastAPI is a great framework for building APIs and the main purpose of this library is to make it a little bit better.\nI guess someone (as I do) has a lot of class-based dependencies in your project.\nBut FastAPI comes with one little problem that will make your application slower than it could be.\n\nLet's take a look at the following example from FastAPI documentation:\n\n```python\nfrom fastapi import Depends, FastAPI\n\napp = FastAPI()\n\nfake_items_db = [\n {\"item_name\": \"Foo\"},\n {\"item_name\": \"Bar\"},\n {\"item_name\": \"Baz\"},\n]\n\nclass CommonQueryParams:\n def __init__(\n self,\n q: str | None = None,\n skip: int = 0,\n limit: int = 100,\n ) -> None:\n self.q = q\n self.skip = skip\n self.limit = limit\n\n@app.get(\"/items/\")\nasync def read_items(commons: CommonQueryParams = Depends()):\n response = {}\n if commons.q:\n response.update({\"q\": commons.q})\n items = fake_items_db[commons.skip: commons.skip + commons.limit]\n response.update({\"items\": items})\n return response\n```\n\nThis example is pretty simple and it works fine, but it has one little problem.\nWhenever FastAPI tries to resolve `CommonQueryParams` dependency it will delegate object creation to\nthe thread-pool executor, which is not good for performance. It will happen with every request.\n\nFastAPI logic is pretty simple, if `asyncio.iscoroutinefunction` returns `True` for the dependency, it will be called\nas a simple coroutine, otherwise, it will be delegated to a thread-pool executor.\n\nFastAPI is using `anyio.to_thread.run_sync` function to delegate object creation to the thread-pool executor.\n`anyio` thread-pool executor has a limited number of threads (40 by default) which means that if you have more than 40\nrequests at the same time, some of them might be blocked until one of the threads from the pool is released.\nThread will be blocked by simple class instantiation, this is not CPU intensive operation,\nthat is not the type of task you want to delegate to the thread-pool executor.\n\nThis library provides a simple solution for this problem, that will avoid unnecessary thread-pool executor usage\nfor class-based dependencies and it should improve your application performance.\n\n# Usage\n\nLet's take a look at the same example, but with `fastapi-async-safe-dependencies` library:\n\n```python\nfrom fastapi import Depends, FastAPI\nfrom fastapi_async_safe import async_safe, init_app\n\napp = FastAPI()\ninit_app(app) # don't forget to initialize application\n\nfake_items_db = [\n {\"item_name\": \"Foo\"},\n {\"item_name\": \"Bar\"},\n {\"item_name\": \"Baz\"},\n]\n\n@async_safe # you just need to add this decorator to your dependency\nclass CommonQueryParams:\n def __init__(\n self,\n q: str | None = None,\n skip: int = 0,\n limit: int = 100,\n ) -> None:\n self.q = q\n self.skip = skip\n self.limit = limit\n\n\n@app.get(\"/items/\")\nasync def read_items(commons: CommonQueryParams = Depends()):\n response = {}\n if commons.q:\n response.update({\"q\": commons.q})\n items = fake_items_db[commons.skip: commons.skip + commons.limit]\n response.update({\"items\": items})\n return response\n```\n\nThat's it, now your dependency will be called as simple coroutine, and it will not be delegated to the thread-pool.\n\nCode above is equivalent to the following code:\n\n```python\nfrom fastapi import Depends, FastAPI\n\napp = FastAPI()\n\nfake_items_db = [\n {\"item_name\": \"Foo\"},\n {\"item_name\": \"Bar\"},\n {\"item_name\": \"Baz\"},\n]\n\nclass CommonQueryParams:\n def __init__(\n self,\n q: str | None = None,\n skip: int = 0,\n limit: int = 100,\n ) -> None:\n self.q = q\n self.skip = skip\n self.limit = limit\n\n\nasync def _common_query_params(\n q: str | None = None,\n skip: int = 0,\n limit: int = 100,\n) -> CommonQueryParams:\n return CommonQueryParams(q=q, skip=skip, limit=limit)\n\n\n@app.get(\"/items/\")\nasync def read_items(commons: CommonQueryParams = Depends(_common_query_params)):\n response = {}\n if commons.q:\n response.update({\"q\": commons.q})\n items = fake_items_db[commons.skip: commons.skip + commons.limit]\n response.update({\"items\": items})\n return response\n```\n\n# Documentation\n\nAll you need to do is to add `@async_safe` decorator to your dependency class or synchronous function that\nshould not be delegated to the thread-pool executor.\n\n```python\nfrom typing import Any\nfrom dataclasses import dataclass\n\nfrom fastapi_async_safe import async_safe\n\n@dataclass\n@async_safe\nclass CommonQueryParams:\n q: str | None = None\n skip: int = 0\n limit: int = 100\n\n\n@async_safe\ndef common_query_params(\n q: str | None = None,\n skip: int = 0,\n limit: int = 100,\n) -> dict[str, Any]:\n return {\"q\": q, \"skip\": skip, \"limit\": limit}\n```\n\nBoth `CommonQueryParams` class and `common_query_params` function will not be delegated to the thread-pool executor.\n\nIf your class inherits from a class that is decorated with `@async_safe` decorator then this class will be `async-safe` too.\n\n```python\nfrom dataclasses import dataclass\n\nfrom fastapi_async_safe import async_safe\n\n@dataclass\n@async_safe\nclass BaseQueryParams:\n q: str | None = None\n\n\n@dataclass # this class will be async-safe too\nclass CommonQueryParams(BaseQueryParams):\n skip: int = 0\n limit: int = 100\n```\n\nIf you don't want your inherited class to be `async-safe` you can use `@async_unsafe` decorator.\n\n```python\nfrom dataclasses import dataclass\n\nfrom fastapi_async_safe import async_safe, async_unsafe\n\n@dataclass\n@async_safe\nclass BaseQueryParams:\n q: str | None = None\n\n\n@dataclass\n@async_unsafe # this class no longer will be async-safe\nclass CommonQueryParams(BaseQueryParams):\n skip: int = 0\n limit: int = 100\n```\n\nAlso, don't forget to initialize your application with `init_app` function, otherwise, `@async_safe` decorator will not\nhave any effect. `init_app` function will monkey-patch `Dependant` instances on application startup.\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_async_safe import init_app\n\napp = FastAPI()\ninit_app(app) # don't forget to initialize application !!!\n```\n\nIf you want to wrap all your class-based dependencies with `@async_safe` decorator you can pass `all_classes_safe=True`\nargument to `init_app` function. It will wrap all your class-based dependencies expect those that are decorated with\n`@async_unsafe` decorator.\n\n```python\nfrom fastapi import FastAPI\nfrom fastapi_async_safe import init_app\n\napp = FastAPI()\ninit_app(app, all_classes_safe=True)\n```\n\n# Benchmarks\n\nPlease take a look at the [benchmark](https://github.com/uriyyo/fastapi-async-safe-dependencies/tree/main/benchmark) directory for more details.\n\nPerformance boost depends on the number of class-based dependencies in your application, the more dependencies you have,\nthe more performance boost you will get.",
"bugtrack_url": null,
"license": "MIT",
"summary": "FastAPI async safe dependencies",
"version": "0.1.1",
"project_urls": {
"Homepage": "https://github.com/uriyyo/fastapi-async-safe-dependencies",
"Repository": "https://github.com/uriyyo/fastapi-async-safe-dependencies"
},
"split_keywords": [],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "341e1e6accc6f043d6a50c80503e1b8b3e189281209badf8ef80f04ce5b59156",
"md5": "7ef3c98d1723d2138bd30e9e11940da7",
"sha256": "f2873e408e32045a9e1cc6d5cfa4912446dbffe6bd80246d771a84cb5868a2b9"
},
"downloads": -1,
"filename": "fastapi_async_safe_dependencies-0.1.1-py3-none-any.whl",
"has_sig": false,
"md5_digest": "7ef3c98d1723d2138bd30e9e11940da7",
"packagetype": "bdist_wheel",
"python_version": "py3",
"requires_python": ">=3.9,<4.0",
"size": 7450,
"upload_time": "2024-01-25T10:00:12",
"upload_time_iso_8601": "2024-01-25T10:00:12.182207Z",
"url": "https://files.pythonhosted.org/packages/34/1e/1e6accc6f043d6a50c80503e1b8b3e189281209badf8ef80f04ce5b59156/fastapi_async_safe_dependencies-0.1.1-py3-none-any.whl",
"yanked": false,
"yanked_reason": null
},
{
"comment_text": "",
"digests": {
"blake2b_256": "a601df0498e7e88fe1babaee98f5f46ad6001db9c5eb7f3e5cc91121031148de",
"md5": "542dbb1a26d8b17aa00ce7e26cdc2480",
"sha256": "6d9d44b70e90f4b2e09ae02e5a1330106afa1f73cc80d16953fba55d38a6ff5b"
},
"downloads": -1,
"filename": "fastapi_async_safe_dependencies-0.1.1.tar.gz",
"has_sig": false,
"md5_digest": "542dbb1a26d8b17aa00ce7e26cdc2480",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.9,<4.0",
"size": 6333,
"upload_time": "2024-01-25T10:00:14",
"upload_time_iso_8601": "2024-01-25T10:00:14.239901Z",
"url": "https://files.pythonhosted.org/packages/a6/01/df0498e7e88fe1babaee98f5f46ad6001db9c5eb7f3e5cc91121031148de/fastapi_async_safe_dependencies-0.1.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-01-25 10:00:14",
"github": true,
"gitlab": false,
"bitbucket": false,
"codeberg": false,
"github_user": "uriyyo",
"github_project": "fastapi-async-safe-dependencies",
"travis_ci": false,
"coveralls": false,
"github_actions": true,
"lcname": "fastapi-async-safe-dependencies"
}