How do you implement background tasks in FastAPI?
Answer
FastAPI provides BackgroundTasks for running lightweight tasks after returning the response. Inject in the route: @app.post('/send-email') async def send(background_tasks: BackgroundTasks, email: str): background_tasks.add_task(send_email_func, email); return {'msg': 'Email scheduled'}. The response is sent immediately; the background task runs after. Limitations: tasks run in the same process/thread pool — they block the worker from other requests. Not suitable for long-running or CPU-intensive tasks. For heavier background work: Celery (distributed task queue with Redis/RabbitMQ broker) — the standard for production background jobs in Flask/FastAPI. ARQ (async task queue built for asyncio). For simple scheduled jobs: APScheduler. Background tasks are appropriate for sending notifications, webhooks, and cache invalidation after a request completes.
Previous
What is Flask's application factory pattern?
Next
What is Pydantic v2 and what changed from v1?