Developing a responsive and efficient web application is a paramount goal for developers. One common requirement is the ability to execute multiple tasks in parallel while being able to return an immediate response for the tasks that complete first. This blog post will walk you through a practical example using FastAPI to achieve just that.
The Challenge
Suppose you have three time-consuming tasks to run when an endpoint is triggered, but you want to provide an immediate response as soon as the first task completes, while the remaining tasks continue to run in the background.
Enter FastAPI and asyncio
FastAPI, coupled with Python’s asyncio
library, provides a robust way to handle such requirements. Below is a simple yet effective approach to tackle this challenge.
The Code
|
How It Works
- Define Async Functions: We define three asynchronous functions, each simulating a delayed task using
await asyncio.sleep()
.
- Create a FastAPI App: We initialize a FastAPI app instance,
app
.
- Design Endpoints: The
/run-tasks
endpoint triggers the execution of our defined tasks.
Execute and Await Tasks:
The first task (
first_sub_function()
) is awaited directly, meaning the endpoint will wait for its completion.The other two tasks (
second_sub_function()
andthird_sub_function()
) are started as background tasks usingasyncio.create_task()
.
- Immediate Response: The endpoint returns the result of the first task as soon as it’s available, while the remaining tasks continue to run in the background.
Run The Application
To run the FastAPI app, save the code in a file (e.g., main.py
) and run the following command:
|