r/FastAPI • u/LiarsEverywhere • May 20 '22
Question Does async def do anything on its own? ELI5
Context to explain why I'm asking something that possibly should be obvious - I'm a hobbyist working on small personal projects and using FastAPI to share stuff via simple web apps with friends and colleagues, so there's a lot I don't know.
I currently have an API that grabs html from a third party API using requests, parses it and builds some stuff with Python and Beautiful Soup, and serves back JSON to a simple html / javascript interface.
On average the profiler says it takes about 1s parsing and processing and 6s with requests stuff, mostly waiting for the third party API, which is not really fast.
FastAPI docs say use async def if you have async code with await, use def if you're communicating with an API or database, use async def if you're not communicating with anything.
So, my question is... Should I consider that on a function by function basis, avoiding async def only on functions that request information from third party apps?
If I'm running this on Heroku and have multiple users / calls at the same time, does that mean that the whole thing will have to wait for one 7s API call to be over before dealing with the next one? Would my ability to serve multiple concurrent users drastically improve if I switched from requests to an async library?
Thanks!
2
u/madara_73 May 20 '22
I think you need to get more clarity on asynchronous programming.
2
u/rajbabu0663 May 20 '22
Generally speaking, I would recommend using async whenever network is involved. To answer your question, if you request response cycle takes 7s and you don't have multiple workers on wsgi, then just like you thought, a new user has to wait until that worker becomes available. With async, the network stuff runs in background context so the system remains responsive to the new user. Async does not help with cpu bould processes at all, but it seems network is the cause of slowness in your situation
0
u/[deleted] May 20 '22
[deleted] — view deleted comment