Skip to content

Fix bm_fastapi failing when an HTTP proxy is configured - #505

Open
sendaoYan wants to merge 1 commit into
python:mainfrom
sendaoYan:fix-fastapi-proxy
Open

sendaoYan wants to merge 1 commit into
python:mainfrom
sendaoYan:fix-fastapi-proxy

Conversation

@sendaoYan

Copy link
Copy Markdown

Fixes #504

Problem

The fastapi benchmark (bm_fastapi) fails when the environment has an HTTP
proxy configured — e.g. HTTP_PROXY/http_proxy set, which is common in CI or
corporate environments — and 127.0.0.1 is not listed in NO_PROXY.

The benchmark starts a uvicorn server on 127.0.0.1 and then talks to it with
httpx.AsyncClient(). Because httpx reads proxy configuration from the
environment by default, the request to http://127.0.0.1:<port>/items/0 is
routed through the proxy. The proxy cannot reach the benchmark machine's
loopback address, so it returns 503 Service Unavailable and the benchmark
dies:

httpx.HTTPStatusError: Server error '503 Service Unavailable' for url 'http://127.0.0.1:40027/items/0'
...
RuntimeError: Benchmark died
ERROR: Benchmark fastapi failed: Benchmark died

Fix

Create the client with trust_env=False so it never reads proxy (or .netrc)
settings from the environment:

async with httpx.AsyncClient(trust_env=False) as client:

This is correct for this benchmark because it only ever connects to its own
loopback server, so it must never be routed through a proxy. In environments
with no proxy configured, trust_env=False behaves identically to the default,
so benchmark results are unaffected for the common case.

Only bm_fastapi is affected: the other networking benchmarks
(bm_tornado_http, bm_asyncio_tcp, bm_asyncio_websockets, bm_async_tree)
use clients that do not read proxy environment variables.

Testing

Reproduced by running the benchmark with proxy environment variables inherited
and 127.0.0.1 absent from NO_PROXY:

$ python -m pyperformance run bm_fastapi --inherit-environ http_proxy,https_proxy,no_proxy
  • Before the change: Benchmark fastapi failed: Benchmark died with the 503 above.
  • After the change: the benchmark completes and reports a result.

httpx.AsyncClient() reads HTTP_PROXY/HTTPS_PROXY/NO_PROXY from the
environment by default. When a proxy is set, the benchmark routes
requests to its local 127.0.0.1 server through that proxy, which cannot
reach the loopback server and returns 503 Service Unavailable, causing
the benchmark to fail ("Benchmark died").

Pass trust_env=False since the benchmark only ever talks to localhost.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bm_fastapi fails with "503 Service Unavailable" when a proxy is configured

1 participant