Simultaneous Task Execution in FastAPI

Gopal Katariya
3 min readMar 30, 2024

--

Introduction

In today’s fast-paced world of web development, efficiency is key. Asynchronous programming has become a game-changer in the realm of web servers, allowing developers to execute multiple tasks concurrently, thus optimizing performance and responsiveness. In this guide, we’ll delve into how to run two tasks simultaneously in FastAPI, a modern web framework for building APIs with Python.

Real-world example:

In a web-based chat application, while one task handles incoming messages, another task updates the online status of users. This simultaneous execution ensures a smooth user experience without delays in message processing or status updates, enhancing the overall responsiveness of the application.

Step 1: Setting Up the Environment

First and foremost, ensure you have FastAPI and Uvicorn installed in your Python environment. If not, you can install them using pip:

pip install fastapi uvicorn

Step 2: Writing the Code

Let’s begin by writing the code to run two tasks simultaneously in FastAPI. Below is a sample code snippet illustrating this:

main.py

from fastapi import FastAPI
import asyncio
import uvicorn

app = FastAPI()

async def task1():
for i in range(10):
print("task1 ", i)

async def task2():
for i in range(10):
print("task2 ", i)

@app.get('/start')
async def start():
task1_coroutine = asyncio.create_task(task1())
task2_coroutine = asyncio.create_task(task2())

await asyncio.gather(task1_coroutine, task2_coroutine)

if __name__ == '__main__':
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)

Step 3: Understanding the Code

In the provided code, we define two asynchronous tasks, task1 and task2, each performing some dummy operations in a loop. Then, in the /start endpoint, we create tasks for task1 and task2 using asyncio.create_task(), which converts the functions into awaitable coroutines. Finally, we use asyncio.gather() to run both tasks concurrently.

Step 4: Running the Application

To run the FastAPI application, execute the following command in your terminal:

python main.py

Step 5: Testing the Endpoint

Once the server is up and running, you can test the /start endpoint using tools like cURL or Postman. Make a GET request to http://localhost:8000/start observe the output in your terminal, showcasing the simultaneous execution of both tasks.

You can go to http://localhost:8000/docs Swagger UI also.

Conclusion:

In this guide, we’ve explored how to leverage asynchronous programming in FastAPI to run multiple tasks concurrently. By following the steps outlined above, you can enhance the performance and responsiveness of your FastAPI applications, thereby providing a seamless experience for your users. Asynchronous programming opens up a world of possibilities for building efficient and scalable web services, and mastering it can greatly benefit your development endeavors.

Feel free to connect:

LinkedIN : https://www.linkedin.com/in/gopalkatariya44/

Github : https://github.com/gopalkatariya44/

Instagram : https://www.instagram.com/_gk_44/

Twitter: https://twitter.com/GopalKatariya44

Youtube: https://youtube.com/@gopalkatariya44

Thanks 😊 !

--

--

Gopal Katariya
Gopal Katariya

Written by Gopal Katariya

AI Engineer | Machine Learning Enthusiast | Transforming Ideas into Intelligent Solutions

No responses yet