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 regulardeffunction, 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 useasync def, you're telling FastAPI that this function can be paused and resumed. Inside anasync deffunction, you can use theawaitkeyword 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 defwhen your function has I/O-bound operations you canawait. This includes:- Making HTTP requests to external APIs with libraries like
httpx. - Querying a database with an async driver.
- Reading or writing to files.
- Making HTTP requests to external APIs with libraries like
Use
defwhen:- Your function is purely CPU-bound (e.g., performing complex calculations, image processing). Making it
asyncwon't make the CPU work faster. - You are using a library that doesn't support
asyncio(i.e., it's a blocking library).
- Your function is purely CPU-bound (e.g., performing complex calculations, image processing). Making it
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:
- Import
BackgroundTasksfromfastapi. - Add a parameter of type
BackgroundTasksto your path operation function. - Use the
add_task()method on thebackground_tasksobject to schedule a function to run in the background.
Example: Sending a Welcome Email
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:
pip install httpxMaking an Asynchronous Request:
To make an async request, you'll use httpx.AsyncClient.
Example: Fetching Data from an External API
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.
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
- FastAPI Documentation on Concurrency: https://fastapi.tiangolo.com/async/
- FastAPI Documentation on Background Tasks: https://fastapi.tiangolo.com/tutorial/background-tasks/
- HTTPX Documentation: https://www.python-httpx.org/
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:
Create a standard synchronous function named
send_welcome_notificationthat accepts a single parameter,email. For this challenge, the function body can simply bepass.Create a
POSTendpoint at the path/register.The endpoint function must be asynchronous (
async def).The endpoint must accept a
BackgroundTasksinstance via dependency injection and a request body parameteremailwhich is a string.Inside the endpoint, use
httpx.AsyncClientto make an asynchronousGETrequest to a mock external service athttps://api.mockservice.io/validate_email/{email}to check if the email is valid. You must use anasync withblock for the client andawaitthe request.After the
awaitcall, use theBackgroundTasksinstance to schedule thesend_welcome_notificationfunction to run in the background. Pass the user'semailto it.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:
A synchronous function
send_welcome_notification(email: str)with apassstatement in its body.An asynchronous
POSTendpoint 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 withblock, there must be a line that awaits aGETrequest:response = await client.get(f"https://api.mockservice.io/validate_email/{email}"). - Following the
async withblock,background_tasks.add_task(send_welcome_notification, email)must be called. - The function must conclude by returning
{"status": "User registration processing"}.
- The function signature must be