Performance: Background tasks
Background tasks affect server response time and user interaction speed by offloading work from the main request cycle.
from fastapi import FastAPI, BackgroundTasks app = FastAPI() def send_email_sync(email: str, content: str): # Slow operation pass @app.post('/send-email') async def send_email(data: dict, background_tasks: BackgroundTasks): background_tasks.add_task(send_email_sync, data['email'], data['content']) return {'status': 'email scheduled'}
from fastapi import FastAPI app = FastAPI() @app.post('/send-email') async def send_email(data: dict): # Slow operation done inline send_email_sync(data['email'], data['content']) return {'status': 'email sent'}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous slow task in request | N/A (server-side) | N/A | N/A | [X] Bad |
| Background task after response | N/A (server-side) | N/A | N/A | [OK] Good |
BackgroundTasks in FastAPI?background_tasks.add_task(function, args) inside the endpoint function.background_tasks.add_task(your_function, arg1, arg2) inside the endpoint correctly uses add_task. Call your_function() directly inside the endpoint calls function immediately, blocking. Use await your_function() inside the endpoint awaits function, blocking. Import BackgroundTasks but do not use it does nothing.from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
def write_log(message: str):
print(f"Log: {message}")
@app.get("/items/{item_id}")
async def read_item(item_id: int, background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, f"Item {item_id} accessed")
return {"item_id": item_id}write_log is scheduled as a background task, so it runs after the response is sent.write_log will execute after response, printing the log message with the item_id value.from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
def send_email(email: str):
print(f"Sending email to {email}")
@app.post("/send")
async def send(background_tasks: BackgroundTasks, email: str):
background_tasks.add_task(send_email)
return {"message": "Email scheduled"}send_email requires an argument email, but add_task is called without arguments.background_tasks.add_task(send_email, email) to pass the email parameter.background_tasks.add_task schedules both tasks as background tasks, so they run after response. Options B and C block response. Run logging in background task but send email synchronously delays sending email.Pass the test and this pattern moves unknown