0
0
FastAPIframework~5 mins

Concurrent task execution in FastAPI

Choose your learning style9 modes available
Introduction

Concurrent task execution lets your app do many things at the same time. This helps your app stay fast and responsive.

When your app needs to handle multiple user requests at once.
When you want to run background jobs without stopping the main app.
When you need to call several slow services or APIs together.
When you want to improve app speed by doing tasks in parallel.
Syntax
FastAPI
import asyncio
from fastapi import FastAPI

app = FastAPI()

@app.get("/tasks")
async def run_tasks():
    task1 = asyncio.create_task(some_async_function1())
    task2 = asyncio.create_task(some_async_function2())
    results = await asyncio.gather(task1, task2)
    return {"results": results}

Use async def for functions that run asynchronously.

asyncio.create_task() starts tasks concurrently.

Examples
Two simple async tasks that wait for some time and then return a message.
FastAPI
import asyncio

async def task1():
    await asyncio.sleep(1)
    return "Task 1 done"

async def task2():
    await asyncio.sleep(2)
    return "Task 2 done"
Run both tasks at the same time and wait for both to finish.
FastAPI
import asyncio

async def main():
    t1 = asyncio.create_task(task1())
    t2 = asyncio.create_task(task2())
    results = await asyncio.gather(t1, t2)
    print(results)
FastAPI endpoint that runs two tasks concurrently and returns their results.
FastAPI
from fastapi import FastAPI

app = FastAPI()

@app.get("/run")
async def run():
    t1 = asyncio.create_task(task1())
    t2 = asyncio.create_task(task2())
    results = await asyncio.gather(t1, t2)
    return {"results": results}
Sample Program

This FastAPI app has an endpoint /tasks that runs two tasks at the same time. Task 1 waits 1 second, Task 2 waits 2 seconds. The endpoint waits for both to finish and returns their messages together.

FastAPI
import asyncio
from fastapi import FastAPI

app = FastAPI()

async def task1():
    await asyncio.sleep(1)
    return "Task 1 done"

async def task2():
    await asyncio.sleep(2)
    return "Task 2 done"

@app.get("/tasks")
async def run_tasks():
    t1 = asyncio.create_task(task1())
    t2 = asyncio.create_task(task2())
    results = await asyncio.gather(t1, t2)
    return {"results": results}
OutputSuccess
Important Notes

Use asyncio.gather() to wait for many tasks at once.

Concurrent tasks help your app handle slow operations without freezing.

Remember to use async and await keywords properly.

Summary

Concurrent task execution lets your app do many things at once.

Use asyncio.create_task() and asyncio.gather() to run and wait for tasks.

FastAPI supports async endpoints to handle concurrent tasks easily.