Requests distribution #2467
-
Hey 👋 Recently we noticed that request distribution between different processes on a single machine looks like this: We use Here is an example of the `supervisor` config:
and here is a simple app for testingimport asyncio
import os
from fastapi import FastAPI
app = FastAPI()
# Global counter and lock
request_count = 0
request_count_lock = asyncio.Lock()
# Function to safely increment and print request count
async def increment_request_count():
global request_count
async with request_count_lock:
request_count += 1
@app.get("/")
async def read_root():
await increment_request_count()
return {"pid": os.getpid(), 'count': request_count} and a simple script to test itimport asyncio
import httpx
from httpx import Limits
async def call(client):
response = await client.get('http://127.0.0.1:8000')
print(response.text)
return response.json()
async def main():
results = {}
async with httpx.AsyncClient(limits=Limits(max_connections=10, max_keepalive_connections=10)) as client:
for result in (await asyncio.gather(*[call(client) for _ in range(1000)])):
results[result['pid']] = result['count']
print(results)
if __name__ == '__main__':
asyncio.run(main()) This setup provides poor requests distribution. I tried using uvicorn as a process manager, but the result is the same. Previously, there was a similar discussion, but about
Sorry for the long intro 😅 Here is my question: If it's not possible to do that using just Thank you!! |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 17 replies
-
Hi @SlavaSkvortsov , right... I don't know where the issue relies on. We do set the Line 512 in a507532 Any ideas @graingert @abersheeran ? My recommendation would be to rely on an external load balancer e.g. nginx. |
Beta Was this translation helpful? Give feedback.
-
Please make sure you use the new multi-process manager and increase the concurrency (the test script you gave establishes at most 10 connections, so the test is too accidental). |
Beta Was this translation helpful? Give feedback.
-
We have the same problem with gunicorn, our application structure is an asynchronous gunicorn-worker with processing of most requests in a synchronous thread (there is only one thread). Perhaps if you repeat this load profile, the balancing problem will be visible. |
Beta Was this translation helpful? Give feedback.
-
@SlavaSkvortsov does https://github.com/encode/uvicorn/pull/2472/files fix it for you? |
Beta Was this translation helpful? Give feedback.
@SlavaSkvortsov does https://github.com/encode/uvicorn/pull/2472/files fix it for you?