Skip to the page

FastAPI · Trade-off

async def or plain def in FastAPI

The interviewer asks

In FastAPI, when do you write an endpoint as async def and when as plain def? What does FastAPI do differently with each?

Then

Follow-ups the interviewer asks next

  1. Where does a def endpoint run, and how many can run at once?
  2. What happens if an async def endpoint calls requests.get() or time.sleep()?
  3. Your get_db dependency is a plain def. Does that matter for an async def endpoint?
  4. How do you call a blocking library from an async def endpoint?
  5. Does any of this help with CPU-heavy work?

The answer

What a strong answer covers

  • async def endpoints run on the event loop and must only await non-blocking calls (httpx.AsyncClient, async database drivers). One blocking call freezes every request in that worker process.
  • Plain def endpoints and def dependencies run in a thread pool and are awaited. AnyIO's default limit is 40 threads per process, so 40 slow calls fill it and the rest queue.
  • Rule of thumb: async def when everything inside is async; def when you call blocking libraries (a classic SQLAlchemy session, requests, many vendor SDKs).
  • Inside async def, wrap blocking calls with await run_in_threadpool(fn, ...) (Starlette) or anyio.to_thread.run_sync.
  • CPU work (PDF parsing, image resizing, big pandas jobs) blocks the loop in async def and competes for the GIL in threads; send it to a process pool or a worker queue. Free-threaded Python 3.14t exists and FastAPI supports it since 0.136, but check that every library you use supports it too.
  • Signs of a blocked loop: even /health is slow; an event-loop lag metric jumps; py-spy dump shows the main thread inside a blocking call.

The red pen

Common traps

Avoid:"always use async def, it's faster"; requests inside async def; thinking def endpoints run one at a time.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview