Learn FastAPI Β· 9/14

Background Tasks and Concurrency

6 min read

πŸš€ Background Tasks and Concurrency in FastAPI

Welcome back! Today, we're diving into some of the magic that makes FastAPI so fast and efficient: concurrency and background tasks. Don't worry, we'll break it down piece by piece, so you'll be juggling tasks like a pro in no time.


1. Async vs Sync: Understanding Concurrency in FastAPI πŸ€–

The Problem: Why Do We Need Concurrency?

Imagine a popular coffee shop with only one barista. This barista takes an order, makes the coffee, and then serves it before even looking at the next customer. If making one coffee takes a few minutes, the line of caffeine-deprived (and increasingly grumpy) customers will quickly grow out the door.

In the world of web servers, this is what's known as blocking or synchronous execution. Each request is handled one at a time, and if a request involves a slow operation (like waiting for a database or an external API), every other request has to wait. This can lead to a slow and unresponsive application.

The Solution: Asynchronous Code to the Rescue!

Now, what if our barista could start brewing a coffee, and while it's brewing, take the next customer's order? This is the essence of asynchronous programming. It allows a program to handle multiple tasks concurrently, by not waiting for slow operations to finish.

FastAPI is built on an asynchronous framework called Starlette, which allows it to handle many requests at once without getting bogged down.

def vs. async def in FastAPI

In FastAPI, you can define your endpoint functions in two ways: with the standard def or with async def.

  • def (Synchronous): When you use a regular def function, FastAPI is smart enough to know it might contain blocking code. To prevent it from blocking the whole server, FastAPI runs it in a separate thread pool. This is like having a team of assistant baristas who can take over a time-consuming order, freeing up the main barista to serve other customers. However, managing these threads has some overhead.

  • async def (Asynchronous): When you use async def, you're telling FastAPI that this function can be paused and resumed. Inside an async def function, you can use the await keyword on I/O-bound operations. This is like our main barista starting a coffee brew, and while it's brewing (await), they can handle other quick tasks. This is highly efficient for I/O-bound operations.

When to use which?

  • Use async def when your function has I/O-bound operations you can await. This includes:

    • Making HTTP requests to external APIs with libraries like httpx.
    • Querying a database with an async driver.
    • Reading or writing to files.
  • Use def when:

    • Your function is purely CPU-bound (e.g., performing complex calculations, image processing). Making it async won't make the CPU work faster.
    • You are using a library that doesn't support asyncio (i.e., it's a blocking library).

A funny exaggeration: Using def for a heavy database query is like sending a raven with a message and then staring at the sky until it returns. Using async def with await is like sending the raven and then going about your day, knowing it will tap on your window when it has a reply.


2. Background Tasks: Running Operations After Response Delivery πŸƒβ€β™€οΈπŸ’¨

The Problem: Don't Make the User Wait

Imagine a user signs up on your website. You want to send them a welcome email. If you send the email before confirming their registration, they have to wait for the email to be sent before they see a "success" message. This can make your application feel sluggish.

The Solution: BackgroundTasks

FastAPI provides a BackgroundTasks class that allows you to run tasks after a response has been sent to the client. This is perfect for operations that the user doesn't need to wait for, like sending notifications, logging, or processing data.

How to use it:

  1. Import BackgroundTasks from fastapi.
  2. Add a parameter of type BackgroundTasks to your path operation function.
  3. Use the add_task() method on the background_tasks object to schedule a function to run in the background.

Example: Sending a Welcome Email

python
from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

def send_welcome_email(email: str, message: str):
    """
    A placeholder function to simulate sending an email.
    In a real application, this would contain your email sending logic.
    """
    with open("log.txt", mode="a") as log:
        log.write(f"Message to {email}: {message}\n")

@app.post("/register")
async def register_user(email: str, background_tasks: BackgroundTasks):
    # Your user registration logic here
    message = f"Welcome, {email}! Thanks for registering."
    background_tasks.add_task(send_welcome_email, email, message)
    return {"message": "User registered successfully!"}

