Skip to content
Advertisement

Architecture Flask vs FastAPI

I have been tinkering around Flask and FastAPI to see how it acts as a server.
One of the main things that I would like to know is how Flask and FastAPI deal with multiple requests from multiple clients.
Especially when the code has efficiency issues (long database query time).

So, I tried making a simple code to understand this problem.
The code is simple, when the client access the route, the application sleeps for 10 seconds before it returns results.
It looks something like this:

FastAPI

JavaScript

Flask

JavaScript

Once the applications are up, I tried accessing them at the same time through 2 different chrome clients. The below are the results:

FastAPI

enter image description here

Flask

enter image description here

As you can see, for FastAPI, the code first waits 10 seconds before processing the next request. Whereas for Flask, the code processes the next request while the 10-second sleep is still happening.

Despite doing a bit of googling, there is not really a straight answer on this topic.
If anyone has any comments that can shed some light on this, please drop them in the comments.

Your opinions are all appreciated. Thank you all very much for your time.

EDIT An update on this, I am exploring a bit more and found this concept of Process manager. For example, we can run uvicorn using a process manager (gunicorn). By adding more workers, I am able to achieve something like Flask. Still testing the limits of this, however. https://www.uvicorn.org/deployment/

Thanks to everyone who left comments! Appreciate it.

Advertisement

Answer

This seemed a little interesting, so i ran a little tests with ApacheBench:

Flask

JavaScript

FastAPI

JavaScript

I ran 2 tests for FastAPI, there was a huge difference:

  1. gunicorn -w 4 -k uvicorn.workers.UvicornWorker fast_api:app
  2. uvicorn fast_api:app --reload

So here is the benchmarking results for 5000 requests with a concurrency of 500:

FastAPI with Uvicorn Workers

JavaScript

FastAPI – Pure Uvicorn

JavaScript

For Flask:

JavaScript

Total results

Flask: Time taken for tests: 27.827 seconds

FastAPI – Uvicorn: Time taken for tests: 1.562 seconds

FastAPI – Uvicorn Workers: Time taken for tests: 0.577 seconds


With Uvicorn Workers FastAPI is nearly 48x faster than Flask, which is very understandable. ASGI vs WSGI, so i ran with 1 concurreny:

FastAPI – UvicornWorkers: Time taken for tests: 1.615 seconds

FastAPI – Pure Uvicorn: Time taken for tests: 2.681 seconds

Flask: Time taken for tests: 5.541 seconds

I ran more tests to test out Flask with a production server.

5000 Request 1000 Concurrency

Flask with Waitress

JavaScript

Gunicorn with Uvicorn Workers

JavaScript

Pure Uvicorn, but this time 4 workers uvicorn fastapi:app --workers 4

JavaScript
Advertisement