FastAPI · Trade-off
async def or plain def in FastAPI
Practise this out loud
Say your answer out loud to an AI interviewer that follows up, and get a score for it.
Practise by voiceThe 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
- Where does a
defendpoint run, and how many can run at once? - What happens if an
async defendpoint callsrequests.get()ortime.sleep()? - Your
get_dbdependency is a plaindef. Does that matter for anasync defendpoint? - How do you call a blocking library from an
async defendpoint? - Does any of this help with CPU-heavy work?
The answer
What a strong answer covers
async defendpoints run on the event loop and must onlyawaitnon-blocking calls (httpx.AsyncClient, async database drivers). One blocking call freezes every request in that worker process.- Plain
defendpoints anddefdependencies 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 defwhen everything inside is async;defwhen you call blocking libraries (a classic SQLAlchemy session,requests, many vendor SDKs). - Inside
async def, wrap blocking calls withawait run_in_threadpool(fn, ...)(Starlette) oranyio.to_thread.run_sync. - CPU work (PDF parsing, image resizing, big pandas jobs) blocks the loop in
async defand 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
/healthis slow; an event-loop lag metric jumps;py-spy dumpshows 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 voicePractise 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.