To async or not to async? #5227
-
|
In all the examples from the doc, I see path operation functions using @app.get("/")
async def root():
return {"message": "Hello World"}Why not just use The FastAPI doc states:
Those functions are run in an external threadpool
Those functions are executed in the event loop
Those functions, like the one in the example, are executed in the event loop too. Is there any advantage in doing that? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
If you use endpoint function or dependency declared with |
Beta Was this translation helpful? Give feedback.
If you use endpoint function or dependency declared with
def(notasync def), FastAPI will execute them in thread pool.This brings some overheads. If you are sure your endpoint is light-weight (don't contain heavy computations or other sync blocking code), it't better to make this function
async. This way it will be executed in event loop and avoid those overheads with using thread pool.