Anthropic shim opens a new TLS connection for every request (~541 ms per turn)
Release blocker. ~541 ms is added to every request an agent makes through wally, before a single byte of the request is sent.
Problem
The Anthropic→OpenAI shim builds a fresh httplib::Client for every request to the hosted endpoint: inside the streaming sink in src/anthropic/messages.cpp (HandleStreaming, httplib::Client client(*origin) ~L183) and again in HandleNonStreaming (~L119). Each one opens a new TCP connection and completes a new TLS handshake, streams one response, and is destroyed.
Against the regional load balancer that handshake was measured at ~541 ms (InferenceInfra .claude/rules/terraform-safety.md, 2026-09-06; InferenceInfra #418 measured ~556 ms per new connection from Delhi, and nothing on reused connections). Claude Code makes several requests per user turn once ANTHROPIC_BASE_URL points at the shim — the main completion plus the small side calls — and every one pays it. Claude Code → shim is loopback and unaffected; the shim → inference.runanywhere.ai leg is where the cost lands.
Why it blocks release
It is the largest piece of time-to-first-token a customer feels that has nothing to do with the GPU, on every turn. It also makes the regional-TLS question (InferenceInfra #299) look worse than it is: once the connection is reused, that handshake is paid once per session instead of once per request.
Fix
- Keep long-lived
httplib::Clients on the shim'sRuntime,set_keep_alive(true). Anhttplib::Clientserialises requests on its one socket, so use a small pool — one per concurrent stream — and reuse across turns. - Reconnect lazily: if a request fails on a stale socket (the ALB keeps idle client connections ~10 minutes), retry once on a fresh one. Never retry a request that has started streaming.
- Enable TLS session resumption on the client so a reconnect is one round-trip.
- Same pattern in
src/harness/codex.cpp/opencode.cpponly if they own an HTTP client of their own; if they hand the tool a base URL and the tool's client talks directly, they are unaffected.
Done when
A packet capture of a second request in the same session shows no TLS handshake, and the per-turn TTFT in a real agent session drops by roughly the handshake time.
Related: the cancel-on-close issue (same file), InferenceInfra #299.
Plan — wally #80: reuse the shim's upstream connection
Done when (from the issue): a second request in the same wally session shows no TLS handshake, and per-turn TTFT drops by roughly the handshake time.
What the code does today
src/anthropic/messages.cpp builds a fresh httplib::Client per request — in the streaming sink (HandleStreaming, ~L183) and in HandleNonStreaming (~L119) — so every request pays TCP connect + TLS handshake (~541 ms measured against the regional ALB). The shim's httplib::Server runs a thread pool, so requests are concurrent; an httplib::Client serialises requests on its single socket (request_mutex_), so one shared client would make Claude Code's parallel side calls wait behind a long stream. Hence a pool, not a singleton. src/ide/openai_proxy.cpp has the same pattern at three sites.
Design
- New
src/net/upstream_pool.{h,cpp}—UpstreamPool(origin, api_key, read_timeout)holding idlehttplib::Clients (eachset_keep_alive(true), bearer set, 600 s read timeout as today, plus a 10 s connect timeout).Lease acquire()pops an idle client or builds one; the RAIILeasereturns it on destruction only if the request completed cleanly; a lease markeddiscard()(stream aborted, transport error) drops the socket. Idle cap 4 (Claude Code's realistic parallelism); concurrent leases are unbounded. Mutex-protected; no global state. - Retry once on a stale reused socket. Pure decision
RetryOnFreshConnection(error, status, receiver_called, was_reused): retry iff the client was reused, no HTTP status arrived, the receiver was never called (nothing reached the editor), and the error is connection-class (Connection,Read,Write,ConnectionClosed,SSLConnection). Never retry once bytes have streamed; never retry a fresh client (a real outage must surface). httplib already drops a socket that received FIN (is_socket_alive) before reuse; this covers the half-open case the ALB's ~10-minute idle timeout can leave. - Shim wiring.
Runtimeownsstd::shared_ptr<UpstreamPool>; the streaming lambda captures it (same reason the current code capturesshared_ptrs: the sink outlives the handler). Verbose mode logsupstream: reused|fresh. Behaviour otherwise unchanged: same translation, same error mapping, sameRetry-Afterforwarding. - Out of scope, stated: TLS session resumption — cpp-httplib 0.46.1 does not implement it, so a reconnect is a full handshake regardless; keep-alive is the fix. HTTP/2 — not in httplib.
Steps (each with the test that proves it; every new test shown RED then GREEN, both runs quoted in the commit)
- Test harness first.
tests/test_wally_anthropic.cpp(new executable, registered intests/CMakeLists.txtlike the others): a fake upstreamhttplib::Serveron loopback serving/v1/chat/completions(JSON and SSE) that recordsrequest.remote_portper request. Test A: start the shim viaanthropic::Startagainst it, send two sequential/v1/messages, assert the upstream saw the same remote port both times (same TCP connection). RED today — ports differ. Test B: two concurrent streaming requests → two distinct ports, both complete (guards against a serialising singleton). UpstreamPool+ its unit tests (lease/return/discard/idle-cap/thread-safety, no sockets touched beyond loopback). Hermetic.- Wire the shim (streaming + non-streaming) to the pool. Test A → GREEN; existing 10 tests stay green.
- Retry-once. Unit-test the decision table. Integration: fake upstream with
set_keep_alive_max_count(1)(server closes after every response) → second request still succeeds; aborted-stream test (upstream streams slowly, editor side disconnects) → that connection is discarded and the next request succeeds on a new port. - Docs + hygiene. One paragraph in
docs/EDITORS.md(the translator keeps a connection per stream open across turns; reconnects once on a stale one);AGENTS.mduntouched unless a rule needs it;scripts/ci/check-agents-sync.sh, clang-format on touched files, fullctest. - System check (needs a signed-in session):
wally claude-code -m glm-5.3-flashwith the shim verbose against dev — second request logsreused; optionally a packet capture showing one handshake. Aman runs this, or I do withWALLY_CONSOLE_URLpointed at dev. - Follow-up, separate PR unless you want it here: wire the same pool into
src/ide/openai_proxy.cpp(3 sites).
Risks
- Stale reused socket → covered by httplib's liveness check + the retry-once rule; a retry never repeats a request that has produced output.
- Memory/sockets → idle cap 4; discarded leases close.
- Windows → httplib abstracts Winsock; the pool uses only its public API.
- Server-side
Connection: close(e.g. LiteLLM restarts) → httplib honours it and reconnects; test 4 covers the mechanism.
Validation before the PR
cmake --build build && ctest --test-dir build --output-on-failure (all green, new suite included) · bash scripts/ci/check-agents-sync.sh · clang-format check · break-test quotes for tests A, B, retry, abort in the commits · draft PR against main, no attribution lines.
Plan review — amendments before implementation
Reviewed the plan above against the shim and cpp-httplib 0.46.1. Core design stands (pooled keep-alive clients, RAII lease returned only on clean completion, retry only when nothing reached the editor). Five amendments:
- Step 6 is mandatory and quantitative, not optional. The hermetic tests prove
httplibreuses a connection to our fake server; they cannot prove the real edge allows it (an ALB/Cloud RunConnection: closewould leave every test green and the win at zero). Before the PR leaves draft: shim viawally claude-code --serveagainst dev, two requests withcurl -w '%{time_starttransfer}', both numbers and a handshake count in the PR body. That is the issue's own done-when. - Retry-once needs an integration test on the real path.
set_keep_alive_max_count(1)makes the server send FIN, which httplib'sis_socket_alivecatches before sending, so the retry code never runs. Add a raw-socket fake upstream that serves request 1, then on request 2 reads the request and closes without responding: reused client → connection-class error, no status, receiver never called → retry on a fresh client → success. - State the duplicate-generation risk. On a reused socket, "no bytes back" does not prove the server never processed the request. This is the curl/browser heuristic for stale keep-alives and is kept, capped at one retry, and logged (
upstream: retried on fresh connection) so a duplicate is traceable. Recorded in the PR body as an accepted risk. - Test B needs a latch. The fake upstream holds both concurrent streams open until both have arrived; otherwise legitimate reuse of a fast stream's connection makes the test flaky.
- The 10 s connect timeout is a behaviour change (today: httplib default 300 s). Kept, but named in the PR body as outside #80's strict scope.
Also recorded: connection reuse lapses across long tool runs (ALB idle timeout ~10 min) — one full handshake per lull, by design; goes in docs/EDITORS.md. Step 7 (JetBrains proxy, 3 sites) stays a separate PR.
Monday MVP triage (2026-09-12): moved to important / P2, still open.
Connection reuse improves latency; user explicitly excluded performance-only work from Monday gates. Retain for follow-up and PR82 coordination.
This is a scope decision, not a fix or passing deployment claim. The final production acceptance gate is tracked in RunanywhereAI/InferenceInfra#280; reapply release-blocker if its stated workaround/disabled-feature assumption is not true of the release artifact.
Fixed on main (Rust port). The shim keeps its upstream connection open and reuses it across turns (src/net/upstream_pool.rs, src/net/http1.rs), opens a separate one for concurrent streams, and retries once on a fresh connection only when a reused one went stale. Checked today: sequential_requests_reuse_the_upstream_connection, concurrent_requests_use_separate_connections and stale_reused_connection_is_retried_once_on_a_fresh_one pass on main, along with the rest of test_wally_anthropic (24/24).