{"title":"CLIProxyAPI Session Affinity: What the Logs Prove and What They Don't","excerpt":"Session affinity is built into stock CLIProxyAPI v8.0.58 and is off by default. Checked against the source and a day of masked logs from a Claude Code, Codex and T3 Code setup: the binding key, why one credential can't prove stickiness, what fill-first does, and why affinity enables cache reuse but can't prove it.","canonicalUrl":"https://automationtester.in/blog/ai-in-testing/cliproxyapi-session-affinity-what-logs-prove","category":{"name":"AI in Testing","slug":"ai-in-testing"},"tags":["cliproxyapi","session-affinity","claude-code","codex","t3-code","prompt-caching","llm-proxy"],"author":{"name":"Shashank Rawlani","url":"https://shashank.rawlani.com","linkedin":"https://www.linkedin.com/in/shashankrawlani/"},"datePublished":"2026-11-10T05:30:00.000Z","dateModified":"2026-11-10T05:30:00.000Z","coverImage":{"url":"https://ik.imagekit.io/automationtester/automationtester-in/blog/covers/v3/cliproxyapi-session-affinity-what-logs-prove.webp","alt":"Rows of short pills run in from the left. The brightest green row, inside a dashed boundary, curves into one large ringed green node; a dashed orange curve leaves it and ends at a crossed-out ring, while a grey node sits unused."},"contentHtml":"<div class=\"callout callout-info\"><strong>Quick answer:</strong> Session affinity is part of stock CLIProxyAPI v8.0.58. It is off by default. Turn it on with <code>routing.session-affinity: true</code> and the proxy ties each conversation to one credential under the key <code>provider::sessionID::model</code>. If you only have one credential per provider, the proxy has nothing else to pick, so the logs show affinity running but can't show it keeping a session on one account. A request with no binding goes to <code>routing.strategy</code>, once per session and model, not once per request. <code>fill-first</code> never spreads load. And none of this proves a prompt-cache hit. Only <code>cache_read_input_tokens</code> in the response does.</div>\n\n<p>There is a popular setup guide for running <a href=\"https://code.claude.com/docs/en/overview\">Claude Code</a> and <a href=\"https://developers.openai.com/codex\">Codex</a> through a local <a href=\"https://github.com/router-for-me/CLIProxyAPI\">CLIProxyAPI</a>, with <a href=\"https://t3.codes\">T3 Code</a> as the front end. Three of its claims are worth checking before you copy it. It says stock CLIProxyAPI rotates credentials on every request. It says session affinity is a custom-fork feature that \"preserves Anthropic's 5-minute prompt cache\". And it treats a log full of affinity lines as proof that affinity works. On v8.0.58 the first claim is wrong, the second goes too far, and the third proves less than it seems to.</p>\n\n<p>CLIProxyAPI is an open-source local proxy that wraps Claude Code, Codex and other providers as one OpenAI-, Claude- and Codex-compatible API. T3 Code is an open-source desktop, web and mobile app that drives the agent CLIs already installed on your machine. Session affinity is the proxy setting that keeps one conversation on one account.</p>\n\n<p>This article separates what the source code and a day of real logs actually show from what they only hint at. Everything below was captured on 2026-11-07 on a single-user local install with one Claude account, one Codex account and no remote clients. Hostnames, account identifiers, keys and session IDs are removed or replaced with placeholders.</p>\n\n<h2 id=\"routing-block\">Which routing settings does CLIProxyAPI v8.0.58 actually use?</h2>\n\n<figure><img src=\"https://ik.imagekit.io/automationtester/automationtester-in/blog/figures/cliproxyapi-session-affinity-what-logs-prove/fig-01-version.png\" alt=\"Terminal output of cliproxyapi --help showing CLIProxyAPI Version 8.0.58, Commit Homebrew, built 2026-11-06T12:49:38Z\" width=\"2400\" height=\"395\" loading=\"lazy\" /><figcaption>The installed binary reports v8.0.58. Every source reference in this article is pinned to that tag.</figcaption></figure>\n\n<p>This install came from the <a href=\"https://formulae.brew.sh/formula/cliproxyapi\">Homebrew formula</a>. The <a href=\"https://help.router-for.me/introduction/quick-start\">CLIProxyAPI quick start</a> covers other ways to install it. The config file is <code>~/.cli-proxy-api/config.yaml</code>, using schema <code>config-version: 8</code>. These are the fields that matter here:</p>\n\n<pre class=\"language-yaml\"><code class=\"language-yaml\">routing:\n  strategy: \"fill-first\"\n  session-affinity: true\n  session-affinity-ttl: \"1h\"\n  session-affinity-subagents: true\n  session-affinity-rebind-on: \"quota\"\n  retry:\n    request-retry: 3\n    max-retry-interval: 30</code></pre>\n\n<p>The upstream <code>config.example.yaml</code> at tag <code>v8.0.58</code> documents every one of these. Its defaults differ from the block above in two places. <code>session-affinity</code> defaults to <code>false</code>, and <code>session-affinity-rebind-on</code> defaults to <code>\"any\"</code>. So when a guide says stock CLIProxyAPI \"distributes traffic naively\", it is describing the switch left off. The code can do better.</p>\n\n<p>That file lists exactly three strategies: <code>round-robin</code> (the default), <code>weighted-round-robin</code> and <code>fill-first</code>. This version has no expiration-aware strategy. If a guide or video shows one, it is using a fork.</p>\n\n<h2 id=\"binding-key\">What does session affinity bind a conversation to?</h2>\n\n<p>The selector is <code>SessionAffinitySelector.Pick</code> in <code>sdk/cliproxy/auth/selector.go</code>, and the core of it is short. It pulls out a session ID, builds <code>cacheKey := provider + \"::\" + primaryID + \"::\" + modelKey</code>, and looks that key up with <code>GetAndRefresh</code>. If the bound credential is still available, the selector returns it and renews the TTL. If it isn't, the fallback selector (your <code>routing.strategy</code>) picks one, and the proxy stores that pick as the new binding.</p>\n\n<p>Two things follow from that key. The model is part of it, so a conversation that switches models gets a second, separate binding. And the TTL is an idle timeout. Every hit resets it, so a conversation that keeps going never expires, while one that sits quiet for an hour does. Bindings live in memory, so restarting the proxy drops all of them.</p>\n\n<p>The session ID comes from <code>ExtractSessionID</code>, which checks a fixed list in order. These are the entries that matter for T3 Code:</p>\n\n<table>\n<thead><tr><th>Priority</th><th>Signal</th><th>Sent by</th></tr></thead>\n<tbody>\n<tr><td>1</td><td><code>X-Claude-Code-Session-Id</code> header</td><td>Claude Code</td></tr>\n<tr><td>2</td><td>Session inside <code>metadata.user_id</code></td><td>Claude Code</td></tr>\n<tr><td>3</td><td><code>Session-Id</code> / <code>Session_id</code> header</td><td>Codex and compatible clients</td></tr>\n<tr><td>8</td><td><code>prompt_cache_key</code>, with <code>conversation.id</code> as an alias</td><td>Responses API clients</td></tr>\n<tr><td>11–12</td><td>Derived context identity, then a hash of the first messages</td><td>Nobody. The proxy computes it.</td></tr>\n</tbody>\n</table>\n\n<p>The order matters in practice. The source calls an explicit ID \"absolute authority\", and the proxy only falls back to matching on the longest common prefix of the messages when there is no header, body field or execution-session identity at all. A client that sends no ID still gets affinity, but through content matching, which is the weaker signal.</p>\n\n<h2 id=\"log-evidence\">What do the session-affinity log lines show?</h2>\n\n<p>With default log settings the proxy writes one line for each selection decision. With the IDs masked, they look like this:</p>\n\n<pre class=\"language-text\"><code class=\"language-text\">[info] selector.go:1312 session-affinity: cache miss, new binding | session=claude:&lt;id&gt; auth=&lt;cred&gt; provider=mixed model=claude-sonnet-5-5\n[info] selector.go:1226 session-affinity: cache hit | session=claude:&lt;id&gt; auth=&lt;cred&gt; provider=mixed model=claude-sonnet-5-5\n[info] selector.go:1453 session-affinity: LCP cache miss, new binding | session=lcp:&lt;hash&gt; auth=&lt;cred&gt; provider=mixed model=gpt-6-sol</code></pre>\n\n<p>The capture window ran from 19:51 to 23:52 IST on 2026-11-07. In that window the log held 228 <code>cache hit</code> lines, 5 <code>cache miss, new binding</code> lines (all with an explicit <code>claude:</code> or <code>codex:</code> prefix) and 1 <code>LCP cache miss, new binding</code> line. The prefix is what tells you something. The proxy only writes a <code>claude:</code> or <code>codex:</code> prefix when it took the explicit-identity path, so every one of those prefixed lines means a real client session ID arrived, not a content hash. The single <code>lcp:</code> line came from earlier in the day. It was a test call made by hand to <code>gpt-6-sol</code> without a session header.</p>\n\n<figure><img src=\"https://ik.imagekit.io/automationtester/automationtester-in/blog/figures/cliproxyapi-session-affinity-what-logs-prove/fig-07-tally.png\" alt=\"Terminal output counting server.log lines: 228 session-affinity cache hits, 5 cache-miss new bindings and 1 LCP cache-miss new binding\" width=\"2400\" height=\"651\" loading=\"lazy\" /><figcaption>The counts at the end of the capture window. The proxy kept logging after this, so a later count of the same file is higher.</figcaption></figure>\n\n<p>This evidence has limits. The log truncates the session ID, so you can't tell whether two bindings belong to two T3 threads or to one thread that switched models. And <code>provider=mixed</code> only says the candidate pool covered more than one provider type. It doesn't say which credentials were eligible for a given model.</p>\n\n<p>Mask the session ID and the credential before you share a line like these. The same rule applies to any agent log, and <a href=\"/blog/ai-in-testing/mcp-observability-audit-without-secrets\">logging MCP tool calls without secrets</a> shows how to test that no token reaches a log sink.</p>\n\n<h2 id=\"one-credential\">Why can one credential never prove affinity works?</h2>\n\n<p>With exactly one Claude credential and one Codex credential, every request has exactly one eligible credential. A cache hit returns it. A cache miss falls back to <code>fill-first</code>, which returns <code>available[0]</code>, the same credential. You get the same result whether affinity works perfectly or is completely broken. So the 228 hits show that the lookup runs and the TTL refreshes. They don't show that sessions stick.</p>\n\n<div class=\"callout callout-warning\"><strong>Warning:</strong> While each provider has only one credential, a log full of <code>session-affinity: cache hit</code> lines doesn't prove a session is sticky, because any selector would return that one credential. It doesn't prove a provider cache hit either. Add a second credential and check that <code>auth=</code> stays the same within each session, then read <code>cache_read_input_tokens</code> in the response.</div>\n\n<p>Adding a second credential for the same provider changes that. You can then see three behaviours, and each leaves its own trace in the log:</p>\n\n<ul>\n<li>A new session's first request logs <code>cache miss, new binding</code>, and the strategy decides where it goes. Under <code>fill-first</code> it lands on the first credential every time, in ID order, until that credential is unavailable. Under <code>round-robin</code> it rotates, per model, on each cold pick.</li>\n<li>Later requests in that session log <code>cache hit</code> with the same <code>auth=</code> value, even if the strategy would now pick something else.</li>\n<li>When the bound credential hits a quota or auth error, the session rebinds. With <code>rebind-on: \"quota\"</code>, transient failures (408, 5xx, an empty stream) retry that one request on another credential and leave the binding alone, while 429 and 401/402/403 rebind it. With the default <code>\"any\"</code>, any failure blamed on the credential rebinds it.</li>\n</ul>\n\n<p>One more detail interacts with the example config. An existing binding beats credential priority. If a session is bound to a lower-priority credential and a higher-priority one comes back, the session stays put. Priority only decides cold bindings, requests without a session, and rebinding after a failure.</p>\n\n<h2 id=\"when-distribution-happens\">When does CLIProxyAPI pick a new credential?</h2>\n\n<p>\"Distribution\" means three different things depending on what the request carries, and the guide uses one word for all of them.</p>\n\n<table>\n<thead><tr><th>Situation</th><th>Who chooses the credential</th><th>How often</th></tr></thead>\n<tbody>\n<tr><td>Affinity on, session ID present, binding exists</td><td>The binding</td><td>Not at all until TTL, restart or failover</td></tr>\n<tr><td>Affinity on, session ID present, no binding</td><td><code>routing.strategy</code></td><td>Once per session and model</td></tr>\n<tr><td>Affinity on, no ID extractable</td><td><code>routing.strategy</code></td><td>Every request</td></tr>\n<tr><td>Affinity off</td><td><code>routing.strategy</code></td><td>Every request</td></tr>\n<tr><td>Subagent, <code>session-affinity-subagents: true</code></td><td>The parent's credential</td><td>Inherited, same model</td></tr>\n<tr><td>Subagent, <code>session-affinity-subagents: false</code></td><td>The strategy, over the whole pool</td><td>Every subagent session</td></tr>\n</tbody>\n</table>\n\n<p>Here is what that means for load. With affinity on and several credentials, <code>fill-first</code> works as a priority queue, not a load balancer. It piles new sessions onto the first credential and only moves on when that one is blocked. <code>round-robin</code> spreads new sessions out, but a long session still stays on one credential for as long as it runs. If you want several accounts used evenly on every request, neither setting does that. Only turning affinity off does, and then you lose the cache reuse that affinity is there to protect.</p>\n\n<h2 id=\"cache-claim\">Does session affinity preserve the prompt cache?</h2>\n\n<p>Anthropic's prompt-caching documentation says the cache lasts 5 minutes by default, and each use of the cached content refreshes it for free. A 1-hour option costs extra. The same page says cache entries are isolated between organizations and, on the Claude API, between workspaces. Two separate accounts are two organizations, so a request that jumps to a second account can't read the first account's cache. That is the reason to keep a session on one credential. That follows from the documentation, though. These logs didn't measure it.</p>\n\n<p>Two settings are easy to mix up here. The proxy's 1-hour <code>session-affinity-ttl</code> is how long a binding between a session and a credential survives while idle. It has nothing to do with how long the provider keeps a cached prefix, which is 5 minutes unless the client asked for the longer option. Also, a binding log line only tells you which credential the proxy used. Whether the provider then served from cache shows up in the response usage fields. A <code>cache_read_input_tokens</code> value above zero is a hit. If both it and <code>cache_creation_input_tokens</code> are zero, nothing was cached.</p>\n\n<p>With default settings, this install records neither field, because request logging is off and no usage data is stored. The accurate thing for a guide to say is that affinity keeps a session on one credential, and that this is a precondition for cache reuse. To measure reuse, turn request logging on for a while, run two turns in a row in one session, and read <code>cache_read_input_tokens</code> from the second response. That test was not run for this article.</p>\n\n<p>To see what losing the cache costs, put your session's token counts into the <a href=\"/tools/agent-cost-estimator\">Agent Cost-per-Run Estimator</a> twice, once with caching and once without. It prices re-sent history and cache reads separately.</p>\n\n<h2 id=\"t3-metadata\">Does T3 Code send a session ID through the proxy?</h2>\n\n<p>T3 Code has no special provider type for proxies. Its <a href=\"https://github.com/pingdotgg/t3code\">README</a> says it controls the agent CLIs set up on your computer, and for each provider instance it launches the real CLI with that instance's environment. For Codex, that means a separate <code>CODEX_HOME</code> whose <code>config.toml</code> defines a custom provider. Codex's documentation describes <code>[model_providers.&lt;id&gt;]</code> with <code>base_url</code>, <code>env_key</code> and <code>wire_api</code>, and says Codex keeps its state under <code>CODEX_HOME</code>:</p>\n\n<pre class=\"language-toml\"><code class=\"language-toml\">model = \"gpt-6-sol\"\nmodel_provider = \"cliproxy\"\n\n[model_providers.cliproxy]\nname = \"CLIProxyAPI\"\nbase_url = \"http://127.0.0.1:8317/v1\"\nwire_api = \"responses\"\nenv_key = \"CLIPROXY_API_KEY\"\nrequires_openai_auth = false</code></pre>\n\n<p>For Claude Code, the instance sets <code>ANTHROPIC_BASE_URL</code>, which the docs describe as the way to send requests through a proxy or gateway, and <code>ANTHROPIC_AUTH_TOKEN</code>, which goes out as the <code>Authorization</code> bearer value. It also sets its own <code>CLAUDE_CONFIG_DIR</code>. Don't add <code>/v1</code> to the base URL, because Claude Code appends <code>/v1/messages</code> itself. Put the proxy's client key in the instance's sensitive environment variables, never in a file you commit.</p>\n\n<figure><img src=\"https://ik.imagekit.io/automationtester/automationtester-in/blog/figures/cliproxyapi-session-affinity-what-logs-prove/fig-11-t3-claude-env.png\" alt=\"T3 Code provider settings for the Claude via CLIProxy instance, with ANTHROPIC_BASE_URL set to http://127.0.0.1:8317 and ANTHROPIC_AUTH_TOKEN held as a stored secret\" width=\"800\" height=\"500\" loading=\"lazy\" /><figcaption>The Claude instance in T3 Code. The base URL points at the local proxy with no <code>/v1</code>, and T3 keeps the token as a stored secret that it never shows again.</figcaption></figure>\n\n<figure><img src=\"https://ik.imagekit.io/automationtester/automationtester-in/blog/figures/cliproxyapi-session-affinity-what-logs-prove/fig-12-t3-model-picker.png\" alt=\"T3 Code model picker listing Claude Opus 5.5 twice, once under the Claude provider and once under Claude via CLIProxy\" width=\"800\" height=\"500\" loading=\"lazy\" /><figcaption>The same model appears once for each provider instance. Picking the \"Claude via CLIProxy\" entry is what sends the request through the proxy.</figcaption></figure>\n\n<p>Because the real CLIs send the requests, the headers and body fields that affinity reads are the CLIs' own. The log backs this up. <code>claude:</code> and <code>codex:</code> prefixes appear, and those only exist when a client sends an explicit identity. What the log can't confirm is how it behaves per thread. The truncated IDs hide whether each T3 thread gets its own session, and you'd need to capture headers to know which one carried the ID.</p>\n\n<h2 id=\"corrections\">Corrections for the guide you started from</h2>\n\n<ul>\n<li>Session affinity is in stock CLIProxyAPI v8.0.58 and is off by default. Only expiration-aware scheduling needs a fork.</li>\n<li>Replace the \"enable WebSockets\" line with the real v8 field, <code>upstream.codex.websocket-compression</code>.</li>\n<li>Change \"preserves the 5-minute cache\" to \"keeps a session on one credential, a precondition for cache reuse\".</li>\n<li>Say that <code>fill-first</code> does not spread load, and that bindings are per session and model.</li>\n<li>Add that bindings live in memory and disappear on restart.</li>\n<li>\"Switches seamlessly\" is only true inside one provider's pool, and with <code>rebind-on: \"quota\"</code> transient errors keep the binding on purpose.</li>\n<li>The binary is <code>cliproxyapi</code>. If a guide spells it with an extra <code>p</code>, the command will fail when you paste it.</li>\n</ul>\n\n<h2 id=\"apply-now\">Apply this now</h2>\n\n<p>Run <code>cliproxyapi --help</code> and note the version. Compare your <code>routing</code> block with the <code>config.example.yaml</code> for that exact tag. Grep your log for <code>session-affinity:</code>, count the hits, new bindings and <code>lcp:</code> lines, and look at the prefix on every <code>session=</code> value. Keep three things as evidence: the version string, the counts, and one line for each prefix type with the session ID and credential masked.</p>\n\n<p>If you run several accounts, know that pooling subscription accounts through a local proxy may break a provider's terms. This article didn't check any provider's terms. Read them before you add a second credential, and count a suspended account as a real cost of this setup.</p>\n\n<h2 id=\"faq\">FAQ</h2>\n\n<h3 id=\"faq-restart\">Do bindings survive a proxy restart?</h3>\n<p>No. The binding cache lives in memory, so after a restart every session starts cold and the routing strategy places it again. If that first request lands on a different credential, it also misses the provider's cache.</p>\n\n<h3 id=\"faq-fill-first\">Is fill-first a good choice with affinity on?</h3>\n<p>It is predictable. New sessions go to the first credential until it is blocked. That makes it a poor choice if you want accounts used evenly. Use <code>round-robin</code> to spread new sessions, or <code>weighted-round-robin</code> with a top-level <code>weight</code> field in each credential file when your accounts have different quotas.</p>\n\n<h3 id=\"faq-model-switch\">What happens when I switch models mid-conversation?</h3>\n<p>The model is part of the binding key, so the new model gets its own binding, possibly on a different credential.</p>\n\n<h3 id=\"faq-no-id\">Why would a request show an lcp: session?</h3>\n<p>The request had no explicit session header or body field, so the proxy matched it on the start of the message content instead. That works, but it is the fallback. A test call made by hand is one way to get one, as happened here.</p>\n\n<h3 id=\"faq-usage-error\">T3 shows a usage error but requests succeed. Is routing broken?</h3>\n<p>The setup guide reports a JSON-RPC <code>-32600</code> message in T3's usage panel for a Codex instance with no ChatGPT login. It reads that as T3's own usage check failing, not routing. The check that matters is an HTTP 200 on the model request in the proxy log.</p>\n\n<h2 id=\"references\">Primary references</h2>\n\n<ul>\n<li><a href=\"https://github.com/router-for-me/CLIProxyAPI/blob/v8.0.58/config.example.yaml\">CLIProxyAPI v8.0.58, <code>config.example.yaml</code></a>: the <code>routing</code> block, its defaults and the semantics of <code>session-affinity-rebind-on</code> and <code>session-affinity-subagents</code>.</li>\n<li><a href=\"https://github.com/router-for-me/CLIProxyAPI/blob/v8.0.58/sdk/cliproxy/auth/selector.go\"><code>sdk/cliproxy/auth/selector.go</code> at v8.0.58</a>: <code>SessionAffinitySelector.Pick</code>, the binding key, <code>FillFirstSelector.Pick</code> and the <code>ExtractSessionID</code> priority list.</li>\n<li><a href=\"https://platform.claude.com/docs/en/build-with-claude/prompt-caching\">Anthropic prompt caching</a>: the 5-minute default lifetime, refresh on use, the 1-hour option, usage fields and organization/workspace isolation.</li>\n<li><a href=\"https://code.claude.com/docs/en/env-vars\">Claude Code environment variables</a>: <code>ANTHROPIC_BASE_URL</code>, <code>ANTHROPIC_AUTH_TOKEN</code> and <code>CLAUDE_CONFIG_DIR</code>.</li>\n<li><a href=\"https://developers.openai.com/codex/config-advanced\">Codex advanced configuration</a>: custom <code>model_providers</code> entries and <code>CODEX_HOME</code>.</li>\n<li><a href=\"https://t3.codes\">T3 Code</a> and its <a href=\"https://github.com/pingdotgg/t3code\">GitHub repository</a>: what T3 Code is, the providers it supports and that it drives the agent CLIs installed on your machine.</li>\n<li><a href=\"https://help.router-for.me/introduction/quick-start\">CLIProxyAPI documentation</a> and the <a href=\"https://formulae.brew.sh/formula/cliproxyapi\">Homebrew formula</a>: installing the proxy.</li>\n<li><a href=\"https://code.claude.com/docs/en/overview\">Claude Code overview</a> and <a href=\"https://developers.openai.com/codex\">Codex documentation</a>: the two agent CLIs routed through the proxy.</li>\n</ul>"}