Phase 18 of 25 · Topic 18.5

Background Tasks & WebSockets in FastAPI

1Concept

FastAPI `BackgroundTasks` offloads light post-response jobs (e.g. sending confirmation emails, recording audit logs) without delaying the HTTP response. `WebSocket` endpoints enable real-time bidirectional streaming.

2Architecture Diagram

Client POST /order ---> Receives 200 OK immediately
                    ---> [ BackgroundTask ] sends email asynchronously in background

3Code Example

Python 3.12
streaming_example = '''
from fastapi import FastAPI, BackgroundTasks, WebSocket

app = FastAPI()

def send_email_notification(email: str, order_id: int):
    print(f"Dispatched email to {email} for Order {order_id}")

@app.post("/checkout")
async def checkout(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(send_email_notification, email, 101)
    return {"status": "ORDER_PLACED", "message": "Email sending in background"}

@app.websocket("/ws/telemetry")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    await websocket.send_text("Telemetry Stream Connected")
    await websocket.close()
'''
print("=== Background Tasks & WebSockets Pipeline ===")
print(streaming_example.strip())

4Expected Output

=== Background Tasks & WebSockets Pipeline ===
from fastapi import FastAPI, BackgroundTasks, WebSocket

app = FastAPI()

def send_email_notification(email: str, order_id: int):
    print(f"Dispatched email to {email} for Order {order_id}")

@app.post("/checkout")
async def checkout(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(send_email_notification, email, 101)
    return {"status": "ORDER_PLACED", "message": "Email sending in background"}

@app.websocket("/ws/telemetry")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    await websocket.send_text("Telemetry Stream Connected")
    await websocket.close()

5Key Takeaways

  • Use `BackgroundTasks` for light tasks within the same process; use Celery/RabbitMQ for heavy compute.
  • WebSockets support streaming audio, chat messages, and live market updates.
  • Accept WebSocket connections with `await websocket.accept()` before sending data.