Skip to content

fix(router): unify HTTP client singletons to prevent socket exhaustion#53

Merged
sheepdestroyer merged 3 commits into
masterfrom
fix/unify-http-clients-final
Jun 24, 2026
Merged

fix(router): unify HTTP client singletons to prevent socket exhaustion#53
sheepdestroyer merged 3 commits into
masterfrom
fix/unify-http-clients-final

Conversation

@sheepdestroyer

Copy link
Copy Markdown
Owner

Description

This pull request unifies all HTTP client instances in router/main.py to use a shared global httpx.AsyncClient singleton. Re-creating AsyncClient on every request/endpoint call can lead to socket exhaustion and adds unnecessary TCP handshake overhead.

Key Changes

  1. Shared Client Singleton: Introduced get_http_client() which lazily instantiates a shared global AsyncClient with a high timeout default.
  2. Rebase & Conflict Resolution: Rebased on top of master (incorporating dynamic URL environment variables from PR Extract hardcoded microservice endpoint bindings #47). Integrated get_http_client() inside:
    • get_llamacpp_metrics()
    • proxy_models()
    • lifespan() wait-readiness loop
  3. Indentation Fix: Corrected a minor IndentationError in the proxy_memory response block.
  4. FastAPI Lifespan Cleanup: Ensured the global client is properly closed (await _http_client.aclose()) when the application shuts down.

Verification & Testing

  • Validated python compilation: python -m py_compile router/main.py
  • Ran unit tests: pytest test_antigravity.py test_circuit_breaker.py (9/9 passed)

Supersedes #50.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @sheepdestroyer, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@coderabbitai

coderabbitai Bot commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Warning

Review limit reached

@sheepdestroyer, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 26 minutes and 48 seconds. Learn how PR review limits work.

Your organization has used up its prepaid credits, and credit purchases are no longer available. Enable the review add-on in the billing tab to keep reviews running — you're only billed for reviews past your plan's rate limits ($0.25/file).

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based credits.

🚦 How do rate limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: b91019f2-386d-4435-badf-5350706ddce3

📥 Commits

Reviewing files that changed from the base of the PR and between 0e1c0b2 and e2badb8.

📒 Files selected for processing (3)
  • router/free_models_roster.json
  • router/main.py
  • test_models_proxy.py
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/unify-http-clients-final

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request refactors router/main.py to use a shared HTTP client via get_http_client() instead of creating inline httpx.AsyncClient instances, while preserving the respective request timeouts. Feedback on these changes highlights two main issues: first, the shared global client's default connection limit of 100 may be easily exhausted under moderate load, so configuring custom limits is recommended; second, the proxy_models endpoint is vulnerable to a KeyError if the upstream LiteLLM service returns an error response without a 'data' key, which should be resolved by safely checking the response status and structure before modifying the payload.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread router/main.py
litellm_master_key = os.getenv("LITELLM_MASTER_KEY", "")
max_wait = 180
logger.info(f"⏳ Waiting for LiteLLM on {LITELLM_URL} (max {max_wait}s)...")
client = get_http_client()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The shared global httpx.AsyncClient is initialized with default limits (max_connections=100). Since this client is now shared across all endpoints and background tasks (including long-lived streaming proxy requests), a limit of 100 concurrent connections can easily be exhausted under moderate load, leading to httpx.PoolTimeout errors.

Consider configuring the global client with custom limits to support higher concurrency, for example:

_http_client = httpx.AsyncClient(
    timeout=3600.0,
    limits=httpx.Limits(max_connections=1000, max_keepalive_connections=500)
)

Comment thread router/main.py Outdated
@sheepdestroyer
sheepdestroyer force-pushed the fix/unify-http-clients-final branch 2 times, most recently from 14aa555 to fff00c0 Compare June 24, 2026 19:26
google-labs-jules Bot and others added 3 commits June 24, 2026 21:27
Replaced all localized `httpx.AsyncClient` context managers in `router/main.py`
with the shared global client from `get_http_client()`. Specific timeouts
are now passed directly to request methods. This change improves connection
pooling and reduces the risk of socket leaks (TIME_WAIT accumulation)
under heavy concurrency.

Functions updated:
- sync_adaptive_router_roster
- _register_ollama_models_in_db
- lifespan
- check_http_endpoint
- classify_request
- get_llamacpp_metrics
- get_best_free_model
- proxy_memory
- proxy_models

Co-authored-by: sheepdestroyer <1377479+sheepdestroyer@users.noreply.github.com>
Co-authored-by: gemini-code-assist[bot] <176961590+gemini-code-assist[bot]@users.noreply.github.com>
@sheepdestroyer
sheepdestroyer force-pushed the fix/unify-http-clients-final branch from fff00c0 to e2badb8 Compare June 24, 2026 19:27
@sheepdestroyer
sheepdestroyer merged commit b580cc3 into master Jun 24, 2026
6 checks passed
@sheepdestroyer
sheepdestroyer deleted the fix/unify-http-clients-final branch June 24, 2026 19:28
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.

1 participant