Run background threads with FastAPI

David Y.

The Problem

I’m building an API server in Python using FastAPI. Apart from responding to API requests, I need this server to do some other operations in the background, such as long-running data processing operations requested by certain API calls. How can I implement these background tasks on a separate thread so that they do not block my API from processing requests?

The Solution

FastAPI provides the BackgroundTasks class for this purpose. Here’s some example code showing how to run a background task that writes to a log file:

from fastapi import FastAPI, BackgroundTasks # import BackgroundTasks from pydantic import BaseModel class Data(BaseModel): data: str app = FastAPI() # define background task def write_log(message: str): with open("log.txt", "a") as log: log.write(f"{message}\n") @app.post("/submit-data/") async def submit_data(data: Data, background_tasks: BackgroundTasks): background_tasks.add_task(write_log, f"Data received: {data.data}") # add task to queue return {"message": "Data is being processed in the background."}

Every time a request is sent to the /submit-data/ endpoint, our code will schedule a new run of the write_log function, passing it the data from the API call using background_tasks.add_task. Our server will immediately respond to the client, without waiting for write_log to finish. In the background, all of the tasks in the task queue will be executed in order.

We can add additional background tasks by writing functions for them and adding calls to these functions to the task queue in the same way. Note that tasks can be synchronous (def task_name) or asynchronous (async def task_name).

For more complex and intensive background operations that are not directly tied to the API’s operations, consider creating a separate application that uses a task queue, such as Celery. This will require additional setup, such as configuring a Redis server, but will also provide considerably more power and flexibility. FastAPI’s Full Stack Project Generator can be used to generate a FastAPI project with a configured Celery instance.

Loved by over 4 million developers and more than 90,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

    TwitterGitHubDribbbleLinkedinDiscord
© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.