Python / FastAPI 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
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
