# Run Background Tasks in FastAPI with BackgroundTasks

> Use FastAPI BackgroundTasks class to run long-running operations without blocking API responses, with examples for task queuing and Celery alternatives

**URL:** https://sentry.io/answers/run-background-threads-with-fastapi/

---

## 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`](https://fastapi.tiangolo.com/tutorial/background-tasks/) class for this purpose. Here's some example code showing how to run a background task that writes to a log file:

```python
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`](https://fastapi.tiangolo.com/reference/background/#fastapi.BackgroundTasks.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](https://docs.celeryq.dev/en/stable/). 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](https://fastapi.tiangolo.com/project-generation/) can be used to generate a FastAPI project with a configured Celery instance.

---

*Source: [sentry.io/answers/run-background-threads-with-fastapi/](https://sentry.io/answers/run-background-threads-with-fastapi/)*