Now, when a user registers, they'll get an immediate response, and the email will be "sent" in the background.

A word of caution: Background tasks run in the same process as your application. If your application crashes, the background task might be lost. For critical, long-running, or heavy tasks, consider using a dedicated task queue like Celery.


3. Making External Async HTTP Calls with HTTPX 🌐

The Problem: Blocking HTTP Requests

It's very common for an API to need to communicate with other APIs. If you use a traditional, synchronous HTTP library like requests, each call will block the execution of your async function, defeating the purpose of using async in the first place.

The Solution: HTTPX

HTTPX is a modern HTTP client for Python that supports both synchronous and asynchronous requests. It's the recommended library for making HTTP calls in FastAPI.

Installation:

If you installed FastAPI with the full option, httpx is already included. Otherwise, you can install it separately:

bash
pip install httpx

Making an Asynchronous Request:

To make an async request, you'll use httpx.AsyncClient.

Example: Fetching Data from an External API

python
import httpx
from fastapi import FastAPI

app = FastAPI()

@app.get("/get-external-data")
async def get_external_data():
    async with httpx.AsyncClient() as client:
        response = await client.get("https://jsonplaceholder.typicode.com/todos/1")
        return response.json()

In this example, await client.get(...) will pause the execution of our function until the response is received, allowing FastAPI to handle other requests in the meantime.

Pro-Tip: Managing the Client Lifecycle

For better performance, it's a good practice to reuse the httpx.AsyncClient across multiple requests. You can achieve this using FastAPI's lifespan events.

python
import httpx
from fastapi import FastAPI
from contextlib import asynccontextmanager

@asynccontextmanager
async def lifespan(app: FastAPI):
    # Initialize the client on startup
    app.state.http_client = httpx.AsyncClient()
    yield
    # Close the client on shutdown
    await app.state.http_client.aclose()

app = FastAPI(lifespan=lifespan)

@app.get("/get-external-data-optimized")
async def get_external_data_optimized():
    response = await app.state.http_client.get("https://jsonplaceholder.typicode.com/todos/1")
    return response.json()

This approach creates a single AsyncClient instance when the application starts and closes it gracefully on shutdown, which is more efficient.


πŸ“š Extra Reading and References

Challenge

Challenge: Asynchronous User Registration with Background Notification

Your task is to implement a user registration endpoint in a FastAPI application. This endpoint must perform an asynchronous external API call to validate user data and then schedule a non-blocking background task to send a welcome notification.

Requirements:

  1. Create a standard synchronous function named send_welcome_notification that accepts a single parameter, email. For this challenge, the function body can simply be pass.

  2. Create a POST endpoint at the path /register.

  3. The endpoint function must be asynchronous (async def).

  4. The endpoint must accept a BackgroundTasks instance via dependency injection and a request body parameter email which is a string.

  5. Inside the endpoint, use httpx.AsyncClient to make an asynchronous GET request to a mock external service at https://api.mockservice.io/validate_email/{email} to check if the email is valid. You must use an async with block for the client and await the request.

  6. After the await call, use the BackgroundTasks instance to schedule the send_welcome_notification function to run in the background. Pass the user's email to it.

  7. The endpoint should immediately return the JSON response: {"status": "User registration processing"} without waiting for the background task to complete.

Expected result

Your code should define a complete FastAPI application with two main components:

  1. A synchronous function send_welcome_notification(email: str) with a pass statement in its body.

  2. An asynchronous POST endpoint function decorated with @app.post("/register").

    • The function signature must be async def register_user(email: str, background_tasks: BackgroundTasks):.
    • Inside the function, there must be an async with httpx.AsyncClient() as client: block.
    • Within the async with block, there must be a line that awaits a GET request: response = await client.get(f"https://api.mockservice.io/validate_email/{email}").
    • Following the async with block, background_tasks.add_task(send_welcome_notification, email) must be called.
    • The function must conclude by returning {"status": "User registration processing"}.
python

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.