Sobes.tech
Middle

How to run synchronous blocking code (for example, a 1-second computation) in FastAPI on a route without blocking the EventLoop?

sobes.tech AI

Answer from AI

In FastAPI, to execute synchronous blocking code (for example, calculations that take 1 second) without blocking the main EventLoop, you should run this code in a separate thread or process. For this, the run_in_executor function from the asyncio module is used.

Example:

import time
import asyncio
from fastapi import FastAPI

app = FastAPI()

def blocking_task():
    time.sleep(1)  # blocking operation
    return "Done"

@app.get("/sync-task")
async def run_blocking():
    loop = asyncio.get_running_loop()
    result = await loop.run_in_executor(None, blocking_task)
    return {"result": result}

Here, run_in_executor runs blocking_task in the default thread pool, without blocking the EventLoop, allowing other requests to be processed in parallel.