Performance: Async vs sync decision
This affects how quickly the server can respond to requests and handle multiple users at once.
from fastapi import FastAPI import asyncio app = FastAPI() @app.get('/async') async def read_async(): await asyncio.sleep(2) # non-blocking wait return {'message': 'done'}
from fastapi import FastAPI app = FastAPI() @app.get('/sync') def read_sync(): import time time.sleep(2) # blocking wait return {'message': 'done'}
| Pattern | Concurrency | Event Loop Blocking | Response Delay | Verdict |
|---|---|---|---|---|
| Synchronous endpoint | Limited by thread pool size | Yes (blocks threads during I/O) | High under load | [X] Bad |
| Asynchronous endpoint | Multiple requests concurrently | Non-blocking event loop | Low even under load | [OK] Good |
async function over a def synchronous function?async def followed by the function name and parentheses.async def syntax; others are invalid Python syntax.from fastapi import FastAPI
import time
app = FastAPI()
@app.get('/sync')
def sync_endpoint():
time.sleep(2)
return {'message': 'Done'}
@app.get('/async')
async def async_endpoint():
await some_async_task()
return {'message': 'Done'}/sync and /async endpoints?sync_endpoint uses time.sleep(2), which blocks the thread and stops handling other requests during that time.async_endpoint uses await on an async task, allowing the server to handle other requests while waiting.@app.get('/data')
async def get_data():
result = time.sleep(1)
return {'result': result}time.sleep(1) is a blocking call that pauses the whole thread, including the async event loop.await asyncio.sleep(1) to avoid blocking the event loop.Pass the test and this pattern moves unknown