r/learnpython • u/Iklowto • Dec 07 '21
Why is my FastAPI application able to make several hundred HTTP requests/second when the requests are synchronous?
/r/FastAPI/comments/rbazot/why_is_my_fastapi_application_able_to_make/
4
Upvotes
1
u/deikan Dec 08 '21
The results you got from this "test" is not very reliable. I looked at your code here and you're sending a basic request with no user agent headers and not using a proxy. It's possible the site you're hitting is detecting your script as a malicious agent and rate limiting you. If you want better results, get a list of good user agents and working proxies and rotate them with every request.
Another thing is you are not taking advantage of is connecting pooling, you should be setting the client context at the start of your script and use the same client to send every subsequent request. Right now you are incurring a lot of overhead by creating a new client for every request.
This one is a little harder to answer as I don't have a great deal of experience with FastApi. But generally speaking if a web framework supports both sync and async handlers, it is very likely there are underlying dependencies that are natively async. Just think about this logically, async can always be "downgraded" to support sync operations because by default sync operations are blocking, whereas sync dependencies cannot just magically support async operations. So there is probably a lot behind the scene that is speeding up your requests.
A better test would be to put a simple blocking time.sleep(1) within your sync and non-blocking asyncio.sleep(1) within your async handler. You'll notice the same average response time but way less requests per second.