Performance: Event-driven architecture
This affects how quickly the application responds to user actions and external events, impacting interaction responsiveness and server load.
from fastapi import FastAPI, BackgroundTasks app = FastAPI() @app.post('/process') async def process_data(data: dict, background_tasks: BackgroundTasks): background_tasks.add_task(long_running_task, data) return {'status': 'processing started'} def long_running_task(data): import time time.sleep(5) # Simulates background work # Save results or notify user asynchronously
from fastapi import FastAPI app = FastAPI() @app.post('/process') async def process_data(data: dict): # Blocking call result = long_running_task(data) return {'result': result} def long_running_task(data): import time time.sleep(5) # Simulates blocking operation return 'done'
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Blocking synchronous task in request handler | N/A | N/A | N/A | [X] Bad |
| Background task with FastAPI BackgroundTasks | N/A | N/A | N/A | [OK] Good |
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
results = []
def write_log(message: str):
results.append(message)
@app.post('/send')
async def send_message(background_tasks: BackgroundTasks):
background_tasks.add_task(write_log, 'Message sent')
return {'status': 'ok'}
# After calling POST /send once, what is the value of results?from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
@app.post('/notify')
async def notify():
background_tasks.add_task(print, 'Notify event')
return {'message': 'Notification sent'}Pass the test and this pattern moves unknown