Skip to main content

Background tasks

FastAPI provides an efficient and simple way to perform background tasks. These are tasks that you schedule to run after the request-response cycle completes. It's useful for tasks like sending emails, push notifications, or handling heavy computations that you don't want to process during the request-response cycle.

What are Background Tasks?

Background tasks in FastAPI are functions that you schedule to run after returning a response. They don't delay the response time because they execute independently of the request-response cycle.

Creating Background Tasks

To create a background task, first, you need to define a function for the task:

def write_log(message: str):
with open("log.txt", "a") as log:
log.write(message)

This function writes a message to a log file.

Then, create your FastAPI app and use the BackgroundTasks class to create a background task:

from fastapi import FastAPI, BackgroundTasks

app = FastAPI()

@app.post("/log/")
async def log_message(background_tasks: BackgroundTasks, message: str):
background_tasks.add_task(write_log, message)
return {"message": "Message logged!"}

In the log_message path operation, background_tasks is an instance of BackgroundTasks. You can add tasks to it using the add_task method. The first argument is the task function (in this case, write_log), followed by the task function's arguments.

When you send a POST request to "/log/" with a JSON body containing a message, FastAPI will:

  1. Take the message and pass it to the log_message function.
  2. Add the write_log function as a background task, with the message as an argument.
  3. Return a JSON response {"message": "Message logged!"}.
  4. After sending the response, FastAPI will execute the write_log function as a background task.

Limitations of Background Tasks

While background tasks can be incredibly useful, it's important to be aware of their limitations:

  • They run in the same process and thread as the request.
  • If a background task crashes, it won't be retried.
  • If the main FastAPI process finishes or crashes before the background tasks complete, they might not get executed.

For more robust background processing, consider using a task queue like Celery or RQ.

Conclusion

Background tasks are a powerful feature in FastAPI. They allow you to schedule tasks to run after the request-response cycle, helping keep your API responses quick. However, for heavy or more reliable background processing, consider using a dedicated task queue.

Remember to test your background tasks thoroughly, especially if they're critical to your application's functionality.