DEV Community

Cover image for Day 8: Background Tasks in FastAPI โ€” Build an Email Logger!
Utkarsh Rastogi
Utkarsh Rastogi

Posted on • Edited on

Day 8: Background Tasks in FastAPI โ€” Build an Email Logger!

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
Enter fullscreen mode Exit fullscreen mode

Now, create a new Python file named day8_logger.py and import the required modules:

from fastapi import FastAPI, BackgroundTasks

app = FastAPI()
Enter fullscreen mode Exit fullscreen mode

โœ‰๏ธ 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")
Enter fullscreen mode Exit fullscreen mode

๐Ÿš€ 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"}
Enter fullscreen mode Exit fullscreen mode

โœ… 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"}
Enter fullscreen mode Exit fullscreen mode

๐Ÿงช 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
Enter fullscreen mode Exit fullscreen mode

โœ… 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:

Click "Try it out" โž "Execute"

Input

โœ… You will receive a JSON response immediately, while the background task logs the email to a file.

Output


โœ… Step 3: Verify the Log File

After calling the API, check if the email log was recorded in the email_logs.txt

logs

๐ŸŽ‰ 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)