Python / FastAPI Interview Questions
What are BackgroundTasks in FastAPI and when should you use them?
BackgroundTasks let you run work after returning a response to the client — for lightweight fire-and-forget tasks like sending emails or writing audit logs. The response is sent immediately and the task runs afterward in the same process.
from fastapi import FastAPI, BackgroundTasks
from pydantic import BaseModel
app = FastAPI()
def send_welcome_email(email: str, username: str):
# Simulate sending an email (could call an email service)
print(f"Sending welcome email to {email} for {username}")
def write_audit_log(action: str, user_id: int):
print(f"Audit: user {user_id} performed {action}")
class UserIn(BaseModel):
username: str
email: str
@app.post("/register", status_code=201)
def register_user(user: UserIn, background_tasks: BackgroundTasks):
# Response is returned immediately
# Email is sent after the response
background_tasks.add_task(
send_welcome_email,
email=user.email,
username=user.username,
)
background_tasks.add_task(write_audit_log, "register", user_id=42)
return {"message": f"User {user.username} created"}
# BackgroundTasks can also be injected via dependencies
def get_background(background_tasks: BackgroundTasks) -> BackgroundTasks:
return background_tasksLimitations: BackgroundTasks run in the same process and event loop — if the server restarts, queued tasks are lost. For heavy, reliable background work use Celery, ARQ, or FastAPI + Redis Queue instead.
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...
