Performance: Concurrent task execution
Concurrent task execution affects how quickly a FastAPI server can handle multiple requests or background tasks without blocking, improving responsiveness and throughput.
from fastapi import FastAPI import asyncio app = FastAPI() @app.get("/async-task") async def async_task(): await asyncio.sleep(5) # non-blocking sleep return {"message": "Task done"}
from fastapi import FastAPI import time app = FastAPI() @app.get("/sync-task") def sync_task(): time.sleep(5) # blocking sleep return {"message": "Task done"}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous blocking task | N/A | N/A | N/A | [X] Bad |
| Asynchronous non-blocking task | N/A | N/A | N/A | [OK] Good |
asyncio.create_task() in FastAPI?asyncio.create_task() purposeasyncio.gather() runs multiple coroutines concurrently and waits for all to complete.await asyncio.gather(func1(), func2()). await asyncio.create_task(func1()); await asyncio.create_task(func2()) starts tasks but awaits them separately, not concurrently. func1(); func2() runs functions synchronously. asyncio.run(func1(), func2()) is invalid syntax.import asyncio
from fastapi import FastAPI
app = FastAPI()
async def task1():
await asyncio.sleep(1)
return "Task 1 done"
async def task2():
await asyncio.sleep(2)
return "Task 2 done"
@app.get("/run")
async def run_tasks():
results = await asyncio.gather(task1(), task2())
return {"results": results}import asyncio
from fastapi import FastAPI
app = FastAPI()
async def task():
await asyncio.sleep(1)
return "Done"
@app.get("/test")
async def test():
task1 = asyncio.create_task(task())
task2 = asyncio.create_task(task())
return {"result": task1.result() + task2.result()}task1.result() immediately after creating the task tries to get the result before the task finishes, causing an error.await asyncio.gather(task1, task2) before accessing results.asyncio.gather() with return_exceptions=True lets all tasks run concurrently and collects exceptions as results without stopping others.asyncio.gather(task1(), task2(), task3(), return_exceptions=True) and process results for exceptions. correctly runs all tasks concurrently and handles errors individually. Use await task1(); await task2(); await task3() sequentially and catch exceptions globally. runs tasks sequentially, losing concurrency. Use asyncio.create_task() for each task but do not await them before returning. does not await tasks, so results are unavailable. Run tasks synchronously in a loop and catch exceptions inside each. runs synchronously, blocking concurrency.Pass the test and this pattern moves unknown