Skip to content

Instantly share code, notes, and snippets.

@yyming009
Created October 16, 2026 07:28
Show Gist options
  • Select an option

  • Save yyming009/24966e44a121923139f5ead668e4a872 to your computer and use it in GitHub Desktop.

Select an option

Save yyming009/24966e44a121923139f5ead668e4a872 to your computer and use it in GitHub Desktop.
Minimal and standalone reproduction: an asyncio client keeping N requests in flight against one host
"""Minimal, standalone reproduction: an asyncio client keeping N requests in flight against one host.
The server holds each request for HOLD seconds (like a model server decoding), so the client keeps N pooled
connections. We measure the client's event-loop lag (how late a 10 ms ticker wakes up) and the client-side overhead
per request (wall time minus HOLD) for httpx.AsyncClient (one client, max_connections=N, as many RL rollout loops do)
and for one aiohttp.ClientSession.
"""
import argparse, asyncio, statistics, time
import aiohttp, httpx
from aiohttp import web
HOLD = 2.0
async def handler(request):
await request.read()
await asyncio.sleep(HOLD)
return web.json_response({"text": "x" * 2048, "meta_info": {"completion_tokens": 512}})
async def lag_probe(stop, out, period=0.01):
while not stop.is_set():
t = time.perf_counter(); await asyncio.sleep(period); out.append(time.perf_counter() - t - period)
async def run(kind, n, rounds, port):
url = f"http://127.0.0.1:{port}/generate"
payload = {"input_ids": list(range(1024)), "sampling_params": {"max_new_tokens": 512}}
if kind == "httpx":
client = httpx.AsyncClient(limits=httpx.Limits(max_connections=n), timeout=httpx.Timeout(None))
async def one():
r = await client.post(url, json=payload); r.raise_for_status(); r.json()
else:
client = aiohttp.ClientSession(connector=aiohttp.TCPConnector(limit=0), timeout=aiohttp.ClientTimeout(total=None))
async def one():
async with client.post(url, json=payload) as r:
r.raise_for_status(); await r.json()
lags, over, stop = [], [], asyncio.Event()
probe = asyncio.create_task(lag_probe(stop, lags))
async def worker():
for _ in range(rounds):
t = time.perf_counter(); await one(); over.append(time.perf_counter() - t - HOLD)
t0 = time.perf_counter(); await asyncio.gather(*(worker() for _ in range(n))); wall = time.perf_counter() - t0
stop.set(); await probe
await (client.aclose() if kind == "httpx" else client.close())
q = lambda xs, p: sorted(xs)[min(len(xs) - 1, int(p * len(xs)))]
return dict(kind=kind, n=n, requests=len(over), wall_s=round(wall, 1),
overhead_mean_s=round(statistics.mean(over), 3), overhead_p99_s=round(q(over, 0.99), 3),
loop_lag_p99_s=round(q(lags, 0.99), 3), loop_lag_max_s=round(max(lags), 3))
async def main():
ap = argparse.ArgumentParser(); ap.add_argument("--n", type=int, nargs="+", default=[64, 256, 768, 1536])
ap.add_argument("--rounds", type=int, default=4); a = ap.parse_args()
app = web.Application(client_max_size=64 << 20); app.router.add_post("/generate", handler)
runner = web.AppRunner(app, access_log=None); await runner.setup()
site = web.TCPSite(runner, "127.0.0.1", 0, backlog=4096); await site.start()
port = site._server.sockets[0].getsockname()[1]
print(f"httpx {httpx.__version__}, httpcore {__import__('httpcore').__version__}, aiohttp {aiohttp.__version__}")
for n in a.n:
for kind in ("httpx", "aiohttp"):
print(await run(kind, n, a.rounds, port), flush=True)
await runner.cleanup()
if __name__ == "__main__":
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment