Welcome to Day 8 of the FastAPI Zero to Hero ๐ series!
Today, we dive into something powerful and often overlooked โ Background Tasks in FastAPI. Whether itโs sending emails, logging activity, or processing images โ not everything needs to block the userโs response.
FastAPI gives us a sleek way to handle this via BackgroundTasks
.
๐ง What Youโll Learn Today
- What are background tasks?
- How to use
BackgroundTasks
in FastAPI - Build a mini project: Log email in the background
- Real-world use cases of background tasks
โณ Why Use Background Tasks?
Letโs say you need to send a confirmation email or write to a log file after a user signs up. These actions can take time, and we donโt want the user to wait for them.
Thatโs where BackgroundTasks
shines!
Instead of waiting for the task to complete, the response is sent back immediately, and the task runs in the background โ improving the user experience.
๐ง Step 1: Import What We Need
Install FastAPI and Uvicorn if you havenโt already:
pip install fastapi uvicorn
Now, create a new Python file named day8_logger.py
and import the required modules:
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
โ๏ธ Step 2: Define a Background Function
Letโs simulate sending an email by logging it to a file:
def log_email(email: str, message: str):
with open("email_logs.txt", mode="a") as file:
file.write(f"Email sent to: {email} | Message: {message}\n")
๐ Step 3: Use BackgroundTasks in Your Endpoint
@app.post("/send-email/")
async def send_email(
email: str, message: str, background_tasks: BackgroundTasks
):
background_tasks.add_task(log_email, email, message)
return {"message": f"Email will be sent to {email} in the background"}
โ
Full Code: day8_logger.py
from fastapi import FastAPI, BackgroundTasks
app = FastAPI()
# Background task function
def log_email(email: str, message: str):
with open("email_logs.txt", mode="a") as file:
file.write(f"Email sent to: {email} | Message: {message}\n")
# API endpoint
@app.post("/send-email/")
async def send_email(
email: str, message: str, background_tasks: BackgroundTasks
):
background_tasks.add_task(log_email, email, message)
return {"message": f"Email will be sent to {email} in the background"}
๐งช How to Run This App
Follow these simple steps to run and test the FastAPI app locally.
โ Step 1: Run the FastAPI Server
In the same directory where your day8_logger.py
file is located, open your terminal and run:
uvicorn day8_logger:app --host 0.0.0.0 --reload --port 9000
โ Step 2: Test in Browser or Swagger UI
Open your browser and navigate to the built-in Swagger UI docs:
๐ http://localhost:9000/docs
Use the /send-email/
POST endpoint and enter the following parameters:
-
email
:[email protected]
-
message
:Hello from FastAPI background!
Click "Try it out" โ "Execute"
โ You will receive a JSON response immediately, while the background task logs the email to a file.
โ Step 3: Verify the Log File
After calling the API, check if the email log was recorded in the email_logs.txt
๐ This confirms that your background task ran successfully and logged the email!
๐งฉ Real-World Use Cases of BackgroundTasks
Here are some actual ways developers use BackgroundTasks
in production:
โ 1. Sending Emails
- Welcome emails
- Password resets
- Invoice receipts
๐ก๏ธ 2. Audit Logging
- Log user activity securely without slowing down the response
๐ฆ 3. File Post-Processing
- Resize or compress images
- Scan for viruses
๐ 4. Report Generation
- Create reports and email them later
- Notify the user when the report is ready
๐ฏ 5. Push to Event Queues
- Send events to Kafka, Amazon SQS, or EventBridge
๐ 6. Cache Invalidation
- Invalidate or update Redis or memory cache in the background
โ ๏ธ When NOT to Use It
BackgroundTasks
is not a job queue system like Celery or AWS SQS + Lambda.
Itโs best suited for tasks that are:
- โ Short
- โ Lightweight
- โ Non-blocking
Avoid using it for tasks that are:
- โ CPU-intensive
- โ Time-consuming
- โ Require retries or persistence
โก๏ธ In such cases, use Celery, RQ, Django-Q, or serverless solutions like AWS Lambda + SQS/EventBridge.
๐ง Summary Table
Use Case | Why BackgroundTasks Helps |
---|---|
Sending Emails | Avoids user wait time |
Logging | Lightweight & async |
File Post-Processing | Keeps UI snappy |
Report Generation | Offloads long job |
Queue/Event Push | Decouples services |
Cache Updates | Keeps system in sync |
๐งต Wrap-Up
In this post, you learned how to use FastAPIโs BackgroundTasks
to handle lightweight, non-blocking operationsโlike simulating email sendingโwithout slowing down your API responses.
โ We covered:
- What
BackgroundTasks
are and why they matter - Step-by-step implementation in FastAPI
- How to test and verify background execution
- Real-world use cases and when not to use it
๐ Whether you're building a SaaS platform, an internal tool, or a hobby project, BackgroundTasks
can help you offload tasks and keep your APIs responsive.
๐ Credits
Huge thanks to the FastAPI Official Documentation by Sebastiรกn Ramรญrez (@tiangolo) โ the best place to learn and explore everything about FastAPI.
๐จโ๐ป About Me
Hey there! Iโm Utkarsh Rastogi, an AWS Community Builder and passionate cloud-native enthusiast who loves building scalable backend systems and sharing knowledge with the community.
๐ Connect with me: Utkarsh Rastogi
๐ฌ Share Your Thoughts โ I'd Love Your Feedback!
If you enjoyed today's post or learned something new, I'd truly appreciate it if you leave a comment or share your thoughts ๐
Your feedback, questions, or even a quick โ๐ฅ Loved this!โ keeps me motivated to continue this journey and share more in the upcoming #FastAPIDaily posts.
โ
What did you find most helpful?
โ
Anything you'd like explained in the next part?
โ
Suggestions for improvement? Iโm all ears! ๐
Letโs grow and learn together โ one FastAPI day at a time ๐
Top comments (0)