Choosing between async and sync helps your FastAPI app handle tasks efficiently. Async lets your app do many things at once, while sync does one thing at a time.
0
0
Async vs sync decision in FastAPI
Introduction
When your app needs to handle many users at the same time without waiting.
When your code calls slow operations like database queries or web requests.
When you want simple code that runs step-by-step without extra complexity.
When you have CPU-heavy tasks that don't benefit from async.
When integrating with libraries that only support synchronous calls.
Syntax
FastAPI
async def function_name(): # async code here def function_name(): # sync code here
Use async def to define asynchronous functions.
Use regular def for synchronous functions.
Examples
This is a synchronous route handler. It runs step-by-step.
FastAPI
from fastapi import FastAPI app = FastAPI() @app.get("/sync") def read_sync(): return {"message": "This is sync"}
This is an asynchronous route handler. It can pause and let other tasks run during
await.FastAPI
from fastapi import FastAPI import asyncio app = FastAPI() @app.get("/async") async def read_async(): await asyncio.sleep(1) return {"message": "This is async"}
Sample Program
This FastAPI app has two endpoints. The /sync endpoint blocks for 1 second, stopping other tasks. The /async endpoint waits 1 second without blocking, letting other tasks run.
FastAPI
from fastapi import FastAPI import asyncio app = FastAPI() @app.get("/sync") def sync_endpoint(): # Simulate a blocking task import time time.sleep(1) return {"message": "Finished sync task"} @app.get("/async") async def async_endpoint(): # Simulate a non-blocking task await asyncio.sleep(1) return {"message": "Finished async task"}
OutputSuccess
Important Notes
Async is great for waiting on slow tasks like network calls.
Sync is simpler and good for quick or CPU-heavy tasks.
Mixing async and sync incorrectly can cause problems; keep your code consistent.
Summary
Async lets your app handle many things at once by waiting without blocking.
Sync runs tasks one after another and can block other work.
Choose async for I/O-bound tasks and sync for CPU-bound or simple tasks.