When to use sync vs async

31-10-2025

import asyncio
import asyncpg
from fastapi import FastAPI
 
app = FastAPI()
 
 
# CASE 1: non-blocking
@app.get("/health")
async def health_check():  # async router function
    return {"status": "healthy"}
 
# CASE 2: non-blocking (io-bound)
@app.get("/call_other_service")
async def call_other_service():  # async router function
    data = await _fetch_db_data()
    return {"data": data}
 
async def _fetch_db_data():  # async function (io-intensive work; requires async database driver)
    conn = await asyncpg.connect(database='dbname', host='localhost')
    rows = await conn.fetch("SELECT * FROM your_table WHERE some_column = 'some_value'")
    await conn.close()
    return rows
 
# CASE 3: blocking (cpu-bound)
@app.get("/factorize")
async def factorize():  # async router function
    loop = asyncio.get_running_loop()
    result = await loop.run_in_executor(None, _factorize)
    return result
 
def _factorize():  # sync function (CPU-intensive work)
    ...