Skip to the page

FastAPI · mid

async def or def in FastAPI, and a blocked event loop

async def endpoints run on the event loop and must never block. Plain def endpoints run in a thread pool of limited size. A slow call in the wrong place stalls the whole process.

The notes

What you must know

  • async def endpoints run on the event loop and may only await non-blocking calls (httpx.AsyncClient, async database drivers). One blocking call freezes every request in that process.
  • Plain def endpoints and def dependencies run in a thread pool. AnyIO's default limit is 40 threads per process. 40 slow calls fill it and other requests queue.
  • Use async def when everything inside is async; use def when you call blocking libraries (a classic SQLAlchemy session, requests, many vendor SDKs).
  • Inside async def, wrap blocking calls with run_in_threadpool (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. Use a process pool or a worker queue.
  • Signs of a blocked loop: even /health is slow, an event-loop lag metric jumps, py-spy dump shows the main thread in a blocking call. CPU is low.
  • A slow partner API with def endpoints: 20-second calls hold threads, others wait in line. An async def endpoint that depends on a def dependency also needs a thread. Fix: timeouts (connect 2 s, read 5 s), a circuit breaker, httpx.AsyncClient with a semaphore (a bulkhead), or queue the job and return 202.
  • Do not raise the thread limit to 500: more memory, GIL contention and database connections. A liveness probe should catch dead processes, not busy ones; fix the blocking, not the probe.

The red pen

Common traps: mistake → fix

  • Mistake: async def is always faster than def

    Fix: a blocking call in async def is worse than def.

  • Mistake: More threads fix a slow partner

    Fix: the queue moves somewhere worse.

  • Mistake: Low CPU means the service is healthy

    Fix: low CPU with high latency means waiting or blocking.

  • Mistake: Wrapping CPU work in a thread makes it parallel

    Fix: the GIL still applies.

Easy to hard

Questions interviewers ask, easy to hard

  1. When do you write async def and when def in FastAPI?
  2. What does FastAPI do differently with each?
  3. A partner API takes 20 seconds. Even endpoints that do not call it are slow. Why?
  4. Every few minutes all requests hang, even /health, after adding a PDF summary button. What do you do?
  5. How do you prevent it?

Practise

Practise with these questions

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

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

Start your free interview