r/learnpython • • 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

14 comments sorted by

1

u/deikan Dec 08 '21

Making HTTP requests

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.

Loading JSON from disk

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.

1

u/Iklowto Dec 08 '21

I appreciate the concern for the tests being rate-limited. The HTTP request tests were made over several disjointed runs and averaged with low standard deviation - rate limiting is not the issue. However, it absolutely could be just a shoddy implementation of `httpx.AsyncClient()` - I'll need to test with more async HTTP libraries before drawing a conclusion here.

I don't really like tests like this that "simulate" blocking IO with time.sleep(). While it's likely that it is affecting the system in the same way that a large file read would, there's no guarantee (for me, at least) that it would. I'd prefer to stay safe by testing the same operations I would be making in a real project.

it is very likely there are underlying dependencies that are natively async

I completely agree - but when that's the case, I see little reason to ever use `async/await` in my path operations. There are of course edge cases where I would need to make 5 HTTP request simultaneously, and `await asyncio.gather()` would be helpful there. However, in practically all of the current documentation, the advice is to use `async/await` for IO-bound work. Given this experiment, calls that should be blocking IO aren't blocking anything, and so async/await becomes redundant.

1

u/deikan Dec 08 '21

While it's likely that it is affecting the system in the same way that a large file read would, there's no guarantee (for me, at least) that it would

Can you explain why you think this way? If you put a blocking time.sleep(1) and then use an async client to send 1000 requests to your webserver, you will start timing out on requests. Whereas with asyncio.sleep() on an async webserver will probably not cause any timeouts.

I see little reason to ever use `async/await` in my path operations.

Yeah it's because there is no I/O bound work actually done by your handlers. Reading from json file and deserializing is CPU bound work -- and very light CPU work. Imagine a scenario where your handler needs to send an HTTP request to another service and get a response. This would be an i/o bound operation that makes more sense. If you think a time.sleep() is not a good simulation then you could try sending a request to a website in your handler or you could hook up a DB and send a query to your DB (make sure it's prepopulated with a lot of rows and no secondary index). These are the use cases where async handlers would make a lot of sense.

1

u/Iklowto Dec 08 '21

I might be confused, but reading a JSON file from disk is most definitely IO-bound work, by definition. My experiments also include HTTP request to external services as you suggest. In fact, in the case of HTTP requests, asynchronous handlers perform significantly worse than their synchronous counterparts (rate limiting has been ruled out as the causing factor). Do you see any reason why any of these two use cases don’t demonstrate IO-bound work?

1

u/deikan Dec 08 '21 edited Dec 08 '21

reading a JSON file from disk is most definitely IO-bound work

I believe this is our fundamental disconnect. When the docs are referring to I/O bound work it means sending a query request to a DB or an HTTP request to another service within your system. So no, generally anything that relies on your webserver to do work is not relevant to our I/O context. Anything where you service just "forwards" the request to be worked on somewhere else is relevant though.

My experiments also include HTTP request to external services as you suggest

I am talking about testing async handlers. So the flow is, your client sends a requestA to your webserver. The handler receiving the request now needs to send another requestB (with another client) to a random website and get back a response and returns that response to your client. The middle step where your handler is sending a requestB will be blocking as it has to wait for a response before responding to your first requestA.

1

u/Iklowto Dec 08 '21

The middle step where your handler is sending a requestB will be blocking

This is categorically disproven in the experiments. Please see the code in the repo for details.

The test setup in the HTTP test is as follows:

  1. 500 clients send requestA to my service with 1 second delay between requests for each client

  2. Upon receiving a requestA, my client makes a requestB to an external API.

  3. Once a response is received from requestB, it is returned to the original calling client

Even when making requestB synchronously (e.g. using requests.get() with no await), my service was able to handle 15k requests from the 500 clients within one minute, with an average response time of 800 ms. With those stats, it is literally impossible for the requests.get() call to be blocking the other clients.

I urge you to run this test yourself to verify. In the repo, the script is stress_sync_http.sh. The clients will hit the /sync/http route which you can verify is not awaiting the outgoing HTTP request from the service since the function is synchronous.

1

u/deikan Dec 08 '21 edited Dec 08 '21

Ok i took a look and I see you are using uvicorn which is an async worker. This is the reason why you are able to handle so many requests. FastAPI runs on ASGI so it cannot use traditional WSGI sync workers.

I forked your repo and added a simple flask app and served it on a single sync workers. When i call stress_sync_http.sh, it is only serving ~8 requests/second now. If you up the workers to 2 instead of 1, it will serve ~17 requests per second which is almost exactly double -- demonstrating each worker is being blocked.

I also made some modifications to your original handlers. I changed your handlers to send a requestB and I noticed an improvement from ~120 requests/second with sync handler to ~180 requests/second with async handler. This is on your FastAPI webapp both being served with 1 uvicorn worker.