FastAPI Best Practices
Limit Only One Access to Endpoint at a Time
Limit only one access to an endpoint at a time with asyncio.Lock
in asyncio
in FastAPI.
fastapi_request_lock.py
loading...
NOTE: The
asyncio.Lock
only take effect in theasyncio
loop level, if usingunicorn
to run server in multiple processes, it can not lock the request!
No limitation.
fastapi_request_nolock.py
loading...
Limit only one access to an endpoint at a time with thread.Lock
Limit only one access to an endpoint at a time with process.Lock
Attach A Background Service Into the Application
Run a background service behind the FastAPI server:
- share the same
asyncio
main loop with the server - the service start when the server starts and stop when the server stops
- it should be light-weight and non-CPU heavy workload
Coroutines and Tasks — Python 3.11.4 documentation Event Loop — Python 3.11.4 documentation
fastapi_background_service.py
loading...