• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Fast API Request Handling

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
In FastAPI, how route handlers (endpoints) behave in terms of parallelism and concurrency depends on whether they are defined using async def or def, and whether the work inside them is I/O-bound or CPU-bound.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.



Here are the four combinations of route handlers and how they affect parallel or concurrent handling of requests:

✅ 1. async def with async I/O-bound work (e.g., await asyncio.sleep, database calls)


@router.get("/async-io")
async def async_io_route():
await asyncio.sleep(2)
return {"status": "async io"}
  • Handled concurrently
  • Non-blocking — multiple such requests can be handled at the same time.
  • Best performance for I/O tasks like DB queries, network calls, file access.
✅ 2. async def with CPU-bound work (e.g., heavy computation, no await)


@router.get("/async-cpu")
async def async_cpu_route():
result = sum(i * i for i in range(10**7))
return {"result": result}
  • Not truly concurrent for CPU-bound work.
  • Blocks the event loop — slows down other async endpoints.
  • BAD practice — use a thread pool for CPU-bound tasks instead.
✅ 3. def with CPU-bound work


@router.get("/sync-cpu")
def sync_cpu_route():
result = sum(i * i for i in range(10**7))
return {"result": result}
  • Parallel execution via thread pool executor (Starlette/FastAPI handles this).
  • Slower than async I/O but doesn't block the event loop.
  • Suitable for CPU-bound work when properly limited.
✅ 4. def with I/O-bound work (e.g., time.sleep)


@router.get("/sync-io")
def sync_io_route():
time.sleep(2)
return {"status": "sync io"}
  • Blocks thread and wastes resources.
  • Not concurrent nor parallel in a performant way.
  • Worst option — avoid using blocking I/O in sync routes.
Summary Table

Route TypeI/O TypeConcurrent?Notes
async defAsync I/O✅ YesBest option for scalable I/O-bound endpoints
async defCPU-bound❌ NoBlocks the event loop — BAD
defCPU-bound✅ ParallelRuns in thread pool — acceptable for CPU tasks
defBlocking I/O❌ NoBlocks threads — worst case, avoid
  • Use async def + await for I/O-bound operations.
  • Offload CPU-heavy operations to a thread/process pool (e.g., run_in_executor()).
  • Avoid blocking operations like time.sleep() in FastAPI routes.

Here’s a clear and concise table showing different FastAPI route types, the kind of operation they perform, and whether the request handling is parallel or concurrent:

? FastAPI Route Behavior Comparison

Route TypeOperation TypeExample Code SnippetBehaviorNotes
async defAsync I/O-boundawait asyncio.sleep(1)✅ ConcurrentBest for DB queries, API calls, file I/O, etc.
async defCPU-boundsum(i * i for i in range(10**7))❌ BlockingBlocks event loop – BAD pattern
async defCPU-bound (offload)await loop.run_in_executor(None, cpu_task)✅ ParallelOffloads to thread pool – does not block event loop
async defCPU-bound (multi-core)run_in_executor(ProcessPool, cpu_task)✅✅ True ParallelUses multiple CPU cores – best for heavy computations
defCPU-boundsum(i * i for i in range(10**7))✅ ParallelRuns in thread pool – doesn't block event loop
defBlocking I/Otime.sleep(2)❌ BlockingWastes threads – avoid blocking I/O in sync functions
✅ Legend

  • Concurrent: Multiple tasks share the same thread (async I/O).
  • Parallel: Tasks run in separate threads or processes simultaneously.
  • Blocking: One task prevents others from proceeding.


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу