r/FastAPI • u/Iklowto • Dec 07 '21
Question Why is my FastAPI application able to make several hundred HTTP requests/second when the requests are synchronous?
I created a small project for benchmarking sync/async operations in FastAPI APIs.
It seems that calls that should be blocking (e.g. open() or requests.get()) are running perfectly in parallel.
This seems great because it means I don't really need async and async libraries when I thought I did. However, I'm not familiar enough with FastAPI to make that judgement yet. Can someone explain what's going on here? And if using async even makes sense if synchronous calls run in parallel?
I put the code for reproducing my experiments on a public repository here. Repo contains a quick start guide for running the stress tests.
Experiments
General settings for all experiments:
Simple FastAPI application with two routes
/sync/...for synchronous operations/async/...for asynchronous operations
API is run under Gunicorn with a single worker
Worker class set to
uvicorn.workers.UvicornWorker
API is stress tested using Locust
Only one endpoint per test
500 users @ 50 users/sec spawn rate
Each user waits 1 second between requests
Tests run for 1 minute
Loading JSON from disk
Users hit an endpoint that loads a small JSON file from disk and returns it. The /sync/json endpoint uses the standard open() method to read the file (should be blocking). The /async/json endpoint uses aiofiles.open() instead.
/sync/json statistics:
Num. requests: 15550
Avg. response time: 745 ms
Avg. requests/second: 259.16
/async/json statistics:
Num. requests: 15304
Avg. response time: 778 ms
Avg. requests/second: 255.06
With an avg. response time of 745 ms, it's simply not possible for open() to be blocking with 15550 requests successfully handled in 1 minute.
Making HTTP requests
Users hit an endpoint that makes a GET request to https://jsonplaceholder.typicode.com/todos/1 and returns the result. The /sync/http endpoint uses the httpx.Client() synchronous client, which should be blocking. Was also tested with requests.get() with similar results. The /async/http endpoint uses the httpx.AsyncClient() asynchronous client.
/sync/http statistics:
Num. requests: 6422
Avg. response time: 917 ms
Avg. requests/second: 107.03
/async/http statistics:
Num. requests: 3946
Avg. response time: 5951 ms (I did not switch up sync/async here)
Avg. requests/second: 65.76
Again, with the average request taking 917 ms to complete, httpx.Client.get() can not be blocking when it successfully made 6422 GET requests in 1 minute.
Also interestingly, the synchronous HTTP client seems to perform much, much better than the asynchronous one. No requests failed in either case, and the tests were run several times to ensure that one wasn't being rate-limited while the other was.
Hope someone can help me clear this up, thanks in advance!