Middle
FastAPI allows implementing functions as asynchronous and synchronous — how does this affect behavior? How to parallelize requests in an async function?
sobes.tech AI
Answer from AI
FastAPI supports both synchronous and asynchronous request handlers.
- Synchronous functions run in the main thread, and if they contain blocking operations (e.g., database queries without async driver), they block the processing of other requests.
- Asynchronous functions allow using
awaitfor non-blocking operations, which increases performance with a large number of concurrent requests.
However, if within an async function you call blocking code without an asynchronous interface, it negates the benefits of asynchronous programming.
To parallelize multiple asynchronous tasks within an async function, you can use asyncio.gather(). For example:
from fastapi import FastAPI
import asyncio
app = FastAPI()
async def fetch_data(x):
await asyncio.sleep(1) # simulate an asynchronous operation
return x * 2
@app.get("/parallel")
async def parallel_requests():
results = await asyncio.gather(
fetch_data(1),
fetch_data(2),
fetch_data(3),
)
return {"results": results}
Thus, requests inside async def are executed in parallel, reducing total waiting time.