Performance: Async path operations
This affects server response time and how quickly the browser receives data, impacting page load speed and interaction responsiveness.
from fastapi import FastAPI import asyncio app = FastAPI() @app.get("/data") async def get_data(): await asyncio.sleep(2) # non-blocking sleep return {"message": "Data fetched"}
from fastapi import FastAPI app = FastAPI() @app.get("/data") def get_data(): import time time.sleep(2) # blocking sleep return {"message": "Data fetched"}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous blocking path operation | N/A | N/A | Delays response, increasing INP | [X] Bad |
| Async non-blocking path operation | N/A | N/A | Faster response, better INP | [OK] Good |
async def for path operations in FastAPI?async def allows the server to pause on waiting tasks and handle other requests meanwhile.await.async def followed by the function name and parentheses.def. def async read_item(): return {'item': 'value'} incorrectly places async after def./wait?
from fastapi import FastAPI
import asyncio
app = FastAPI()
@app.get('/wait')
async def wait_seconds():
await asyncio.sleep(1)
return {'message': 'Done waiting'}asyncio.sleep is awaitable.from fastapi import FastAPI
app = FastAPI()
@app.get('/data')
def get_data():
await fetch_data()
return {'status': 'ok'}await inside a function requires the function to be declared with async def.def but uses await, causing a syntax error. Missing async keyword before function definition correctly identifies this.async def and await. def get_user():
user = fetch_user_from_db()
return user is synchronous and misses await. async def get_user():
user = fetch_user_from_db()
return user is async but misses await. def get_user():
user = await fetch_user_from_db()
return user uses await in a normal function, which is invalid.Pass the test and this pattern moves unknown