0
0
FastAPIframework~8 mins

Background tasks in FastAPI - Performance & Optimization

Choose your learning style9 modes available
Performance: Background tasks
MEDIUM IMPACT
Background tasks affect server response time and user interaction speed by offloading work from the main request cycle.
Performing slow operations like sending emails or processing files during a web request
FastAPI
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'}
The slow task runs after the response is sent, keeping the user interaction fast and responsive.
📈 Performance GainResponse returns immediately, improving INP and user experience.
Performing slow operations like sending emails or processing files during a web request
FastAPI
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'}
The slow operation blocks the response, increasing user wait time and hurting interaction speed.
📉 Performance CostBlocks response for the duration of the slow task, increasing INP and user wait time.
Performance Comparison
PatternDOM OperationsReflowsPaint CostVerdict
Synchronous slow task in requestN/A (server-side)N/AN/A[X] Bad
Background task after responseN/A (server-side)N/AN/A[OK] Good
Rendering Pipeline
Background tasks run outside the main request-response cycle, so they do not block the server from sending the response quickly.
Request Handling
Response Sending
⚠️ BottleneckBlocking slow operations during request handling delay response and increase INP.
Core Web Vital Affected
INP
Background tasks affect server response time and user interaction speed by offloading work from the main request cycle.
Optimization Tips
1Always move slow or heavy operations to background tasks to keep responses fast.
2Background tasks improve user interaction speed by reducing server blocking time.
3Use FastAPI's BackgroundTasks to schedule work after sending the response.
Performance Quiz - 3 Questions
Test your performance knowledge
What is the main performance benefit of using background tasks in FastAPI?
AThey allow the server to respond faster by deferring slow work.
BThey reduce the size of the response payload.
CThey improve the visual layout stability of the page.
DThey increase the number of DOM nodes rendered.
DevTools: Network
How to check: Open DevTools Network panel, send a request, and observe the response time. Compare response times with and without background tasks.
What to look for: Faster response time and smaller blocking time indicate good use of background tasks.