r/FastAPI • u/Diablo_1804 • Feb 19 '22
Question Limit Fastapi to process only 1 request at a time and after its completion process the next request
I'm trying to limit Fastapi to process 1 request at a time. And while that request is being executed, other requests gets response of 503(Server busy).
If anyone can help me with this....
5
3
u/whattodo-whattodo Feb 19 '22
It is a better practice to add a task queue like celery to deal with bottlenecks
That said if you really want to do this you should use Middleware. You will be able to define operations that happen before and after all endpoints. Adding basic variables to lock & unlock usage should be easy enough
2
3
u/nohaveuname Feb 19 '22
If this is like a stateful process application, you should consider putting every incoming request into a queue and give responses based on that
3
u/manfre Feb 19 '22 edited Jun 19 '23
No longer wish this content to be here due to the site changes
2
u/gingerdanger123 Feb 19 '22
Maybe a global variable processing_request.
Then middleware for all requests that checks if processing_request is True, if True respond with 503, otherwise flag as True.
Then I guess the difficult part is to make sure you absolutely always make sure to set processing_request to False when a request is finished.
Not so much of a problem when everything goes well, but need to do it with unexpected errors as well, so you need to make sure to catch all errors and set processing_request to 0, and also maybe set a smart timeout that sets it to 0 anyway if certain conditions occur including enough time passed since request started.
Never tried limiting request to 1 at a time though so just spitballing.
1
u/sasmariozeld Feb 20 '22
use gunicorn have multiple workers and have a row in db which just keeps track if a worker is working.. if one of them are the other can return the 503 ... but why would you wanna do this?
29
u/mohammedgqudah Feb 19 '22
That's weird, there is no reason to use an ASGI framework then 🤔.
Anyway, I would try using a wsgi framework like flask, deploy it using gunicorn and change the configuration to 1 worker 1 thread and the backlog=1 .
But this sounds like a xy problem, can you tell us why do you want to do this?