Sobes.tech
Middle

Look at the code of the FastAPI application. Can we remove async from the handler function (replace async def with def)? Will it work, are there any features?

sobes.tech AI

Answer from AI

In FastAPI, handlers can be either asynchronous (async def) or synchronous (def). If you remove async and make the function a regular synchronous one, the application will work, but with some features:

  • Asynchronous handlers allow efficient processing of a large number of concurrent requests, especially if there are input-output operations inside (e.g., database queries or external services).
  • Synchronous handlers block the thread while the function executes, which can reduce performance under high load.
  • If asynchronous calls are used inside the function, they cannot be called from a synchronous function without additional wrapping.

Example of a synchronous handler:

from fastapi import FastAPI

app = FastAPI()

@app.get("/sync")
def read_sync():
    return {"message": "This is a synchronous handler"}

And asynchronous:

@app.get("/async")
async def read_async():
    return {"message": "This is an asynchronous handler"}

Conclusion: you can remove async if there are no asynchronous operations inside and the load is not critical. For scalability and performance, it is better to use async.