Middle
How to solve the event loop blocking problem in FastAPI when using synchronous code?
sobes.tech AI
Answer from AI
In FastAPI, which is built on an asynchronous event loop (usually uvicorn + asyncio), executing long synchronous operations blocks the event loop and slows down the processing of other requests.
To avoid blocking the event loop when using synchronous code, you can:
- Offload synchronous code to a separate thread or process using
run_in_executor:
import asyncio
from fastapi import FastAPI
app = FastAPI()
def blocking_io():
# Long synchronous operation
import time
time.sleep(5)
return "done"
@app.get("/sync")
async def read_sync():
loop = asyncio.get_running_loop()
result = await loop.run_in_executor(None, blocking_io)
return {"result": result}
-
Use asynchronous libraries instead of synchronous ones, if possible.
-
Rewrite critical parts of the code in an asynchronous style.
Thus, run_in_executor allows running blocking code in a separate thread without blocking the main FastAPI event loop.