DEV Community

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

Posted on • Edited on

1 1

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:

  • email: test@example.com
  • message: Hello from FastAPI background!

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 🚀


Dev Diairies image

User Feedback & The Pivot That Saved The Project

🔥 Check out Episode 3 of Dev Diairies, following a successful Hackathon project turned startup.

Watch full video 🎥

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Announcing the First DEV Education Track: "Build Apps with Google AI Studio"

The moment is here! We recently announced DEV Education Tracks, our new initiative to bring you structured learning paths directly from industry experts.

Dive in and Learn

DEV is bringing Education Tracks to the community. Dismiss if you're not interested. ❤️