Python / FastAPI Basics Interview Questions
How do you integrate FastAPI with Celery for reliable background task processing?
FastAPI's built-in BackgroundTasks is suitable for lightweight, lossy tasks. For tasks that must be reliable, retried, scheduled, or distributed across workers, use Celery with a broker (Redis or RabbitMQ).
# pip install celery redis # celery_app.py from celery import Celery celery_app = Celery( "worker", broker="redis://localhost:6379/0", backend="redis://localhost:6379/1", ) celery_app.conf.task_serializer = "json" @celery_app.task(bind=True, max_retries=3, default_retry_delay=60) def send_email(self, email: str, subject: str, body: str): try: # call email service print(f"Sending {subject} to {email}") except Exception as exc: raise self.retry(exc=exc) # retry up to 3 times
# main.py â FastAPI triggers Celery tasks from fastapi import FastAPI from pydantic import BaseModel from celery_app import send_email app = FastAPI() class EmailRequest(BaseModel): to: str subject: str body: str @app.post("/send-email", status_code=202) def trigger_email(req: EmailRequest): # .delay() sends the task to the broker queue task = send_email.delay(req.to, req.subject, req.body) return {"task_id": task.id, "status": "queued"} @app.get("/tasks/{task_id}") def task_status(task_id: str): from celery.result import AsyncResult result = AsyncResult(task_id) return {"task_id": task_id, "status": result.status}
# Run the Celery worker (separate process) # celery -A celery_app worker --loglevel=info
More Related questions...