Ojasa Mirai

Ojasa Mirai

FastAPI

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🚀 Middleware📚 Background Tasks📚 WebSockets📚 CORS📚 Dependencies📚 Dependency Injection📚 Async Programming📚 Performance
Fastapi/Advanced Patterns/Background Tasks

Background Tasks

Learn the fundamentals of background tasks in FastAPI.

🎯 Core Concept

Background tasks allow you to queue work that runs after returning a response to the client. This keeps response times fast while handling long-running operations like email, PDF generation, or log processing asynchronously.

📖 What You'll Learn

In this section, you'll understand:

  • Using `BackgroundTasks` for queued work
  • Running tasks after response is sent
  • Multiple background tasks in one endpoint
  • Long-running operations without blocking
  • Email and async processing patterns

💡 Simple Background Task

from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def write_log(filename: str, message: str):
    # This runs in background after response sent
    with open(filename, "a") as f:
        f.write(f"{message}\n")

@app.post("/send-notification")
async def send_notification(
    email: str,
    background_tasks: BackgroundTasks
):
    # Send response immediately
    background_tasks.add_task(write_log, "log.txt", f"Notified: {email}")
    return {"status": "notification queued"}

Email Background Task

def send_email(email: str, subject: str, body: str):
    # Slow operation, doesn't block response
    smtp_server = smtplib.SMTP(host="localhost", port=2525)
    message = EmailMessage()
    message["Subject"] = subject
    message["From"] = "noreply@example.com"
    message["To"] = email
    message.set_content(body)
    smtp_server.send_message(message)
    smtp_server.quit()

@app.post("/register")
async def register(user: User, background_tasks: BackgroundTasks):
    # Save user to database
    db.add(user)
    db.commit()

    # Queue email - response sent while this runs
    background_tasks.add_task(
        send_email,
        user.email,
        "Welcome!",
        f"Welcome {user.name}!"
    )
    return {"status": "registered"}

Multiple Background Tasks

@app.post("/order-checkout")
async def checkout(
    order: Order,
    background_tasks: BackgroundTasks
):
    # Save order
    saved_order = db.add(order)
    db.commit()

    # Queue multiple tasks
    background_tasks.add_task(
        send_email,
        order.customer_email,
        "Order Confirmed",
        f"Order {saved_order.id} confirmed"
    )
    background_tasks.add_task(
        notify_warehouse,
        saved_order.id
    )
    background_tasks.add_task(
        update_inventory,
        order.items
    )

    return {"order_id": saved_order.id, "status": "processing"}

Async Background Task

async def process_image(image_path: str):
    # Async operation in background
    async with aiohttp.ClientSession() as session:
        async with session.post(
            "https://ai-api.example.com/process",
            files={"image": open(image_path, "rb")}
        ) as response:
            result = await response.json()
            # Store result in database
            db.save_processed_image(image_path, result)

@app.post("/upload-image")
async def upload_image(file: UploadFile, background_tasks: BackgroundTasks):
    filename = f"uploads/{file.filename}"
    with open(filename, "wb") as f:
        f.write(file.file.read())

    background_tasks.add_task(process_image, filename)
    return {"filename": filename}

Real-World Usage

Background tasks are essential for:

  • **Email**: Send confirmations, notifications without delay
  • **Image Processing**: Resize, optimize images async
  • **Logging**: Write detailed logs after response
  • **Reports**: Generate PDFs, exports in background
  • **External APIs**: Call webhooks, integrations async
  • **Database**: Heavy queries don't block responses

🔑 Key Takeaways

  • ✅ Understand the purpose of background tasks
  • ✅ Know when to apply this pattern
  • ✅ Recognize its benefits in real-world scenarios
  • ✅ Be prepared to use it in your projects

Ready to explore more? Check out the advanced section for production patterns and edge cases.


Resources

Python Docs

Ojasa Mirai

Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.

Learn Deep • Build Real • Verify Skills • Launch Forward

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn