<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Felipe Vicens on Medium]]></title>
        <description><![CDATA[Stories by Felipe Vicens on Medium]]></description>
        <link>https://medium.com/@fjvicens?source=rss-a4abbe6cb818------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OQBYXwPpDWpvFte4DaJ7-w.jpeg</url>
            <title>Stories by Felipe Vicens on Medium</title>
            <link>https://medium.com/@fjvicens?source=rss-a4abbe6cb818------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 08:30:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fjvicens/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Let Claude Code Run Anything, Without Letting It Touch Your Machine]]></title>
            <link>https://medium.com/@fjvicens/let-claude-code-run-anything-without-letting-it-touch-your-machine-02692bf491ac?source=rss-a4abbe6cb818------2</link>
            <guid isPermaLink="false">https://medium.com/p/02692bf491ac</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[model-context-protocol]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[docker]]></category>
            <dc:creator><![CDATA[Felipe Vicens]]></dc:creator>
            <pubDate>Sat, 31 Oct 2026 20:21:58 GMT</pubDate>
            <atom:updated>2026-10-31T20:21:58.200Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uCnWA09sFJTm8lmIzreAZQ.png" /></figure><p>Coding agents are good at running things, and that’s the whole point of them. Claude Code reads a repo, installs what it needs, runs the tests and fixes what breaks. The problem is where all of that runs: on your own machine, with your files, your network and your keys.</p><p>So sooner or later you end up in one of these places:</p><ul><li><strong>You approve every command by hand.</strong> It’s safe, but after the twentieth npm install prompt you stop reading them and just press Enter.</li><li><strong>You turn the prompts off.</strong> --dangerously-skip-permissions makes the agent fast, and the name of the flag already tells you what you give up.</li><li><strong>You test an unknown repo anyway.</strong> Its postinstall script, its test fixtures and its dependencies all run as you, with full access to your $HOME.</li><li><strong>Your API key sits in the environment.</strong> Anything the agent runs can read it, including code you have never looked at.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TL_yfv4e9uKZDxYnaHHNAQ.png" /><figcaption><em>The problem: the agent’s commands, an unknown repo’s install scripts and your API key all share one machine.</em></figcaption></figure><p>The fix is to give the agent a place to run things that isn’t your machine. <strong>OpenSandbox</strong>, an open source project of the Agentic AI Foundation (AAIF), does exactly that. A small server on your machine creates throwaway Docker containers on demand, and you run commands and move files inside them through a CLI, an SDK or an MCP server. When you’re done, the container is gone, and everything the agent installed goes with it.</p><p>This post takes you from zero to three working setups: first a sandbox you drive by hand, then Claude Code using sandboxes through MCP, and finally Claude Code running inside a sandbox in YOLO mode, behind a network policy and with a vault that keeps your real API key out of its reach. Every output below was captured from a real run on <strong>OpenSandbox </strong><strong>1.2.0</strong>, Claude Code 2.1.316 and Docker Engine 29.9.2 on Ubuntu 24.04, and I ran the whole thing twice from zero.</p><blockquote>📦 <strong>Companion repo.</strong> Every command in this post can be pasted as it is. Scenario 3 downloads its script from <a href="https://github.com/felipevicens/aaif-labs/tree/main/opensandbox/claude-code-quickstart">felipevicens/aaif-labs</a>, where you&#39;ll also find the other steps as scripts.</blockquote><h3>The mental model (read this before the commands)</h3><p><strong>OpenSandbox is a server that turns “run this” into “run this in a fresh container”.</strong> You talk to the server, never to Docker directly. The server creates the container, puts a small agent called execd inside it, and from then on every command and every file operation goes through execd.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T_ypTg2zfvwkbCwZ52JZEA.png" /><figcaption><em>OpenSandbox sits between your tools and Docker: the CLI, the SDK and the MCP server all talk to one local server, which creates and drives the sandbox containers.</em></figcaption></figure><ul><li><strong>One server, many clients.</strong> The osb CLI, the Python SDK and the MCP server are thin clients of the same API, so once you know one of them you know the others.</li><li><strong>Every sandbox has a lifetime.</strong> You give it a timeout when you create it, and when the time is up the server deletes it, even if you forget.</li><li><strong>The egress sidecar is optional.</strong> It only joins a sandbox that you create with a network policy, and Scenario 3 is the only one that uses it.</li></ul><p><strong>And the words you’ll see</strong>, one line each:</p><ul><li><strong>Sandbox:</strong> one throwaway container that OpenSandbox created for you.</li><li><strong>execd:</strong> the small process OpenSandbox puts inside every sandbox to run your commands.</li><li><strong>MCP (Model Context Protocol):</strong> the standard way to give an AI agent new tools. OpenSandbox ships an MCP server, so Claude Code gets tools like sandbox_create and command_run.</li><li><strong>Egress:</strong> traffic going out of the sandbox, to the internet.</li><li><strong>Credential Vault:</strong> an OpenSandbox feature that adds your real API key to outgoing requests, outside the sandbox, so the code inside never has it.</li><li><strong>YOLO mode:</strong> developer slang (“you only live once”) for running a coding agent with every permission prompt turned off. In Claude Code that’s the --dangerously-skip-permissions flag: the agent runs every command without asking you first.</li></ul><h3>Prerequisites</h3><ul><li><strong>Linux with Docker Engine</strong>, not the Docker snap package (the first gotcha explains why). I used Docker Engine 29.9.2 from docker.com on Ubuntu 24.04, and the sed commands below assume GNU sed.</li><li><strong>uv</strong>, to install the three OpenSandbox tools. I used 0.12.5.</li><li><strong>For Scenario 1, nothing else.</strong> No account and no key.</li><li><strong>For Scenarios 2 and 3</strong>, Claude Code and a key for it: an ANTHROPIC_API_KEY, or an ANTHROPIC_AUTH_TOKEN plus ANTHROPIC_BASE_URL if your company runs its own Anthropic-compatible gateway. I used the second option, so in the outputs below the gateway&#39;s hostname is replaced with &lt;your-gateway&gt;.</li></ul><h3>Setup</h3><h3>1. Install OpenSandbox</h3><p>There are three small Python tools: the server, the osb CLI and the MCP server.</p><pre>uv tool install opensandbox-server==1.2.0<br>uv tool install opensandbox-cli==1.2.0<br>uv tool install opensandbox-mcp==1.2.0<br>export PATH=&quot;$HOME/.local/bin:$PATH&quot;</pre><h3>2. Generate the config and make three changes</h3><p>The server ships with a ready example for Docker:</p><pre>opensandbox-server init-config ~/.sandbox.toml --example docker</pre><p>Three things in that file broke when I left them as generated, so these commands change them for you and print the result:</p><pre>sed -i &quot;/^\[server\]/a api_key = \&quot;$(openssl rand -hex 16)\&quot;&quot; ~/.sandbox.toml<br>sed -i \<br>  -e &#39;s#^execd_image = .*#execd_image = &quot;opensandbox/execd:release-1.2.0&quot;#&#39; \<br>  -e &#39;s#^image = &quot;opensandbox/egress:.*#image = &quot;opensandbox/egress:release-1.2.0&quot;#&#39; \<br>  -e &#39;s/^mode = &quot;dns&quot;$/mode = &quot;dns+nft&quot;/&#39; \<br>  ~/.sandbox.toml<br>grep -E &#39;^(api_key|execd_image|image|mode|no_new_privileges)&#39; ~/.sandbox.toml</pre><p>Output (I masked the key):</p><pre>api_key = &quot;****&quot;<br>execd_image = &quot;opensandbox/execd:release-1.2.0&quot;<br>no_new_privileges = true<br>mode = &quot;direct&quot;<br>image = &quot;opensandbox/egress:release-1.2.0&quot;<br>mode = &quot;dns+nft&quot;</pre><ul><li><strong>api_key.</strong> Without it, the server refuses to start unless you&#39;re at an interactive terminal to confirm the risk, and every client sends this key from now on.</li><li><strong>The two images.</strong> The 1.2.0 example still points at execd:v1.1.0 and egress:v1.1.7, and with the old execd the CLI prints every output line glued to the next one. Matching the release fixes it.</li><li><strong>mode = &quot;dns+nft&quot;.</strong> Scenario 3&#39;s Credential Vault refuses to run in the default dns mode. Scenarios 1 and 2 don&#39;t use the sidecar, so the change doesn&#39;t affect them.</li></ul><p>The mode = &quot;direct&quot; line belongs to another section and stays as it is, and so does no_new_privileges = true, which you want to keep.</p><h3>3. Start the server</h3><p>Start it in its own terminal and leave it running:</p><pre>opensandbox-server --config ~/.sandbox.toml</pre><p>In a second terminal, check that it answers:</p><pre>curl -s http://127.0.0.1:8080/health</pre><pre>{&quot;status&quot;:&quot;healthy&quot;}</pre><p>The CLI, the SDK and the MCP server all read the same variables, so set them in every terminal you use for the scenarios. The API key comes straight from the config file:</p><pre>export PATH=&quot;$HOME/.local/bin:$PATH&quot;<br>export OPEN_SANDBOX_API_KEY=$(sed -n &#39;s/^api_key = &quot;\(.*\)&quot;$/\1/p&#39; ~/.sandbox.toml)<br>export OPEN_SANDBOX_DOMAIN=localhost:8080<br>export OPEN_SANDBOX_PROTOCOL=http</pre><h3>Scenarios</h3><h3>Scenario 1: your first sandbox, by hand</h3><p>Before any agent touches it, use it yourself. This creates a sandbox from a plain python:3.12-slim image with a 30-minute lifetime and keeps its ID in $SID:</p><pre>SID=$(osb sandbox create --image python:3.12-slim --timeout 30m -o json \<br>  | python3 -c &#39;import json,sys; print(json.load(sys.stdin)[&quot;id&quot;])&#39;)<br>echo &quot;sandbox: $SID&quot;</pre><pre>sandbox: ea010e55-86bb-4bc8-ac53-353c25a33514</pre><p>Now run a few commands in it:</p><pre>osb command run &quot;$SID&quot; -- python --version<br>osb command run &quot;$SID&quot; -- sh -c &#39;whoami &amp;&amp; hostname &amp;&amp; head -1 /etc/os-release&#39;</pre><pre>Python 3.12.16<br>root<br>48a8896aa524<br>PRETTY_NAME=&quot;Debian GNU/Linux 13 (trixie)&quot;</pre><p>Notice the sh -c &#39;...&#39; in the second command. osb quotes every word you give it after --, so whoami &amp;&amp; hostname would send &amp;&amp; to whoami as a literal argument. Anything with &amp;&amp;, | or &gt; goes inside sh -c.</p><p>Write a file into the sandbox and run it:</p><pre>osb file write &quot;$SID&quot; /tmp/hello.py --content &#39;print(&quot;2 + 2 =&quot;, 2 + 2)&#39;<br>osb command run &quot;$SID&quot; -- python /tmp/hello.py</pre><pre>✅ Written: /tmp/hello.py<br>2 + 2 = 4</pre><p>Now the part that matters. Install a package inside the sandbox, use it, and then check whether your own machine has it:</p><pre>osb command run &quot;$SID&quot; -- sh -c &#39;pip install -q cowsay 2&gt;/dev/null; python -m cowsay -t &quot;hello from the sandbox&quot;&#39;<br>python3 -c &#39;import cowsay&#39;</pre><pre>______________________<br>| hello from the sandbox |<br>  ======================<br>                      \<br>                       \<br>                         ^__^<br>                         (oo)\_______<br>                         (__)\       )\/\<br>                             ||----w |<br>                             ||     ||<br>ModuleNotFoundError: No module named &#39;cowsay&#39;</pre><p>The cow came from the sandbox, and the ModuleNotFoundError came from your machine, which never saw the package. Kill the sandbox when you&#39;re done:</p><pre>osb sandbox kill &quot;$SID&quot;</pre><pre>Sandboxes<br>╭──────────────────────────────────────┬────────────────────╮<br>│ SANDBOX_ID                           │ STATUS             │<br>├──────────────────────────────────────┼────────────────────┤<br>│ ea010e55-86bb-4bc8-ac53-353c25a33514 │ deletion_requested │<br>╰──────────────────────────────────────┴────────────────────╯</pre><p>The whole scenario, from create to kill, took 12 seconds on my machine with the images already pulled.</p><h3>Scenario 2: the quick win, Claude Code with sandbox tools</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FstC6OuYbzcY-We2AAvweg.png" /><figcaption><em>Claude Code keeps running on your machine, but every command it wants to run goes through MCP into a fresh sandbox.</em></figcaption></figure><p>Now give the same power to Claude Code. OpenSandbox ships an MCP server, so Claude Code gets tools to create sandboxes, run commands and edit files in them. Claude Code itself keeps running on your machine, while the work happens in the sandbox.</p><p>Register the MCP server from the folder where you’ll start Claude Code, because the entry is scoped to that folder:</p><pre>claude mcp add opensandbox --transport stdio \<br>  -e OPEN_SANDBOX_API_KEY=&quot;$OPEN_SANDBOX_API_KEY&quot; \<br>  -- opensandbox-mcp --domain localhost:8080 --protocol http<br>claude mcp list</pre><p>These are the two lines that matter in the output:</p><pre>Added stdio MCP server opensandbox with command: opensandbox-mcp --domain localhost:8080 --protocol http to local config<br>opensandbox: opensandbox-mcp --domain localhost:8080 --protocol http - ✔ Connected</pre><p>Any other MCP client, like Cursor, works the same way: point it at the opensandbox-mcp command with the same arguments.</p><p>Here is the use case I find most useful. You found a repo that looks fine, but you don’t want its install scripts and tests running on your laptop before you’ve read them. Start claude in that folder and paste this prompt:</p><pre>I found this repo and I do not trust it yet: https://github.com/pallets/itsdangerous<br>Use the opensandbox MCP tools, never this machine. Create a sandbox from the python:3.12 image, clone the repo there, install it with its test dependencies and run the test suite. Tell me how many tests passed and failed. Kill the sandbox when you are done.</pre><p>In a normal claude session, Claude Code asks you to approve each MCP call before it runs. I ran it with claude -p instead, Claude Code&#39;s non-interactive mode: it takes the prompt, does the work and exits, and it can log every tool call it makes. That&#39;s where the list below comes from. In this mode there&#39;s nobody to answer a permission prompt, so you allow the tools up front with --allowedTools. Without it, Claude Code stops and asks you to approve sandbox_create. This is the command:</p><pre>claude -p &quot;I found this repo and I do not trust it yet: https://github.com/pallets/itsdangerous. Use the opensandbox MCP tools, never this machine. Create a sandbox from the python:3.12 image, clone the repo there, install it with its test dependencies and run the test suite. Tell me how many tests passed and failed. Kill the sandbox when you are done.&quot; \<br>  --allowedTools &quot;mcp__opensandbox&quot; \<br>  --output-format stream-json --verbose &gt; run.jsonl</pre><p>mcp__opensandbox pre-approves the tools of that MCP server and nothing else. Anything else that needs approval is refused, because nobody is there to approve it. With --output-format stream-json --verbose, Claude Code doesn&#39;t print only its final answer: it writes every step to run.jsonl, one JSON object per line, tool calls included. So the command prints nothing while it runs. When it finishes, run this in the same folder to print the calls it made to the sandbox and then the final answer:</p><pre>python3 - run.jsonl &lt;&lt;&#39;EOF&#39;<br>import json, sys<br>for line in open(sys.argv[1]):<br>    if not line.startswith(&quot;{&quot;):<br>        continue<br>    ev = json.loads(line)<br>    if ev.get(&quot;type&quot;) == &quot;assistant&quot;:<br>        for block in ev[&quot;message&quot;][&quot;content&quot;]:<br>            if block.get(&quot;type&quot;) == &quot;tool_use&quot; and block[&quot;name&quot;].startswith(&quot;mcp__opensandbox__&quot;):<br>                name = block[&quot;name&quot;].removeprefix(&quot;mcp__opensandbox__&quot;)<br>                args = block[&quot;input&quot;]<br>                print(f&quot;{name:&lt;15} {args.get(&#39;command&#39;) or json.dumps(args)}&quot;)<br>    elif ev.get(&quot;type&quot;) == &quot;result&quot;:<br>        print(&quot;\n&quot; + ev.get(&quot;result&quot;, &quot;&quot;))<br>EOF</pre><p>These are the calls from my run, in order, with the command it sent each time. Yours will differ a little, because the agent decides the steps itself:</p><pre>sandbox_create  {&quot;image&quot;: &quot;python:3.12&quot;, &quot;timeout_seconds&quot;: 1800}<br>command_run     which git || (apt-get update -qq &amp;&amp; apt-get install -y -qq git ca-certificates) ; git --version<br>command_run     git clone --depth 1 https://github.com/pallets/itsdangerous /workspace/itsdangerous &amp;&amp; ls /workspace/itsdangerous<br>command_run     git clone --depth 1 https://github.com/pallets/itsdangerous /workspace/itsdangerous &amp;&amp; ls /workspace/itsdangerous &amp;&amp; git -C /workspace/itsdangerous log -1 --oneline<br>command_run     cat /workspace/itsdangerous/pyproject.toml<br>command_run     pip install -q /workspace/itsdangerous pytest freezegun &amp;&amp; pip show itsdangerous | head -3 &amp;&amp; python -c &quot;import itsdangerous; print(itsdangerous.__file__)&quot;<br>command_run     python -I -m pytest -v --tb=short /workspace/itsdangerous/tests<br>sandbox_kill    {&quot;sandbox_id&quot;: &quot;e7779ef7-9100-4582-9315-8806e9d4a3bd&quot;}</pre><p>It read the pyproject.toml before installing anything, which is what you would do too, and it answered with:</p><pre>**297 passed, 0 failed** (in 0.58s, Python 3.12.16, pytest 9.2.0)</pre><p>Then I checked my own machine:</p><pre>ls ~ | grep -i itsdangerous || echo &quot;no clone in \$HOME&quot;<br>python3 -c &#39;import itsdangerous&#39;<br>echo &quot;sandboxes running: $(docker ps --filter label=opensandbox.io/id -q | wc -l)&quot;</pre><pre>no clone in $HOME<br>ModuleNotFoundError: No module named &#39;itsdangerous&#39;<br>sandboxes running: 0</pre><p>No clone, no package and no sandbox left running, and the whole task took 33 seconds. That’s the quick win: <strong>you can let an agent try anything from the internet, and your machine stays exactly as it was.</strong></p><h3>Scenario 3: YOLO mode, safely</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JwshArk4zFAHU6bFJBZouQ.png" /><figcaption><em>Claude Code runs inside the sandbox with no permission prompts; the egress sidecar only lets the model API and npm through, and swaps the fake key for the real one on the way out.</em></figcaption></figure><p>Scenario 2 still asks before each tool call, and Claude Code still runs on your machine. The next step is to put Claude Code itself inside the sandbox and turn the prompts off with --dangerously-skip-permissions, which is only a good idea if two things are true:</p><ul><li><strong>The sandbox can’t talk to anything it doesn’t need.</strong> Here that means the model API and the npm registry, and nothing else.</li><li><strong>The sandbox never has your real key.</strong> Claude Code needs a key to work, but anything that runs next to it could read it.</li></ul><p>OpenSandbox covers both with the egress sidecar. You create the sandbox with a <strong>network policy</strong> that denies everything by default and with <strong>Credential Proxy</strong> enabled. Then, from your machine, you put the real key in the sandbox’s <strong>Credential Vault</strong>. The sandbox only gets a fake key, and when a request leaves it for the model API, the sidecar swaps in the real one.</p><p>The vault is set from the SDK, so this scenario is a Python script. Download it from the companion repo as yolo.py:</p><pre>curl -fsSLo yolo.py https://raw.githubusercontent.com/felipevicens/aaif-labs/main/opensandbox/claude-code-quickstart/scripts/03-yolo-with-vault.py</pre><p>You don’t need to paste anything else, but these are the two parts that matter, copied as they are from the script. First it creates the sandbox with the network policy and the Credential Proxy:</p><pre>sandbox = SandboxSync.create(<br>    image=SandboxImageSpec(IMAGE),<br>    timeout=timedelta(minutes=20),<br>    env=sandbox_env,<br>    connection_config=connection,<br>    network_policy=NetworkPolicy(<br>        defaultAction=&quot;deny&quot;,<br>        egress=[<br>            NetworkRule(action=&quot;allow&quot;, target=model_host),<br>            NetworkRule(action=&quot;allow&quot;, target=&quot;registry.npmjs.org&quot;),<br>        ],<br>    ),<br>    credential_proxy=CredentialProxyConfig(enabled=True),<br>)</pre><p>Then, after a first request that should fail, it puts the real key in the vault, bound to the model’s host and its /v1/* paths:</p><pre>sandbox.credential_vault.create(<br>    credentials=[Credential(name=&quot;model-api&quot;, source={&quot;value&quot;: real_secret})],<br>    bindings=[<br>        CredentialBinding(<br>            name=&quot;model-api&quot;,<br>            match={<br>                &quot;schemes&quot;: [&quot;https&quot;],<br>                &quot;hosts&quot;: [model_host],<br>                &quot;methods&quot;: [&quot;GET&quot;, &quot;POST&quot;],<br>                &quot;paths&quot;: api_paths,<br>            },<br>            auth=auth,<br>        )<br>    ],<br>)</pre><p>Your key stays in your own environment, and the script only hands it to the vault. I ran it against a gateway, with these two variables:</p><pre>export ANTHROPIC_BASE_URL=https://your-gateway.example.com<br>export ANTHROPIC_AUTH_TOKEN=your-gateway-token<br>uv run --with opensandbox==1.2.0 python yolo.py</pre><p>If you use the Anthropic API directly, export only ANTHROPIC_API_KEY=sk-ant-... instead of those two, and the script binds it as an x-api-key header for api.anthropic.com.</p><p>This is the full output of my run. Every line that starts with $ is a command the script ran inside the sandbox, followed by what it printed:</p><pre>curl: (6) Could not resolve host: example.com<br>sandbox: 3bb84768-696a-4966-a41c-d8f6e331f99e<br><br>$ curl -sS -m 20 -o /dev/null -w &#39;POST /v1/messages -&gt; %{http_code}\n&#39; -H &quot;Authorization: Bearer $ANTHROPIC_AUTH_TOKEN&quot; -H &#39;content-type: application/json&#39; -d &#39;{&quot;model&quot;:&quot;claude-haiku-5-5&quot;,&quot;max_tokens&quot;:8,&quot;messages&quot;:[{&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;hi&quot;}]}&#39; &quot;$ANTHROPIC_BASE_URL/v1/messages&quot;<br>POST /v1/messages -&gt; 401<br>$ curl -sS -m 20 -o /dev/null -w &#39;POST /v1/messages -&gt; %{http_code}\n&#39; -H &quot;Authorization: Bearer $ANTHROPIC_AUTH_TOKEN&quot; -H &#39;content-type: application/json&#39; -d &#39;{&quot;model&quot;:&quot;claude-haiku-5-5&quot;,&quot;max_tokens&quot;:8,&quot;messages&quot;:[{&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;hi&quot;}]}&#39; &quot;$ANTHROPIC_BASE_URL/v1/messages&quot;<br>POST /v1/messages -&gt; 200<br>$ env | grep ANTHROPIC_ | sed &#39;s/=.*inside-sandbox/=&lt;fake&gt;/&#39;<br>ANTHROPIC_BASE_URL=https://&lt;your-gateway&gt;<br>ANTHROPIC_AUTH_TOKEN=&lt;fake&gt;<br>$ env | grep -iE &#39;CA_CERT|SSL_CERT&#39; || echo &#39;no CA env vars&#39;<br>NODE_EXTRA_CA_CERTS=/opt/opensandbox/mitmproxy-ca-cert.pem<br>SSL_CERT_FILE=/opt/opensandbox/merged-ca-certificates.pem<br>$ curl -sS -m 10 -o /dev/null -w &#39;%{http_code}\n&#39; https://example.com || echo &#39;blocked&#39;<br>000<br>blocked<br>$ npm install -g @anthropic-ai/claude-code@2.1.316 --no-audit --no-fund 2&gt;&amp;1 | tail -2<br>npm notice To update run: npm install -g npm@12.2.1<br>npm notice<br>$ claude --version<br>2.1.316 (Claude Code)<br>$ mkdir -p /work &amp;&amp; chown node:node /work<br>$ cd /work &amp;&amp; runuser -u node -- env HOME=/home/node claude -p &#39;Create /work/slugify.js exporting a slugify(text) function, plus /work/slugify.test.js using node:test with at least 5 cases. Run the tests with node --test and fix anything that fails. Finish with a one-line summary of the test result.&#39; --dangerously-skip-permissions --output-format text<br>All tests pass: 8/8 tests green in `node --test` (after fixing one incorrect test expectation - punctuation like `.` is removed rather than becoming a hyphen separator, so `&#39;A.B! C#D&#39;` → `&#39;ab-cd&#39;`).<br>$ ls -la /work &amp;&amp; cd /work &amp;&amp; node --test 2&gt;&amp;1 | tail -8<br>total 16<br>drwxr-xr-x 2 node node 4096 Oct 31 14:25 .<br>drwxr-xr-x 1 root root 4096 Oct 31 14:25 ..<br>-rw-r--r-- 1 node node  731 Oct 31 14:25 slugify.js<br>-rw-r--r-- 1 node node 1207 Oct 31 14:25 slugify.test.js<br># tests 8<br># suites 0<br># pass 8<br># fail 0<br># cancelled 0<br># skipped 0<br># todo 0<br># duration_ms 42.146815<br>sandbox killed</pre><p>Read it from the top, because each block proves one part of the setup:</p><ul><li><strong>The vault is doing the work.</strong> The same command with the same fake token gets 401 before the vault exists and 200 after it. The only thing that changed is the vault on the sidecar.</li><li><strong>The sandbox only sees the fake key.</strong> The real one never enters the sandbox’s environment, its files or its command line.</li><li><strong>Nothing else needs configuring.</strong> The sidecar is a man-in-the-middle proxy for HTTPS, and OpenSandbox sets NODE_EXTRA_CA_CERTS and SSL_CERT_FILE so tools like Node and curl trust it. Both npm install and the model calls went through it with no extra step.</li><li><strong>The network policy holds.</strong> example.com isn&#39;t on the allow list, so it doesn&#39;t even resolve. The curl: (6) line at the very top is that same error, printed on stderr before the rest of the output.</li><li><strong>The agent does real work with no prompts.</strong> Claude Code wrote slugify.js and 8 tests and fixed one of its own tests, and the script checked the result with node --test instead of trusting the agent&#39;s summary.</li></ul><p>Why runuser -u node? Claude Code refuses YOLO mode as root, and that&#39;s the second gotcha below. The whole run, including the npm install, took 40 seconds, and then the script killed the sandbox and its sidecar. OpenSandbox&#39;s docs say the vault only lives in the sidecar&#39;s memory, so it goes with it.</p><h3>Gotchas worth remembering</h3><p><strong>The problem.</strong> On Ubuntu with Docker from snap, every sandbox dies right after it starts. The container log says exec /opt/opensandbox/bootstrap.sh: operation not permitted, and the kernel log explains why:</p><pre>apparmor=&quot;DENIED&quot; operation=&quot;exec&quot; info=&quot;no new privs&quot; profile=&quot;snap.docker.dockerd&quot; name=&quot;/opt/opensandbox/bootstrap.sh&quot;</pre><p>OpenSandbox starts every sandbox with no-new-privileges, and the AppArmor profile of the snap blocks exec under that flag. It isn&#39;t an OpenSandbox bug, because a plain docker run --security-opt no-new-privileges=true fails the same way on that Docker. <em>What it means for you:</em> use Docker Engine from docker.com. Turning no_new_privileges off in the config also makes it start, but it weakens the isolation you came here for.</p><p><strong>The problem.</strong> claude -p ... --dangerously-skip-permissions exits with code 1 and prints --dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons, because sandbox commands run as root by default. <em>What it means for you:</em> run the agent as a normal user inside the sandbox. The node image already has one, so runuser -u node -- env HOME=/home/node claude ... is enough, and the sandbox&#39;s environment, fake key included, comes along.</p><p><strong>The problem.</strong> When the OpenSandbox server is down, claude mcp list still shows ✔ Connected, because that status is about the opensandbox-mcp process, which starts fine without the server. The tools then fail with a bare Error executing tool sandbox_create that doesn&#39;t say why. <em>What it means for you:</em> when the tools fail, run curl -s http://127.0.0.1:8080/health before anything else.</p><p><strong>The problem.</strong> The sandbox timeout is a hard limit. I created one with --timeout 1m, ran a command, waited 75 seconds and ran it again:</p><pre>alive<br>Sandbox Error<br>  Get endpoint for sandbox 6cac589a-b832-4c0d-a686-8f39ddb90500 port 44772 <br>failed: Sandbox 6cac589a-b832-4c0d-a686-8f39ddb90500 not found. | <br>[DOCKER::SANDBOX_NOT_FOUND] Sandbox 6cac589a-b832-4c0d-a686-8f39ddb90500 not <br>found. | request_id=1d5dfaa3d628457184622592015dd29f</pre><p><em>What it means for you:</em> the sandbox and everything in it is gone with no warning, so give it enough time for the task or extend it with osb sandbox renew. For an agent that&#39;s a feature, because a forgotten sandbox cleans itself up.</p><p><strong>The problem.</strong> A wrong API key fails fast and clearly, which is good to know when you debug a client:</p><pre>List sandboxes failed: Authentication credentials are invalid. Check your API key and try again. | [INVALID_API_KEY]</pre><p><em>What it means for you:</em> if osb, the SDK or the MCP server can&#39;t talk to the server, compare OPEN_SANDBOX_API_KEY with the api_key in ~/.sandbox.toml first.</p><h3>Running without a model key</h3><p>Scenario 1 needs no key and no account, and it already shows the whole idea in small: create, run, install, kill, and your machine never changes. You can also drive sandboxes from your own code with the same SDK that yolo.py uses, with no model involved. Scenarios 2 and 3 need a key only because Claude Code needs one.</p><p>I only tested on Linux with Docker Engine. The project also documents a Kubernetes runtime, which this post doesn’t cover.</p><h3>Wrap-up</h3><p>You started with an agent that ran everything on your machine, as you, and you now have a local server that gives every task its own container with a lifetime. You used it by hand with osb, Claude Code used it through MCP to test a repo it didn&#39;t trust while your machine stayed clean, and Claude Code ran inside a sandbox with no prompts at all, with a network that only reaches two hosts and a key it never saw.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4oMEh1f9jlhSIG3WpePfg.png" /><figcaption><em>Before: the agent, the unknown repo and the key share your machine. After: each task gets its own sandbox, and the key stays outside.</em></figcaption></figure><p>The pieces, once, in plain terms: the <strong>server</strong> creates and expires sandboxes; <strong>osb, the SDK and </strong><strong>opensandbox-mcp</strong> are three doors into the same API; the <strong>network policy</strong> decides where a sandbox can connect; and <strong>Credential Vault</strong> adds your real key on the way out, so it never enters the sandbox.</p><p>Everything here ran on one machine with Docker. The same API also runs on Kubernetes, and the project has more that I haven’t tested yet, like pause and resume, snapshots and a faster Firecracker-based runtime. That’s for a next post.</p><h3>Tear down</h3><p>Kill every sandbox that is still running:</p><pre>for id in $(osb sandbox list -o json | python3 -c &#39;import json,sys<br>d = json.load(sys.stdin)<br>for s in (d.get(&quot;items&quot;, d) if isinstance(d, dict) else d):<br>    print(s[&quot;id&quot;])&#39;); do osb sandbox kill &quot;$id&quot;; done</pre><p>Stop opensandbox-server with Ctrl+C in its terminal. Then, from the folder where you added it, remove the MCP entry:</p><pre>claude mcp remove opensandbox</pre><p>Uninstall the tools and delete the config, the local data and the script:</p><pre>uv tool uninstall opensandbox-server<br>uv tool uninstall opensandbox-cli<br>uv tool uninstall opensandbox-mcp<br>rm -rf ~/.sandbox.toml ~/.opensandbox yolo.py</pre><p>The images you pulled stay in Docker until you remove them:</p><pre>docker image rm opensandbox/execd:release-1.2.0 opensandbox/egress:release-1.2.0 \<br>  python:3.12-slim python:3.12 node:22-bookworm</pre><p>If you exported your model key in this terminal, clear it too:</p><pre>unset ANTHROPIC_API_KEY ANTHROPIC_AUTH_TOKEN ANTHROPIC_BASE_URL OPEN_SANDBOX_API_KEY</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=02692bf491ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[One API, Any Provider: Switching LLMs Without Changing Your App.]]></title>
            <link>https://medium.com/@fjvicens/one-api-any-provider-switching-llms-without-changing-your-app-44528b1271ef?source=rss-a4abbe6cb818------2</link>
            <guid isPermaLink="false">https://medium.com/p/44528b1271ef</guid>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[platform-engineering]]></category>
            <category><![CDATA[api-gateway]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Felipe Vicens]]></dc:creator>
            <pubDate>Wed, 30 Sep 2026 21:33:04 GMT</pubDate>
            <atom:updated>2026-09-30T21:33:04.249Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OQpKsrIrsTzaQAJowGUckg.png" /><figcaption>One API. Any Provider</figcaption></figure><p>Say your app talks to OpenAI directly. One SDK, one base URL, one key, and it works fine. Then someone asks you to also try Gemini because it has a free tier, or to move one feature to Claude because it answers better.</p><p>Each provider has its own API. You can bolt on a second SDK. Or you can point the OpenAI SDK at the other provider’s OpenAI-compatible endpoint, which works for simple calls. Both options leave you with the same problems:</p><ul><li><strong>Every app holds every key.</strong> Each service that calls a model needs its own copy of the OpenAI key, the Gemini key, and whatever comes next.</li><li><strong>Switching provider is a deploy.</strong> Moving a feature from OpenAI to Gemini means changing code or config in every app that uses it, then shipping them.</li><li><strong>Each provider has its own details.</strong> Auth goes in a different header, some fields have a different name, and the answer comes back in a different shape. Someone has to know all of it, in every app.</li><li><strong>There’s no single place for the next step.</strong> Fallback, rate limits, cost tracking and guardrails end up written once per app, if they get written at all.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-l68n_ykKIxf1MbkTugaaQ.png" /><figcaption><em>Before a gateway: every app carries every provider’s key, auth header and request format, so switching provider means changing every app.</em></figcaption></figure><p>The fix is to put <strong>agentgateway</strong>, an open source gateway for LLM traffic, in front of all of them. Your app talks to one address, always in OpenAI’s format, with no provider key at all. The gateway holds the keys, picks the provider, and translates the request into that provider’s own API when it has to.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q8mAqYrgji0ZwvR7shM27w.png" /><figcaption><em>After agentgateway: apps send one OpenAI-shaped request with no provider key, and the gateway adds the key and speaks each provider’s API.</em></figcaption></figure><p>This post builds exactly that, and it shows the translation happening instead of asking you to trust it. Every output below (status codes, response bodies, what each provider actually received) came from a real request against a live gateway. It runs on <strong>agentgateway open source</strong>, version <strong>1.5.0</strong>, on a throwaway Kubernetes cluster you can delete when you&#39;re done.</p><blockquote>📦 <strong>Companion repo.</strong> Every manifest in this post lives in <a href="https://github.com/felipevicens/aaif-labs/tree/main/agentgateway/multi-provider/manifests">felipevicens/aaif-labs</a>. Apply them as you read.</blockquote><h3>The mental model (read this before the YAML)</h3><p>If you’re new to gateways or Kubernetes, a few ideas up front make the YAML below easy to follow.</p><p><strong>The whole lab is one route and one backend.</strong> Your app sends every request to /v1/chat/completions, the same path the OpenAI SDKs use. A route sends it to one backend called llm. Each scenario changes what&#39;s inside llm: a mock, then OpenAI, then Gemini, then Anthropic, then two providers at once. The route and the app never change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mLxecW7uZ_2x4b5X-A9Oqw.png" /><figcaption><em>Every request enters as one OpenAI-shaped call, and the gateway adds the key and translates it into the API of whichever provider the backend points at.</em></figcaption></figure><ul><li><strong>One request shape in.</strong> Your app is written once, against OpenAI’s /v1/chat/completions body. It never learns which provider answered.</li><li><strong>The </strong><strong>AgentgatewayBackend is where providers live.</strong> It holds the provider type, the model, and a reference to the key. Change it and the traffic moves.</li><li><strong>Translation happens in one place.</strong> For OpenAI there’s nothing to translate. For Gemini and Anthropic the gateway rewrites the body, the headers and the auth, then turns the answer back into OpenAI’s shape. Scenario 3 lets you watch it do that.</li></ul><p><strong>And the Kubernetes words you’ll see</strong>, one line each:</p><ul><li><strong>Kubernetes:</strong> the system that runs everything below as small, managed units called objects.</li><li><strong>kind:</strong> “Kubernetes IN Docker,” a way to run a real but disposable cluster on your laptop with one command.</li><li><strong>Helm:</strong> a package installer for Kubernetes, think apt or brew but for cluster software. We use it to install agentgateway.</li><li><strong>namespace:</strong> a folder-like grouping for related objects. Ours is agentgateway-system.</li><li><strong>Secret:</strong> a Kubernetes object that holds a sensitive value, like an API key, so it never has to appear in a YAML file.</li><li><strong>CRD (Custom Resource Definition):</strong> teaches Kubernetes a new object type. agentgateway’s CRDs add AgentgatewayBackend, the type this post builds on.</li><li><strong>Gateway API:</strong> the standard Kubernetes API for routing traffic, made of objects like Gateway and HTTPRoute. agentgateway builds on it.</li><li><strong>HTTPRoute:</strong> says &quot;requests matching this path go to that backend.&quot; It&#39;s the wire between the front door and your provider config.</li></ul><h3>Prerequisites</h3><ul><li>A Kubernetes cluster. We use an ephemeral <strong>kind</strong> cluster, node image v1.34.0, so you can throw it away afterward.</li><li>kubectl and helm installed.</li><li><strong>For Scenarios 1 and 3, nothing else.</strong> They use httpbun, a mock that answers in OpenAI’s shape, and a small echo server. No account, no key.</li><li><strong>For Scenario 2</strong>, an OpenAI API key. For <strong>Scenario 4</strong>, a Gemini API key from Google AI Studio (the free tier is enough). For <strong>Scenario 5</strong>, an Anthropic API key from the Claude Console (it needs prepaid credits, the smallest top-up is more than enough). Scenario 6 needs the OpenAI and Gemini keys. The whole post costs a fraction of a cent in tokens.</li><li><strong>Optional:</strong> Python with the openai package, if you want to see the same thing from real app code instead of curl.</li></ul><h3>Setup</h3><h3>1. Install agentgateway OSS</h3><pre># Create a disposable local cluster<br>kind create cluster --name agentgateway-multi-provider --image kindest/node:v1.34.0<br><br># Install the Kubernetes Gateway API CRDs (the standard traffic-routing types)<br>kubectl apply --server-side -f \<br>  https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.6.0/experimental-install.yaml<br><br># Install agentgateway&#39;s own object types (CRDs), then the gateway itself<br>helm upgrade -i --create-namespace -n agentgateway-system \<br>  --version v1.5.0 agentgateway-crds \<br>  oci://cr.agentgateway.dev/charts/agentgateway-crds<br><br>helm upgrade -i -n agentgateway-system --version v1.5.0 \<br>  agentgateway oci://cr.agentgateway.dev/charts/agentgateway</pre><p>If you read the <a href="https://medium.com/@fjvicens/give-your-team-their-own-api-keys-to-a-shared-local-ai-model-with-agentgateway-dd1848fc3eec">virtual keys post</a>, you may remember it passed a KGW_ENABLE_GATEWAY_API_EXPERIMENTAL_FEATURES flag to Helm. This post passes no flag at all, and nothing in it needs one. You don&#39;t need that post to follow this one.</p><p>Check that Kubernetes accepted agentgateway as a gateway “class”:</p><pre>kubectl get gatewayclass</pre><pre>NAME           CONTROLLER                      ACCEPTED   AGE<br>agentgateway   agentgateway.dev/agentgateway   True       13m</pre><h3>2. Reach the gateway</h3><p>The gateway is exposed as a LoadBalancer service. On a cloud cluster that gets a real external IP. On a local kind cluster there&#39;s no load-balancer provider, so it stays at EXTERNAL-IP: &lt;pending&gt; forever. That&#39;s expected. Every request in this post goes through a kubectl port-forward, which you start in Scenario 1, once the gateway exists.</p><p>One warning if you run this on a cloud cluster. From Scenario 2 on, the gateway holds your provider keys and asks nothing from the client. With a real external IP, anyone who can reach it can spend your keys. Keep it on a port-forward until you add client authentication, as in the <a href="https://medium.com/@fjvicens/give-your-team-their-own-api-keys-to-a-shared-local-ai-model-with-agentgateway-dd1848fc3eec">virtual keys post</a>.</p><h3>Scenarios</h3><p>Each scenario has its own file in the companion repo, numbered in order. Scenarios 2, 4, 5 and 6 re-apply the same backend, llm, so each one replaces the one before.</p><h3>Scenario 1: One route, zero keys</h3><p><strong>File:</strong> 01-gateway-httpbun-route.yaml</p><p>This is the path anyone can finish. It creates the Gateway (the front door), <strong>httpbun</strong> (a mock that answers in OpenAI&#39;s shape), the backend llm pointing at it, and the route that connects them.</p><pre># excerpt of 01-gateway-httpbun-route.yaml<br>apiVersion: agentgateway.dev/v1alpha1<br>kind: AgentgatewayBackend<br>metadata:<br>  name: llm<br>  namespace: agentgateway-system<br>spec:<br>  ai:<br>    provider:<br>      openai:                     # httpbun answers in OpenAI&#39;s shape<br>        model: gpt-4<br>      host: httpbun.default.svc.cluster.local<br>      port: 3090<br>      path: /llm/chat/completions # where httpbun listens<br>---<br>apiVersion: gateway.networking.k8s.io/v1<br>kind: HTTPRoute<br>metadata:<br>  name: llm<br>  namespace: agentgateway-system<br>spec:<br>  parentRefs:<br>    - name: agentgateway-proxy<br>      namespace: agentgateway-system<br>  rules:<br>    - matches:<br>        - path:<br>            type: PathPrefix<br>            value: /v1/chat/completions<br>      backendRefs:<br>        - name: llm<br>          namespace: agentgateway-system<br>          group: agentgateway.dev<br>          kind: AgentgatewayBackend</pre><p>The route matches /v1/chat/completions and has no rewrite filter. You don&#39;t need one. I checked with a route on a completely different path: the request still reached the provider, translated the same way. The provider types that agentgateway knows (openai, gemini, anthropic, ...) set their own upstream path. Matching the real OpenAI path just means an app only has to change its base_url.</p><p>Apply it, and wait until the gateway is ready:</p><pre>kubectl apply -f https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/multi-provider/manifests/01-gateway-httpbun-route.yaml<br>kubectl wait --for=condition=Programmed gateway/agentgateway-proxy \<br>  -n agentgateway-system --timeout=180s</pre><p>Now start the port-forward, and leave it running in its own terminal for the rest of the post:</p><pre>kubectl port-forward -n agentgateway-system svc/agentgateway-proxy 8080:8080</pre><p>Send a request:</p><pre>curl -s http://localhost:8080/v1/chat/completions \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{&quot;model&quot;:&quot;gpt-4o-mini&quot;,&quot;max_tokens&quot;:20,&quot;messages&quot;:[{&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;Say OK&quot;}]}&#39;<br><br>{&quot;model&quot;:&quot;gpt-4&quot;,&quot;usage&quot;:{&quot;prompt_tokens&quot;:4,&quot;completion_tokens&quot;:29,&quot;total_tokens&quot;:33},&quot;choices&quot;:[{&quot;message&quot;:{&quot;content&quot;:&quot;This is a mock chat response from httpbun. I received your messages and I&#39;m responding with this placeholder text.&quot;,&quot;role&quot;:&quot;assistant&quot;},&quot;finish_reason&quot;:&quot;stop&quot;,&quot;index&quot;:0}],&quot;created&quot;:1790460838,&quot;id&quot;:&quot;chatcmpl-6923f116bf334449cdaff6d6&quot;,&quot;object&quot;:&quot;chat.completion&quot;}</pre><p>Notice &quot;model&quot;:&quot;gpt-4&quot;. The client asked for gpt-4o-mini, but the backend says model: gpt-4, and the backend wins. More on that in Gotchas.</p><p>Now the same thing from real app code. This is the entire app, and it doesn’t change for the rest of the post:</p><pre>from openai import OpenAI<br><br>client = OpenAI(base_url=&quot;http://localhost:8080/v1&quot;, api_key=&quot;not-a-real-key&quot;)<br><br>reply = client.chat.completions.create(<br>    model=&quot;gpt-4o-mini&quot;,<br>    max_tokens=20,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Say OK&quot;}],<br>)<br>print(reply.model, &quot;-&gt;&quot;, reply.choices[0].message.content)<br><br>Download it once, make it executable, and run it:</pre><pre>curl -sO https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/multi-provider/scripts/app.py<br>chmod +x app.py<br>./app.py</pre><pre>gpt-4 -&gt; This is a mock chat response from httpbun. I received your messages and I&#39;m responding with this placeholder text.</pre><p>The api_key is fake on purpose. The app will never hold a provider key: in the next scenarios, the gateway adds the real one.</p><h3>Scenario 2: Swap in OpenAI</h3><p><strong>File:</strong> 02-openai-backend.yaml</p><p>Now the backend llm points at a real provider. The key goes in a Kubernetes Secret, created from your environment, so it never appears in a file:</p><pre>kubectl create secret generic openai-credentials -n agentgateway-system \<br>  --from-literal=Authorization=&quot;$OPENAI_API_KEY&quot;</pre><pre># excerpt of 02-openai-backend.yaml<br>spec:<br>  ai:<br>    provider:<br>      openai:<br>        model: gpt-4o-mini<br>  policies:               # a SIBLING of ai, not inside it<br>    auth:<br>      secretRef:<br>        name: openai-credentials</pre><p>secretRef reads the Authorization key of the Secret by default. You store the bare key, and the gateway sends it upstream as Authorization: Bearer &lt;key&gt;. There&#39;s no host or path: openai is a provider agentgateway already knows.</p><p>Watch where policies goes. It looks like it belongs inside ai, next to the provider it authenticates, but it&#39;s a sibling of ai under spec. Put it inside and the API server rejects the backend with strict decoding error: unknown field &quot;spec.ai.policies&quot;.</p><pre>kubectl apply -f https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/multi-provider/manifests/02-openai-backend.yaml</pre><p>Run the exact same curl as in Scenario 1:</p><pre>curl -s http://localhost:8080/v1/chat/completions \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{&quot;model&quot;:&quot;gpt-4o-mini&quot;,&quot;max_tokens&quot;:20,&quot;messages&quot;:[{&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;Say OK&quot;}]}&#39;<br><br>{&quot;model&quot;:&quot;gpt-4o-mini-2024-07-18&quot;,&quot;service_tier&quot;:&quot;default&quot;,&quot;usage&quot;:{&quot;prompt_tokens&quot;:9,&quot;completion_tokens&quot;:2,&quot;total_tokens&quot;:11,...},&quot;choices&quot;:[{&quot;message&quot;:{&quot;content&quot;:&quot;OK!&quot;,&quot;role&quot;:&quot;assistant&quot;,&quot;refusal&quot;:null,&quot;annotations&quot;:[]},&quot;index&quot;:0,&quot;logprobs&quot;:null,&quot;finish_reason&quot;:&quot;stop&quot;}],&quot;id&quot;:&quot;chatcmpl-ESUwxOfqriloIyNNlvQFHVcJ6DQrK&quot;,&quot;object&quot;:&quot;chat.completion&quot;,...}</pre><p>And the same Python app, unchanged:</p><pre>./app.py<br><br>gpt-4o-mini-2024-07-18 -&gt; OK!</pre><p>A real OpenAI answer, from an app whose only key is not-a-real-key. The gateway replaced the client&#39;s Authorization header with the one from the Secret. That&#39;s the first win: the OpenAI key now lives in exactly one place.</p><p>OpenAI is the easy case, though. Your app already speaks OpenAI’s format, so the gateway just passes the body through. The interesting question is what happens with a provider that doesn’t.</p><h3>Scenario 3: Watch the translation (no keys needed)</h3><p><strong>File:</strong> 03-see-the-translation.yaml</p><p>Gemini and Anthropic don’t use OpenAI’s format. Gemini’s own API is called generateContent and Anthropic&#39;s is called Messages. Both have a different body, a different place for the system prompt, and a different auth header. Instead of trusting that the gateway handles it, let&#39;s look at what it sends.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cuX8PqkF5FXWuO1WAAGnlA.png" /><figcaption><em>One OpenAI-shaped request, two wire formats: what the echo server logged for Gemini and for Anthropic.</em></figcaption></figure><p>This file deploys <strong>echo</strong>, a small server that logs every request it gets: path, headers and body. Two backends point a gemini provider and an anthropic provider at echo instead of at Google or Anthropic. The keys are fake, because nothing real is called. A route called wire sends /wire/gemini to one backend and /wire/anthropic to the other, so this scenario doesn&#39;t touch llm.</p><pre># excerpt of 03-see-the-translation.yaml<br>kind: AgentgatewayBackend<br>metadata:<br>  name: wire-anthropic<br>spec:<br>  ai:<br>    provider:<br>      anthropic:<br>        model: claude-haiku-4-5<br>      host: echo.default.svc.cluster.local   # echo instead of api.anthropic.com<br>      port: 8080<br>  policies:<br>    auth:<br>      key: fake-anthropic-key</pre><p>Apply it, then send one OpenAI-shaped request to each, this time with a system message so you can see where it ends up:</p><pre>kubectl apply -f https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/multi-provider/manifests/03-see-the-translation.yaml<br>kubectl rollout status deploy/echo -n default</pre><pre>curl -s http://localhost:8080/wire/gemini -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{&quot;model&quot;:&quot;gpt-4o-mini&quot;,&quot;max_tokens&quot;:20,&quot;messages&quot;:[{&quot;role&quot;:&quot;system&quot;,&quot;content&quot;:&quot;Be brief.&quot;},{&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;Say OK&quot;}]}&#39;<br><br>curl -s http://localhost:8080/wire/anthropic -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{&quot;model&quot;:&quot;gpt-4o-mini&quot;,&quot;max_tokens&quot;:20,&quot;messages&quot;:[{&quot;role&quot;:&quot;system&quot;,&quot;content&quot;:&quot;Be brief.&quot;},{&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;Say OK&quot;}]}&#39;</pre><p>Both calls return an error or an empty answer to the client (a 502 for Anthropic, an empty 200 for Gemini). That&#39;s expected: echo doesn&#39;t answer like a real provider. What matters is what echo received:</p><pre>kubectl logs deploy/echo -n default</pre><p>Here is the relevant part of each logged request, trimmed:</p><pre>{&quot;path&quot;:&quot;/wire/gemini&quot;,<br> &quot;headers&quot;:{&quot;x-goog-api-key&quot;:&quot;fake-gemini-key&quot;},<br> &quot;body&quot;:{&quot;contents&quot;:[{&quot;role&quot;:&quot;user&quot;,&quot;parts&quot;:[{&quot;text&quot;:&quot;Say OK&quot;}]}],<br>         &quot;systemInstruction&quot;:{&quot;parts&quot;:[{&quot;text&quot;:&quot;Be brief.&quot;}]},<br>         &quot;generationConfig&quot;:{&quot;maxOutputTokens&quot;:20}}}<br><br>{&quot;path&quot;:&quot;/wire/anthropic&quot;,<br> &quot;headers&quot;:{&quot;x-api-key&quot;:&quot;fake-anthropic-key&quot;,&quot;anthropic-version&quot;:&quot;2023-06-01&quot;},<br> &quot;body&quot;:{&quot;messages&quot;:[{&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:[{&quot;type&quot;:&quot;text&quot;,&quot;text&quot;:&quot;Say OK&quot;}]}],<br>         &quot;system&quot;:&quot;Be brief.&quot;,&quot;model&quot;:&quot;claude-haiku-4-5&quot;,&quot;max_tokens&quot;:20}}</pre><p>Compare them with what the client sent. Neither provider received OpenAI’s format:</p><ul><li><strong>Gemini got its native </strong><strong>generateContent body.</strong> messages became contents with parts, the system message moved to systemInstruction, and max_tokens became generationConfig.maxOutputTokens. The model isn&#39;t in the body, because Gemini puts it in the URL. The key went into Google&#39;s own x-goog-api-key header.</li><li><strong>Anthropic got a Messages API body.</strong> The system message moved out of the list into its own system field, the content became a list of blocks, and the model became the backend&#39;s claude-haiku-4-5. The key moved from Authorization to x-api-key by itself, and the gateway added the required anthropic-version header.</li></ul><p>Two notes, so you read the log correctly. The path is the client’s own path (/wire/gemini) only because we pointed host at echo. Against the real Google host, the 1.5.0 source sends it to /v1beta/models/&lt;model&gt;:generateContent. And agentgateway goes to Gemini&#39;s native API on purpose, instead of Google&#39;s OpenAI-compatible endpoint: a comment in its source says its own conversion &quot;does a better job than Google&#39;s OpenAI compatible endpoint.&quot;</p><p>Scenarios 4 and 5 send these same bodies to the real Google and Anthropic APIs.</p><h3>Scenario 4: Swap in Gemini</h3><p><strong>File:</strong> 04-gemini-backend.yaml</p><p>Same backend name, llm, now pointing at Gemini. This time the gateway has to do the translation you just saw, for real. Create the Secret with the bare key:</p><pre>kubectl create secret generic gemini-credentials -n agentgateway-system \<br>  --from-literal=Authorization=&quot;$GEMINI_API_KEY&quot;</pre><pre># excerpt of 04-gemini-backend.yaml<br>spec:<br>  ai:<br>    provider:<br>      gemini:<br>        model: gemini-3.5-flash-lite<br>  policies:<br>    auth:<br>      secretRef:<br>        name: gemini-credentials<br>      location:<br>        header:<br>          name: x-goog-api-key   # see the first Gotcha before removing this</pre><p>The location block tells the gateway to send the key in x-goog-api-key instead of Authorization. It looks optional. With my key it isn&#39;t: without it, Gemini answered 401. The first Gotcha explains why.</p><pre>kubectl apply -f https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/multi-provider/manifests/04-gemini-backend.yaml</pre><p>The same curl again:</p><pre>{&quot;model&quot;:&quot;gemini-3.5-flash-lite&quot;,&quot;usage&quot;:{&quot;prompt_tokens&quot;:3,&quot;completion_tokens&quot;:1,&quot;total_tokens&quot;:4},&quot;choices&quot;:[{&quot;message&quot;:{&quot;content&quot;:&quot;OK&quot;,&quot;role&quot;:&quot;assistant&quot;},&quot;index&quot;:0,&quot;finish_reason&quot;:&quot;stop&quot;}],&quot;id&quot;:&quot;yEO4apzKE8yexN8P5Z6A0As&quot;,&quot;created&quot;:1790460870,&quot;object&quot;:&quot;chat.completion&quot;}</pre><p>And ./app.py again:</p><pre>gemini-3.5-flash-lite -&gt; OK</pre><p>Look at the shape of that answer: choices, message, usage with prompt_tokens, &quot;object&quot;:&quot;chat.completion&quot;. That&#39;s OpenAI&#39;s format. Gemini answered in its own format, and the gateway translated it back before your app saw it. The app went from a mock, to OpenAI, to Gemini, and it never changed.</p><h3>Scenario 5: Swap in Anthropic</h3><p><strong>File:</strong> 05-anthropic-backend.yaml</p><p>Now the other body from Scenario 3, the Messages API, goes to the real Anthropic API. Same backend name, llm, and the same pattern as before:</p><pre>kubectl create secret generic anthropic-credentials -n agentgateway-system \<br>  --from-literal=Authorization=&quot;$ANTHROPIC_API_KEY&quot;</pre><pre># excerpt of 05-anthropic-backend.yaml<br>spec:<br>  ai:<br>    provider:<br>      anthropic:<br>        model: claude-haiku-4-5<br>  policies:<br>    auth:<br>      secretRef:<br>        name: anthropic-credentials</pre><p>There&#39;s no location block this time. You saw why in Scenario 3: for an anthropic provider, the gateway moves the key from Authorization to Anthropic&#39;s own x-api-key header by itself, and adds the anthropic-version header the API requires.</p><pre>kubectl apply -f https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/multi-provider/manifests/05-anthropic-backend.yaml</pre><p>The same curl:</p><pre>{&quot;model&quot;:&quot;claude-haiku-4-5-20251001&quot;,&quot;service_tier&quot;:&quot;standard&quot;,&quot;usage&quot;:{&quot;prompt_tokens&quot;:9,&quot;completion_tokens&quot;:4,&quot;total_tokens&quot;:13,...},&quot;choices&quot;:[{&quot;message&quot;:{&quot;content&quot;:&quot;OK&quot;,&quot;role&quot;:&quot;assistant&quot;},&quot;index&quot;:0,&quot;finish_reason&quot;:&quot;stop&quot;}],&quot;id&quot;:&quot;msg_011CfaJdt8G99Q6WfHqSBFXj&quot;,&quot;created&quot;:1790802378,&quot;object&quot;:&quot;chat.completion&quot;}</pre><p>And ./app.py again:</p><pre>claude-haiku-4-5-20251001 -&gt; OK</pre><p>Claude answered, in OpenAI&#39;s format again. The id still starts with msg_, Anthropic&#39;s own prefix, which is a small sign of where the answer came from. Your app doesn&#39;t need to care.</p><p>One detail the translation handles for you: Anthropic requires max_tokens on every request, and OpenAI&#39;s API doesn&#39;t. Send the request without it and you still get a 200, because the gateway fills it in. Send the same request without max_tokens to Scenario 3&#39;s /wire/anthropic, and echo logs &quot;max_tokens&quot;: 4096.</p><p>Streaming works too. scripts/app_stream.py in the companion repo is the same app with stream=True. The part that changes:</p><pre>stream = client.chat.completions.create(<br>    model=&quot;gpt-4o-mini&quot;,<br>    max_tokens=40,<br>    stream=True,<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;Count from 1 to 10, separated by spaces.&quot;}],<br>)<br>for chunk in stream:<br>    if chunk.choices and chunk.choices[0].delta.content:<br>        print(chunk.choices[0].delta.content, end=&quot;&quot;, flush=True)</pre><pre>curl -sO https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/multi-provider/scripts/app_stream.py<br>chmod +x app_stream.py<br>./app_stream.py</pre><pre>1 2 3 4 5 6 7 8 9 10</pre><p>Claude&#39;s stream came back as OpenAI chat.completion.chunk events. I ran the same code against the OpenAI and Gemini backends, with the same result. What I didn&#39;t test is tool calls, so try those with your own app before you rely on them.</p><h3>Scenario 6: Two providers, one backend</h3><p><strong>Files:</strong> 05-provider-groups-openai-first.yaml, 06-provider-groups-gemini-first.yaml</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NJRiwj0ZpmnSlInfXNzBXg.png" /><figcaption><em>Swapping the group order moves all traffic to the other provider, but order alone is not failover.</em></figcaption></figure><p>A backend can also hold several providers at once, through spec.ai.groups. Groups are used in priority order, so group 0 answers every request.</p><pre># excerpt of 06-provider-groups-openai-first.yaml<br>spec:<br>  ai:<br>    groups:<br>      - providers:<br>          - name: openai<br>            openai:<br>              model: gpt-4o-mini<br>            policies:<br>              auth:<br>                secretRef:<br>                  name: openai-credentials<br>      - providers:<br>          - name: gemini<br>            gemini:<br>              model: gemini-3.5-flash-lite<br>            policies:<br>              auth:<br>                secretRef:<br>                  name: gemini-credentials<br>                location:<br>                  header:<br>                    name: x-goog-api-key</pre><p>Each entry under providers is flat: name, policies and the provider type sit directly on it. There&#39;s no provider: wrapper here, unlike the single-provider backends in Scenarios 2, 4 and 5. Both keys stay where they were, each on its own provider.</p><pre>kubectl apply -f https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/multi-provider/manifests/06-provider-groups-openai-first.yaml</pre><pre>gpt-4o-mini-2024-07-18 -&gt; OK!</pre><p>File 07 is the same backend with the two groups swapped. Apply it, and run the same app again:</p><pre>kubectl apply -f https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/multi-provider/manifests/07-provider-groups-gemini-first.yaml</pre><pre>gemini-3.5-flash-lite -&gt; OK</pre><p>That’s what “switching provider is a config change” means in practice. One kubectl apply on the gateway, and every app behind it now talks to Gemini. No app was redeployed.</p><p>So why use groups, if Scenarios 2, 4 and 5 could already switch provider? With groups, both providers are configured at once, each with its own key. Moving traffic is only a change of order, and the second provider is already in place for the next step.</p><p>That next step is failover, and this setup doesn’t give it to you yet. It’s easy to read “group 0, then group 1” as “try OpenAI, and use Gemini if OpenAI is down.” It doesn’t work that way on its own, and the second Gotcha shows it.</p><h3>Gotchas worth remembering</h3><p><strong>The problem.</strong> A Gemini key that doesn’t start with AIza gets 401 through the gateway, even though it works when you call Google directly. By default, agentgateway 1.5.0 only moves a Gemini key into x-goog-api-key if the key starts with AIza. That&#39;s the API_KEY_PREFIX check in crates/llm/src/gemini.rs, where the source says Google keys are &quot;uniformly AIza-prefixed&quot;. Any other key stays in Authorization: Bearer, and Google&#39;s native endpoint reads a Bearer value as an OAuth token. My Google AI Studio key starts with AQ.. To see what happens with the default auth, apply Scenario 4&#39;s backend and remove its location block:</p><pre>kubectl apply -f https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/multi-provider/manifests/04-gemini-backend.yaml<br>kubectl patch agentgatewaybackend llm -n agentgateway-system --type=json \<br>  -p=&#39;[{&quot;op&quot;:&quot;remove&quot;,&quot;path&quot;:&quot;/spec/policies/auth/location&quot;}]&#39;</pre><p>Then the usual request:</p><pre>curl -s http://localhost:8080/v1/chat/completions \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{&quot;model&quot;:&quot;gpt-4o-mini&quot;,&quot;max_tokens&quot;:20,&quot;messages&quot;:[{&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;Say OK&quot;}]}&#39;</pre><pre>{&quot;event_id&quot;:null,&quot;error&quot;:{&quot;type&quot;:&quot;authentication_error&quot;,&quot;message&quot;:&quot;Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.&quot;,&quot;code&quot;:&quot;UNAUTHENTICATED&quot;}}</pre><p>HTTP 401. Apply file 04 again and the location block comes back, and so does the 200. <em>What it means for you:</em> always set location.header to x-goog-api-key on a Gemini backend. It&#39;s Google&#39;s own header for API keys, so it&#39;s the right place for an AIza key too. I could only test it with an AQ. key.</p><p><strong>The problem.</strong> A list of priority groups looks like failover, but it isn’t. File 08-groups-without-eviction.yaml needs no keys: group 0 is an httpbun endpoint that always answers 500, and group 1 is the healthy mock. It has its own backend and its own path, /demo/groups, so it doesn&#39;t touch llm.</p><pre>kubectl apply -f https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/multi-provider/manifests/08-groups-without-eviction.yaml<br>for i in 1 2 3 4 5; do<br>  curl -s -o /dev/null -w &#39;HTTP %{http_code}\n&#39; http://localhost:8080/demo/groups \<br>    -H &#39;Content-Type: application/json&#39; \<br>    -d &#39;{&quot;model&quot;:&quot;gpt-4o-mini&quot;,&quot;messages&quot;:[{&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;Say OK&quot;}]}&#39;<br>done</pre><pre>HTTP 500<br>HTTP 500<br>HTTP 500<br>HTTP 500<br>HTTP 500</pre><p>Five requests, five failures, and the healthy group 1 was never tried. Nothing marks group 0 as unhealthy, so the gateway keeps choosing it. <em>What it means for you:</em> group order gives you a place to put a second provider. It doesn’t give you resilience. To really fail over you need a health policy (policies.health.eviction) on the providers. The failover post in this series, <em>Your Model Just Went Down. Did Anyone Notice?</em>, builds it on top of this same backend.</p><p><strong>The problem.</strong> The backend’s model silently wins over the client’s. When a backend sets model, whatever model the client sends is replaced. Put the OpenAI backend from Scenario 2 back:</p><pre>kubectl apply -f https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/multi-provider/manifests/02-openai-backend.yaml</pre><p>Then ask it for a model that doesn’t exist:</p><pre>curl -s http://localhost:8080/v1/chat/completions \<br>  -H &#39;Content-Type: application/json&#39; \<br>  -d &#39;{&quot;model&quot;:&quot;gpt-nonexistent-model-xyz&quot;,&quot;max_tokens&quot;:20,&quot;messages&quot;:[{&quot;role&quot;:&quot;user&quot;,&quot;content&quot;:&quot;Say OK&quot;}]}&#39;</pre><pre>{&quot;model&quot;:&quot;gpt-4o-mini-2024-07-18&quot;, ... &quot;choices&quot;:[{&quot;message&quot;:{&quot;content&quot;:&quot;OK!&quot;, ...</pre><p>No error, and an answer from gpt-4o-mini. <em>What it means for you:</em> the model field in your app&#39;s requests means nothing while the backend sets one. That&#39;s handy when you move provider (Scenario 4 answered a request for gpt-4o-mini with Gemini), but don&#39;t expect a typo in a model name to fail. If you want the client to choose, leave model unset on the backend.</p><h3>Running without Kubernetes</h3><p>Everything above uses agentgateway’s Kubernetes objects. agentgateway also runs <strong>standalone</strong>: a single process configured by a local YAML file, no cluster involved. The same idea (one OpenAI-shaped entry point, several providers behind it) works there too. This post didn’t test standalone mode; the <a href="https://agentgateway.dev/docs/standalone/latest/configuration/">standalone configuration docs</a> and the <a href="https://agentgateway.dev/docs/standalone/latest/llm/providers/gemini/">Gemini provider page</a> are the place to start.</p><h3>Wrap-up</h3><p>You started with an app that knew OpenAI’s SDK, OpenAI’s key and OpenAI’s address. You now have an app that knows one address and no keys, and a gateway that answered it from a mock, from OpenAI, from Gemini and from Anthropic. Moving between them was a kubectl apply on the gateway. The app never changed.</p><p>The pieces, once, in plain terms: the <strong>HTTPRoute</strong> gives your apps one stable address; the <strong>AgentgatewayBackend</strong> decides which provider answers; <strong>policies.auth.secretRef</strong> keeps each provider&#39;s key in a Secret, in one place; and the gateway <strong>translates</strong> each request into the provider&#39;s own API, then translates the answer back. Scenario 3 let you watch it happen.</p><p>Your app no longer has to know which provider it’s talking to. Once that line is in place, failover, routing, cost tracking and guardrails become gateway config instead of app code. Later posts in this series build each of those on top of this same backend, starting with failover.</p><h3>Tear down</h3><p>Delete the whole cluster in one command. It takes the gateway, the backends and every Secret with it:</p><pre>kind delete cluster --name agentgateway-multi-provider</pre><p>Your keys only lived in that cluster’s Secrets and in your shell. If you exported them in your terminal, clear them too:</p><pre>unset OPENAI_API_KEY GEMINI_API_KEY ANTHROPIC_API_KEY</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44528b1271ef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Who’s Burning Your Tokens?]]></title>
            <link>https://medium.com/@fjvicens/whos-burning-your-tokens-8e4284789b89?source=rss-a4abbe6cb818------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e4284789b89</guid>
            <category><![CDATA[observability]]></category>
            <category><![CDATA[ai-infrastructure]]></category>
            <category><![CDATA[llmops]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[agentgateway]]></category>
            <dc:creator><![CDATA[Felipe Vicens]]></dc:creator>
            <pubDate>Sun, 30 Aug 2026 19:13:25 GMT</pubDate>
            <atom:updated>2026-08-30T19:13:25.568Z</atom:updated>
            <content:encoded><![CDATA[<h3>Who’s Burning Your Tokens? Observability for AgentGateway with Prometheus, OpenTelemetry, and Grafana</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ONdhwRziFVmIbUTTncpuCA.png" /><figcaption>Four teammates sharing one GPU-backed model. Without attribution, nobody can tell whose traffic is driving the load.</figcaption></figure><p>Your GPU sits at 100%. Three teams share the same model. Latency creeps up, someone opens an incident, and the first question is <em>who’s actually driving this load?</em> Nobody can answer it. Everyone has a theory. Nobody has a number.</p><p>Authentication tells you <em>who’s allowed</em> to call the model. It says nothing about who’s actually calling it, how often, or how many tokens each call burns. That gap is invisible right up until the moment it costs you a GPU you don’t have.</p><p><a href="https://medium.com/@fjvicens/give-your-team-their-own-api-keys-to-a-shared-local-ai-model-with-agentgateway-dd1848fc3eec">Post 1</a> closed the <em>who’s allowed</em> half: every teammate got their own key, every request got attributed to a person, and every person got a token budget. This post closes the other half: actually <strong>seeing</strong> consumption. AgentGateway already emits a Prometheus metric with per-model token counts, no configuration required. We’ll stand up a real metrics pipeline (OpenTelemetry Collector → Prometheus → Grafana), attach team and user_id as custom labels using the same CEL trick post 1 used for rate limits, and end with <strong>two</strong> Grafana dashboards: the gateway&#39;s own operational dashboard, kept as the stock upstream one (health, requests, latency, runtime) for whoever runs the gateway, and a separate, purpose-built <strong>team token-usage dashboard</strong> that answers the question this post is named after: <strong>who&#39;s burning your tokens, by model, by team, and by API key.</strong></p><p>Same way as post 1: every number, log line, and query result below was captured from a real, live cluster, not copied from documentation.</p><blockquote><em>📦 </em><strong><em>Companion repo.</em></strong><em> Every manifest in this post is in </em><a href="https://github.com/felipevicens/aaif-labs/tree/main/agentgateway/observability/manifests"><em>felipevicens/aaif-labs</em></a><em>, apply them as you read.</em></blockquote><blockquote><strong><em>Version bump.</em></strong><em> Post 1 ran AgentGateway </em><em>v1.4.0-alpha.1. This post uses </em><strong><em>v1.5.0</em></strong><em> (the current stable release, bumped up from the </em><em>v1.4.1 this post originally shipped with, re-verified against a live cluster). If you&#39;re still on an older version from post 1, upgrade your Helm install first: the manifests below assume </em><em>1.5.0.</em></blockquote><blockquote><strong><em>What </em></strong><strong><em>v1.5.0 changes for this post: nothing you&#39;ll notice, with one exception worth knowing about.</em></strong><em> The CRD shape (</em><em>AgentgatewayPolicy, </em><em>frontend.metrics), the metric name, and every label discussed below are unchanged, re-tested end to end with byte-for-byte identical results. The one real breaking change in </em><em>v1.5.0 is </em><strong><em>LLM token count normalization</em></strong><em>: token metrics now fold in prompt-cache tokens (</em><em>llm.inputTokens includes cache-read/cache-creation tokens; the original provider-reported values move to new </em><em>llm.providerInputTokens/</em><em>llm.providerTotalTokens fields). This affects Anthropic- and Bedrock-backed setups that use prompt caching. It does </em><strong><em>not</em></strong><em> change anything here, since this post&#39;s self-hosted vLLM/OpenAI backend has no concept of prompt caching to begin with.</em></blockquote><h3>The mental model (read this before the YAML)</h3><p>Three new concepts on top of post 1’s gateway/virtual-key/budget vocabulary:</p><ul><li><strong>A metric</strong> is a number AgentGateway counts and exposes over HTTP in Prometheus’s text format. The one we care about, agentgateway_gen_ai_client_token_usage, is already there, on every install, with zero configuration. You don&#39;t turn it on; you just have to go look.</li><li><strong>A label</strong> is a dimension you can group a metric by, like a column you can GROUP BY in SQL. Some labels come free (which <em>model</em> answered a request); others, like <em>which team</em> or <em>which API key</em>, need you to tell the gateway where to find that information, which is what Scenario 3 is for.</li><li><strong>The OpenTelemetry (OTel) Collector</strong> sits between AgentGateway and Prometheus. Instead of Prometheus reaching out and scraping every gateway pod itself (the classic “pull” model), the Collector scrapes AgentGateway and then <em>pushes</em> (“remote-writes”) the data into Prometheus. This matters specifically because the token-usage metric is a <strong>histogram</strong>: pushing preserves it as a true, mergeable histogram (“native histogram”) instead of flattening it the way a naive scrape setup can. It also gives us a place to plug in Loki and Tempo later without redoing any of this.</li></ul><p>The pipeline this post builds: AgentGateway emits the metric, the OTel Collector relays it, Prometheus stores it, and Grafana turns it into dashboards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHhEAbEGT0OYwGz0FUiwCw.png" /><figcaption>The pipeline this post builds: AgentGateway emits the metric, the OTel Collector relays it, Prometheus stores it, and Grafana turns it into dashboards.</figcaption></figure><pre>AgentGateway ──(scrape :15020/metrics)──►  OTel Collector  ──(remote-write)──►  Prometheus   ──►  Grafana<br>(emits token-usage                         (adds nothing,                       (stores it,        (dashboards:<br> histogram per model,                       just relays +                        serves queries)    tokens by<br> for free)                                  fixes one quirk)                                        model/team/key)</pre><h3>Prerequisites</h3><ul><li>Everything from post 1: a kubectl/helm-capable machine, and an OpenAI-compatible model endpoint (this post reuses the same self-hosted vLLM serving gpt-oss-120b).</li><li>This post is <strong>self-contained</strong>: it doesn’t require post 1’s cluster to still exist, since post 1 ends with kind delete cluster. The setup below recreates the minimum from post 1; see post 1 for the full explanation of each piece.</li></ul><h3>Setup: recap post 1, on v1.5.0</h3><pre>kind create cluster --name agentgateway-observability</pre><pre>kubectl apply --server-side -f \<br>  https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.6.0/experimental-install.yaml<br>helm upgrade -i --create-namespace -n agentgateway-system \<br>  --version 1.5.0 agentgateway-crds \<br>  oci://cr.agentgateway.dev/charts/agentgateway-crds<br>helm upgrade -i -n agentgateway-system agentgateway \<br>  oci://cr.agentgateway.dev/charts/agentgateway \<br>  --version 1.5.0 \<br>  --set controller.image.pullPolicy=Always \<br>  --set controller.extraEnv.KGW_ENABLE_GATEWAY_API_EXPERIMENTAL_FEATURES=true</pre><p>Wire the Gateway / AgentgatewayBackend / HTTPRoute trio to your backend (identical to post 1&#39;s 01-gateway-backend-route.yaml, reproduced here so this post doesn&#39;t require post 1 open in another tab). Point the three env vars at your own model first, then apply. The cat &lt;&lt;EOF | kubectl apply -f - pattern expands the variables straight into the YAML as it&#39;s applied, so nothing below is hard-coded:</p><pre>export LLM_MODEL=&quot;gpt-oss-120b&quot;   # the model name your server advertises<br>export LLM_HOST=&quot;localhost&quot;       # your vLLM host, no http:// prefix<br>export LLM_PORT=&quot;8000&quot;            # your vLLM port<br></pre><pre>cat &lt;&lt;EOF | kubectl apply -f -<br># The front door: a Gateway listening on port 8080.<br>apiVersion: gateway.networking.k8s.io/v1<br>kind: Gateway<br>metadata:<br>  name: agentgateway-proxy<br>  namespace: agentgateway-system<br>spec:<br>  gatewayClassName: agentgateway<br>  listeners:<br>    - protocol: HTTP<br>      port: 8080<br>      name: http<br>      allowedRoutes:<br>        namespaces:<br>          from: All<br>---<br># The backend: WHERE the real model lives (and, if needed, how to log into it).<br>apiVersion: agentgateway.dev/v1alpha1<br>kind: AgentgatewayBackend<br>metadata:<br>  name: local-llm<br>  namespace: agentgateway-system<br>spec:<br>  ai:<br>    provider:<br>      openai:                           # &quot;openai&quot; here = OpenAI-compatible API shape<br>        model: &quot;${LLM_MODEL}&quot;<br>      host: ${LLM_HOST}                 # your vLLM host<br>      port: ${LLM_PORT}<br>---<br># The route: match incoming path /llm and forward it to the backend above.<br>apiVersion: gateway.networking.k8s.io/v1<br>kind: HTTPRoute<br>metadata:<br>  name: local-llm<br>  namespace: agentgateway-system<br>spec:<br>  parentRefs:<br>    - name: agentgateway-proxy<br>      namespace: agentgateway-system<br>  rules:<br>    - matches:<br>        - path:<br>            type: PathPrefix<br>            value: /llm                 # callers hit http://&lt;gateway&gt;:8080/llm<br>      filters:<br>        - type: URLRewrite<br>          urlRewrite:<br>            path:<br>              type: ReplaceFullPath<br>              replaceFullPath: /v1/chat/completions   # rewrite to the model&#39;s real path<br>      backendRefs:<br>        - name: local-llm<br>          namespace: agentgateway-system<br>          group: agentgateway.dev<br>          kind: AgentgatewayBackend<br>EOF</pre><p>Port-forward it, then confirm the control test still works:</p><pre>kubectl port-forward -n agentgateway-system svc/agentgateway-proxy 8080:8080</pre><pre>export LLM_MODEL=&quot;gpt-oss-120b&quot;<br>BODY=&quot;{\&quot;model\&quot;:\&quot;$LLM_MODEL\&quot;,\&quot;max_tokens\&quot;:20,\&quot;messages\&quot;:[{\&quot;role\&quot;:\&quot;user\&quot;,\&quot;content\&quot;:\&quot;Say OK\&quot;}]}&quot;<br>curl -X POST http://localhost:8080/llm -H &#39;Content-Type: application/json&#39; -d &quot;$BODY&quot;<br># → HTTP 200, {&quot;usage&quot;:{&quot;prompt_tokens&quot;:69,&quot;completion_tokens&quot;:20,&quot;total_tokens&quot;:89}, ...}</pre><p>Then reapply post 1’s virtual keys, but with one new field per person. This post’s Secret (01-api-keys-secret-with-team.yaml) adds team alongside user_id, since metadata was always free-form (post 1 said as much):</p><pre>cat &lt;&lt;EOF | kubectl apply -f -<br>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: llm-api-keys<br>  namespace: agentgateway-system<br>type: Opaque<br>stringData:<br>  alice: |<br>    { &quot;key&quot;: &quot;sk-alice-abc123def456&quot;, &quot;metadata&quot;: { &quot;user_id&quot;: &quot;alice&quot;, &quot;team&quot;: &quot;platform&quot; } }<br>  bob: |<br>    { &quot;key&quot;: &quot;sk-bob-xyz789uvw012&quot;, &quot;metadata&quot;: { &quot;user_id&quot;: &quot;bob&quot;, &quot;team&quot;: &quot;platform&quot; } }<br>  carol: |<br>    { &quot;key&quot;: &quot;sk-carol-newkey999&quot;, &quot;metadata&quot;: { &quot;user_id&quot;: &quot;carol&quot;, &quot;team&quot;: &quot;data-science&quot; } }<br>EOF</pre><p>Then apply post 1’s 03-apikey-auth-policy.yaml unchanged:</p><pre>cat &lt;&lt;EOF | kubectl apply -f -<br>apiVersion: agentgateway.dev/v1alpha1<br>kind: AgentgatewayPolicy<br>metadata:<br>  name: api-key-auth<br>  namespace: agentgateway-system<br>spec:<br>  targetRefs:<br>    - group: gateway.networking.k8s.io<br>      kind: Gateway<br>      name: agentgateway-proxy          # attach this rule to our front door<br>  traffic:<br>    apiKeyAuthentication:<br>      mode: Strict                       # no valid key =&gt; rejected<br>      secretRef:<br>        name: llm-api-keys               # check keys against the Secret above<br>EOF</pre><p>Confirm auth still works before moving on, same “test the yes and the no” way as post 1:</p><pre># alice, valid key -&gt; HTTP 200<br>curl -s -o /dev/null -w &quot;HTTP %{http_code}\n&quot; -X POST http://localhost:8080/llm \<br>  -H &#39;Content-Type: application/json&#39; -H &#39;Authorization: Bearer sk-alice-abc123def456&#39; -d &quot;$BODY&quot;<br># no key -&gt; HTTP 401<br>curl -s -o /dev/null -w &quot;HTTP %{http_code}\n&quot; -X POST http://localhost:8080/llm \<br>  -H &#39;Content-Type: application/json&#39; -d &quot;$BODY&quot;</pre><p>Both came back exactly as post 1 predicted: 200 and 401.</p><h3>Scenario 1: See the metrics AgentGateway already emits</h3><p>Before touching Prometheus or Grafana, look at what’s there. AgentGateway’s proxy pods carry prometheus.io/scrape: &quot;true&quot; and prometheus.io/port: &quot;15020&quot; annotations out of the box, confirmed straight from the running pod spec:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oOQsxzceI0jHJsUZPIPbLw.png" /><figcaption>The token-usage metric and its per-model labels are already there on every install, no configuration needed.</figcaption></figure><pre>kubectl get pod -n agentgateway-system -l gateway.networking.k8s.io/gateway-name=agentgateway-proxy \<br>  -o jsonpath=&#39;{.items[0].metadata.annotations.prometheus\.io/scrape} {.items[0].metadata.annotations.prometheus\.io/port}&#39;<br># true 15020</pre><p>Port-forward that port directly (leave this running in its own terminal, we reuse it again in Scenario 3), then curl it from a second terminal:</p><pre>kubectl port-forward -n agentgateway-system deployment/agentgateway-proxy 15020:15020</pre><pre>curl -s http://localhost:15020/metrics | grep gen_ai_client_token_usage</pre><p>Real output, after two successful chat calls:</p><pre># HELP agentgateway_gen_ai_client_token_usage Number of tokens used per request.<br># TYPE agentgateway_gen_ai_client_token_usage histogram<br>agentgateway_gen_ai_client_token_usage_sum{gen_ai_token_type=&quot;output&quot;,gen_ai_operation_name=&quot;chat&quot;,gen_ai_system=&quot;openai&quot;,gen_ai_request_model=&quot;gpt-oss-120b&quot;,gen_ai_response_model=&quot;gpt-oss-120b&quot;,...} 40.0<br>agentgateway_gen_ai_client_token_usage_count{gen_ai_token_type=&quot;output&quot;,...} 2<br>agentgateway_gen_ai_client_token_usage_sum{gen_ai_token_type=&quot;input&quot;,gen_ai_operation_name=&quot;chat&quot;,gen_ai_system=&quot;openai&quot;,gen_ai_request_model=&quot;gpt-oss-120b&quot;,gen_ai_response_model=&quot;gpt-oss-120b&quot;,...} 138.0</pre><p>That checks out: two calls with max_tokens=20 and prompt_tokens=69 each give output=40 (2×20) and input=138 (2×69). <strong>No configuration was needed for this.</strong> gen_ai_request_model, gen_ai_response_model, gen_ai_system, and gen_ai_token_type all come for free, per model, per provider, per direction, straight out of the box.</p><p>What’s <em>not</em> there yet: anything about <em>who</em> made the call. That’s user_id and team, and they don&#39;t exist as labels until Scenario 3. The full list of AgentGateway metrics worth knowing about, captured from the same scrape:</p><pre>agentgateway_gen_ai_client_token_usage       # the one we&#39;re building the dashboard around<br>agentgateway_gen_ai_server_request_duration  # latency of the LLM call itself<br>agentgateway_requests                        # HTTP requests, by route/status<br>agentgateway_cost_catalog_lookups            # dollar-cost lookups (needs a cost catalog configured, out of scope here)<br>agentgateway_request_duration_seconds        # end-to-end request latency<br>agentgateway_build_info                      # build/version info, comes back in &quot;Gotchas worth remembering&quot;</pre><h3>Scenario 2: Stand up the pipeline</h3><p>Deploy kube-prometheus-stack into a telemetry namespace with two settings that matter: enableRemoteWriteReceiver (so it can accept pushes instead of only pulling) and native histograms (so the token-usage histogram survives intact):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B_pC72wgVqJM15cixBY18A.png" /><figcaption>The OTel Collector scrapes AgentGateway and remote-writes into Prometheus, keeping the token-usage histogram intact as a native histogram.</figcaption></figure><pre>helm upgrade -i kube-prometheus-stack prometheus-community/kube-prometheus-stack \<br>  --version 88.0.1 --namespace telemetry --create-namespace \<br>  -f &quot;https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/observability/manifests/04-kube-prometheus-stack-values.yaml&quot; \<br>  --wait --timeout 5m</pre><pre># 04-kube-prometheus-stack-values.yaml (excerpt)<br>prometheus:<br>  prometheusSpec:<br>    enableRemoteWriteReceiver: true<br>    enableFeatures:<br>      - native-histograms</pre><p>Then a metrics-only OTel Collector that discovers AgentGateway pods via the same Prometheus annotations checked in Scenario 1, scrapes them, and remote-writes into Prometheus:</p><pre>helm upgrade -i otel-collector-metrics open-telemetry/opentelemetry-collector \<br>  --version 0.165.0 --namespace telemetry \<br>  -f &quot;https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/observability/manifests/03-otel-collector-metrics-values.yaml&quot; \<br>  --wait --timeout 3m</pre><p>Its startup log proves the scrape worked on the very first cycle, no polling required:</p><pre>info  Metrics  {&quot;otelcol.component.id&quot;: &quot;debug&quot;, &quot;otelcol.component.kind&quot;: &quot;exporter&quot;,<br>                 &quot;otelcol.signal&quot;: &quot;metrics&quot;, &quot;resource metrics&quot;: 1, &quot;metrics&quot;: 71, &quot;data points&quot;: 77}</pre><p>71 distinct metrics, 77 data points, one scrape after startup. Confirm they actually landed in Prometheus, not just in the Collector’s own logs. Port-forward it (leave this running in its own terminal too):</p><pre>kubectl port-forward -n telemetry svc/kube-prometheus-stack-prometheus 9090:9090</pre><pre>curl -s &#39;http://localhost:9090/api/v1/query&#39; --data-urlencode &#39;query=agentgateway_gen_ai_client_token_usage_sum&#39;</pre><p>Real result: the same series seen in Scenario 1, now living in Prometheus with Kubernetes resource attributes attached on top (k8s_pod_name, k8s_namespace_name, k8s_node_name, …), the Collector&#39;s resource_to_telemetry_conversion setting promoting pod metadata onto every metric automatically, no manual relabeling needed.</p><h3>Scenario 3: Attribute usage to people and teams</h3><p>Authentication (post 1) answers “who are you?” Metrics, so far, only answer “which model?” This scenario connects the two, with the exact same CEL pattern post 1 used to attach a token budget to a person, just pointed at metrics instead of rate limiting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gNUevd2204I3t0Dl3hvNdA.png" /><figcaption>Alice and Bob authenticate and roll up under team: platform; Carol rolls up under team: data-science.</figcaption></figure><pre># 02-per-user-team-metrics-policy.yaml<br>apiVersion: agentgateway.dev/v1alpha1<br>kind: AgentgatewayPolicy<br>metadata:<br>  name: per-user-team-metrics<br>  namespace: agentgateway-system<br>spec:<br>  targetRefs:<br>    - group: gateway.networking.k8s.io<br>      kind: Gateway<br>      name: agentgateway-proxy<br>  frontend:<br>    metrics:<br>      attributes:<br>        add:<br>          - name: user_id<br>            expression: &#39;apiKey.user_id&#39;<br>          - name: team<br>            expression: &#39;apiKey.team&#39;</pre><p>Apply it straight from the companion repo, kubectl apply -f takes a URL just as happily as a local path:</p><pre>kubectl apply -f &quot;https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/observability/manifests/02-per-user-team-metrics-policy.yaml&quot;</pre><p>Applied instantly and accepted:</p><pre>$ kubectl get agentgatewaypolicy -n agentgateway-system<br>NAME                    ACCEPTED   ATTACHED   AGE<br>api-key-auth            True       True       6m3s<br>per-user-team-metrics   True       True       2s</pre><p>Drive traffic as each teammate, then check the raw metrics endpoint:</p><pre>for kv in &quot;sk-alice-abc123def456:alice&quot; &quot;sk-bob-xyz789uvw012:bob&quot; &quot;sk-carol-newkey999:carol&quot;; do<br>  key=&quot;${kv%%:*}&quot;<br>  curl -s -o /dev/null -X POST http://localhost:8080/llm -H &#39;Content-Type: application/json&#39; \<br>    -H &quot;Authorization: Bearer $key&quot; -d &quot;$BODY&quot;<br>done</pre><pre>curl -s http://localhost:15020/metrics | grep gen_ai_client_token_usage_sum \<br>  | grep -o &#39;user_id=&quot;[^&quot;]*&quot;,team=&quot;[^&quot;]*&quot;&#39; | sort -u</pre><pre>user_id=&quot;alice&quot;,team=&quot;platform&quot;<br>user_id=&quot;bob&quot;,team=&quot;platform&quot;<br>user_id=&quot;carol&quot;,team=&quot;data-science&quot;</pre><p>Alice and Bob roll up under platform; Carol rolls up under data-science. This is the payoff: team is the exact same free-form metadata field post 1 suggested you could add, now feeding both a label <em>and</em> (unchanged from post 1) a rate-limit budget if you want one.</p><p><strong>If you use JWTs instead of API keys</strong> (post 1, Scenario 3), the same policy shape works unchanged: swap apiKey.user_id / apiKey.team for jwt.claims.user_id / jwt.claims.team. The JWT&#39;s decoded claims are exposed to CEL the same way apiKey.* is.</p><p><strong>Gotcha, confirmed live, and worth testing yourself before you trust a dashboard:</strong> requests made <em>before</em> this policy existed keep reporting on a separate, label-less time series forever. They don’t retroactively gain user_id/team. A histogram&#39;s label set is fixed per series; adding a label starts a <em>new</em> series, it doesn&#39;t rewrite history.</p><p>Running sum by (team) (...) right after applying the policy shows exactly this: a {} (no-team) group alongside the new platform / data-science groups. If your dashboard numbers look like they&#39;re missing history right after turning this on, that&#39;s why: it&#39;s not a bug, just how label cardinality works in Prometheus.</p><p><strong>Second gotcha, straight from the docs and worth internalizing before you scale past a handful of people:</strong> user_id is a <strong>high-cardinality</strong> label: every unique person creates a new time series, which costs Prometheus memory and storage. Fine for tens or hundreds of keys (our three teammates, obviously, are nowhere near that).</p><p>At real scale, prefer grouping by team or tier for your default dashboard view, and reserve per-user_id breakdowns for drill-downs, not the top-level panel.</p><h3>Scenario 4: Build the Grafana dashboards</h3><p>Two audiences, two questions, so <strong>two dashboards</strong>, not one crowded page. Whoever runs the gateway wants health, request rate, latency, and runtime; a team lead or FinOps wants <em>who spent what</em>. Cramming both into one dashboard makes each reader scroll past the other’s panels, and the two even want different filters (the operational panels filter by $gateway/$pod; the token panels filter by $team/$model/$user_id). So we keep them apart:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l_AOkqrlBtBR2ItcwvHKnQ.png" /><figcaption>Two dashboards for two audiences: the operational view for whoever runs the gateway, and the team token-usage view for FinOps and team leads.</figcaption></figure><p><strong>1. The operational dashboard, keep the stock upstream one, minus two panels.</strong> Don’t rebuild what AgentGateway already ships. This post’s copy, 05-agentgateway-operational-dashboard.json (uid agentgateway), is the dashboard AgentGateway itself publishes (health, requests, latency, XDS, Tokio runtime, plus a per-model LLM <em>performance</em> row: TTFT, request time, tokens/sec), with the two <em>token/cost</em> panels lifted out, since those belong with the team view below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NdDeJjXFlHCpMDZZhWgpKg.png" /><figcaption>Overview and Requests rows, driven by the same traffic this post has been sending all along.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*APH3VpAmGbSJCNNfKQlHLg.png" /><figcaption>The LLM row, including Time To First Token and Tokens Per Second, both empty until traffic is sent with stream: true (see Gotchas and the traffic generator below).</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CikAERJUEYvkHy5hLC-5GQ.png" /><figcaption>XDS and Runtime rows, unmodified from the stock dashboard AgentGateway publishes.</figcaption></figure><p><strong>2. The team token-usage dashboard, a separate, purpose-built page.</strong> This is 06-token-usage-dashboard.json (uid agentgateway-token-usage), the one that answers &quot;who&#39;s burning your tokens.&quot; It is designed top-down for that question rather than being a row bolted onto the operational dashboard:</p><ul><li><strong>Headline stats</strong> (range totals): total tokens, <strong>input tokens</strong>, <strong>output tokens</strong> (input/output split out because on local models output tokens drive most of the GPU time), total requests, and avg tokens/request for the window.</li><li><strong>A ranking row</strong>, the money view: <em>Top Teams</em>, <em>Top API Keys</em>, and <em>Top Models</em> as horizontal <strong>bar gauges</strong> (topk(10, …)), plus a <strong>Top consumers table</strong> breaking down every team × API key × model combination, sortable by tokens. A bar gauge answers &quot;who&#39;s biggest&quot; at a glance far better than a time series does.</li><li><strong>Trend row</strong>, the same attribution as <strong>stacked bars</strong> over time (including an input-vs-output panel), so bar height is honest per-bucket consumption, with a <strong>fixed colour per team/model across every panel</strong> so platform is always the same blue and output tokens are always the same orange.</li></ul><p>There’s deliberately <strong>no dollar-cost panel</strong>: this setup targets self-hosted local models, where the meaningful budget is tokens and GPU time, not a per-token API bill.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sNRPAC5GKNWdsyooV-4knQ.png" /><figcaption>Headline stats and the ranking row: platform leads at 8K tokens, alice leads individually at 5K.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*diO1bLHcf3ohUyt3iBVMxQ.png" /><figcaption>The trend row: real bars at the buckets traffic actually landed in, not a smooth fake line.</figcaption></figure><p>The core attribution queries the table view and rankings are built from (each also honouring the $team/$model/$user_id filters) are:</p><ul><li><strong>Tokens by Model:</strong> sum by (gen_ai_request_model, gen_ai_token_type) (increase(agentgateway_gen_ai_client_token_usage_sum{namespace=~&quot;$namespace&quot;}[$__interval]))</li><li><strong>Tokens by Team:</strong> sum by (team) (increase(agentgateway_gen_ai_client_token_usage_sum{namespace=~&quot;$namespace&quot;, team!=&quot;&quot;}[$__interval]))</li><li><strong>Tokens by API Key (user_id):</strong> sum by (user_id) (increase(agentgateway_gen_ai_client_token_usage_sum{namespace=~&quot;$namespace&quot;, user_id!=&quot;&quot;}[$__interval]))</li><li><strong>Input vs Output Tokens:</strong> sum by (gen_ai_token_type) (increase(agentgateway_gen_ai_client_token_usage_sum{namespace=~&quot;$namespace&quot;}[$__interval]))</li></ul><p>Bars over [$__interval] (Grafana&#39;s actual per-pixel-column bucket width), not lines over [$__range]. The panels started out as lines and were actively misleading; see &quot;Gotchas worth remembering&quot; below for why.</p><p>--from-file needs real files on disk (it can&#39;t read a URL directly), so pull both dashboards down right before importing them, then bundle them into one ConfigMap labeled grafana_dashboard: &quot;1&quot;, which kube-prometheus-stack&#39;s Grafana sidecar auto-loads with no restart:</p><pre>curl -sL -O &quot;https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/observability/manifests/05-agentgateway-operational-dashboard.json&quot; \<br>     -O &quot;https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/observability/manifests/06-token-usage-dashboard.json&quot;</pre><pre>kubectl create configmap agentgateway-dashboards -n telemetry \<br>  --from-file=agentgateway-operational.json=05-agentgateway-operational-dashboard.json \<br>  --from-file=token-usage.json=06-token-usage-dashboard.json \<br>  --dry-run=client -o yaml | kubectl label -f - --local -o yaml grafana_dashboard=1 \<br>  | kubectl apply -f -</pre><p>The sidecar’s own log confirms the reload, no polling needed:</p><pre>INFO  Writing /tmp/dashboards/agentgateway-operational.json (ascii)<br>INFO  Writing /tmp/dashboards/token-usage.json (ascii)<br>INFO  None sent to http://localhost:3000/api/admin/provisioning/dashboards/reload. Response: 200 OK {&quot;message&quot;:&quot;Dashboards config reloaded&quot;}</pre><p>Open Grafana itself to actually see them. Port-forward the service (leave this running in its own terminal), then log in with the demo credentials this post’s values file sets, admin / admin, never do this on anything but a throwaway cluster:</p><pre>kubectl port-forward -n telemetry svc/kube-prometheus-stack-grafana 3000:80</pre><p>Open http://localhost:3000 in a browser and go to <strong>Dashboards</strong> in the left nav. Both show up already imported, no manual click-through required: the operational one (uid agentgateway) and the team token-usage one (uid agentgateway-token-usage), the sidecar picked up both the moment the ConfigMap landed.</p><p>Driving a few more requests as alice (twice), bob, and carol, then querying the same four panel expressions directly against Prometheus, confirms real, distinguishable numbers, not just four empty panels:</p><pre>Tokens by Team:    platform ≈ 267   data-science ≈ 89<br>Tokens by API Key: alice ≈ 178      bob ≈ 89      carol ≈ 89</pre><p>Alice’s number is roughly double Bob’s and Carol’s, exactly matching her having made two calls to their one. The dashboard is measuring what actually happened, not just rendering a static mock.</p><h3>Generate more traffic to explore the dashboards yourself</h3><p>A handful of manual curls is enough to prove the pipeline works, but not enough to make a dashboard interesting to look at: every panel above is built from just a few requests. If you want the ranking and trend panels to show something closer to real usage, drive more traffic as alice, bob, and carol in the same 2:1:1 ratio this post used, straight from the companion repo, no local file needed:</p><pre>curl -sL &quot;https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/observability/manifests/generate-traffic.sh&quot; | bash</pre><p>One pass sends 4 calls as alice, 2 as bob, and 2 as carol. To spread traffic across several time buckets instead of one burst, useful for the trend row’s stacked bars, run multiple rounds with a pause between them:</p><pre>curl -sL &quot;https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/observability/manifests/generate-traffic.sh&quot; \<br>  | ROUNDS=6 SLEEP=15 bash</pre><p>Every setting (ALICE_CALLS, BOB_CALLS, CAROL_CALLS, GATEWAY_URL, LLM_MODEL, ROUNDS, SLEEP) is an environment variable with a sane default, so this only touches what you override. It assumes the same prerequisites as the rest of this post: the gateway port-forwarded to localhost:8080 (Setup) and alice/bob/carol&#39;s keys already applied (Scenario 3).</p><h3>Every Prometheus metric this post touches</h3><p>One table, so you don’t have to hunt back through six scenarios to find where a metric came from or what it means. All types confirmed straight from /metrics on a live v1.5.0 gateway:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F5NomZdJmTBPcKGcVh93CQ.png" /><figcaption>Metric-by-metric reference</figcaption></figure><p>Every histogram in that table ships as three series per label set, _sum, _count, and _bucket{le=&quot;...&quot;}, exactly what Scenario 1&#39;s raw curl output already showed for the token-usage metric. None of this needed custom instrumentation: all eight come from AgentGateway itself, on every install, whether or not you ever wire up the rest of this post.</p><h3>Gotchas worth remembering</h3><p>Every one of these was confirmed against a live v1.5.0 cluster:</p><h4><strong>Not every panel will show data, and that’s expected, not broken.</strong></h4><p>After driving traffic through, every Memory/CPU/Requests/Latency/XDS/Runtime panel (operational dashboard) and every token-attribution panel (team dashboard) had real numbers, checked one by one against Prometheus. A few stayed empty for reasons that have nothing to do with the pipeline: MCP Calls / Tool Calls (this post never makes an MCP call), and Time To First Token / Tokens Per Second (both need <em>streaming</em> responses; our test calls are plain, non-streaming chat/completions), both on the operational dashboard, so don&#39;t go debugging a pipeline problem that isn&#39;t there. Cross-check an empty panel&#39;s underlying query before assuming your setup is broken.</p><p><strong>The OTel Collector’s Prometheus receiver silently strips </strong><strong>_info suffixes, and it broke every panel on both dashboards, not just the new one.</strong></p><p>agentgateway_build_info feeds the $namespace dashboard variable; the receiver strips the _info suffix during scraping, the variable resolves to nothing, and every {namespace=~&quot;$namespace&quot;} filter matches nothing. A totally silent failure, no error anywhere. Fix: restore the suffix with a transform processor before the data leaves the Collector:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cs4ts3TAcw4gwEty68I5Rw.png" /><figcaption><em>Before: the OTel Collector strips the </em><em>_info suffix and the </em><em>$namespace variable resolves to nothing. After: a transform processor restores it and the dashboard populates again.</em></figcaption></figure><pre>processors:<br>  transform/info-suffix:<br>    metric_statements:<br>      - context: metric<br>        statements:<br>          - set(metric.name, Concat([metric.name, &quot;info&quot;], &quot;_&quot;)) where metric.metadata[&quot;prometheus.type&quot;] == &quot;info&quot;</pre><p>Add this processor to any OTel Collector pipeline scraping AgentGateway (or anything else emitting OpenMetrics “info” metrics), and if a dashboard is unexpectedly blank, check for this first.</p><h4><strong>A hand-rolled scrape config only carries the labels you explicitly relabel.</strong></h4><p>The Requests/LLM/MCP rows depend on a $gateway variable built from a Gateway API pod label (gateway.networking.k8s.io/gateway-name), a label a stock ServiceMonitor scrape carries automatically, but a hand-rolled one won&#39;t unless you add it:</p><pre>- source_labels: [__meta_kubernetes_pod_label_gateway_networking_k8s_io_gateway_name]   <br>  target_label: gateway_networking_k8s_io_gateway_name <br>- source_labels: [__meta_kubernetes_pod_label_gateway_networking_k8s_io_gateway_class_name]   <br>  target_label: gateway_networking_k8s_io_gateway_class_name</pre><p>So when a dashboard is blank, check every template variable it uses against what your own scrape config actually promotes.</p><h4><strong>Adding a metric label doesn’t relabel history.</strong></h4><p>Requests made before a frontend.metrics policy existed stay in their own label-less series forever, so apply attribution policies early and don&#39;t be surprised by a {} group in your aggregations.</p><h4><strong>rate()/</strong><strong>increase(...[$__range]) smear bursty traffic into what looks like continuous consumption.</strong></h4><p>A burst that took one real second reads as “still consuming” for a full 5-minute window on a rate() panel, because rate() averages over its entire window, a smooth line does not mean constant spend. Fix: for token-attribution panels, use increase(...[$__interval]) (Grafana&#39;s real per-bucket width), rendered as <strong>bars, not a line</strong>, so each bar means exactly &quot;tokens used in this bucket&quot;:</p><pre># sum by (team) (increase(...[60s])), 60s buckets <br>...  0   0   0   0   0   106.97   &lt;- exactly the bucket the burst landed in</pre><p>If a bucketed panel ever looks suspicious, drop into Grafana’s Explore and plot the raw counter (no rate()/increase()) as ground truth. The one exception is an <strong>instant</strong> query (like this dashboard&#39;s Headline stat row): [$__range] is safe there, since it computes one true total instead of a sliding line.</p><h4><strong><em>The trend row went blank at a 30-minute range but showed data at a wider one, confirmed live, and it wasn’t the pipeline.</em></strong></h4><p>Each trend panel had a “Min step” (the JSON’s interval field) hard-set to 5s, well below the ~15s cadence the OTel Collector actually scrapes and remote-writes at. At a short range, Grafana&#39;s auto-computed step is small too, and 5s was low enough to win as the floor. Querying increase(...[5s]) against a metric that only gets a new sample every ~15s means most 5-second windows contain zero samples, so the panel renders empty, not because the data isn&#39;t there, but because the step is finer than the data&#39;s own resolution. Confirmed by running the exact same query with a 5s window (0 series) and a 30s window (real, non-zero values) against the same live range. Widen the time range and the auto-computed step eventually grows past the floor, which is why &quot;just zoom out&quot; made it work. Fix: set each trend panel&#39;s Min step to at least the real scrape interval, ideally 2 to 4x it, here 30s against a 15s scrape.</p><p>If a panel is empty at a short range but fine at a longer one, suspect the Min step before the pipeline, and never set it below your actual scrape/remote-write interval.</p><h4><strong>Multi-select template variables need </strong><strong>${var:pipe}, not the bare </strong><strong>$var.</strong></h4><p>With multi: true filters, Grafana&#39;s default interpolation renders two selected values as {ns-a,ns-b}, valid Grafana glob syntax, but not valid PromQL regex, so the panel silently returns no data the moment a reader picks more than one value. Fix: use the pipe format specifier on every =~ filter reading from a multi-select variable: namespace=~&quot;${namespace:pipe}&quot;.</p><h4><strong>user_id is high-cardinality; </strong><strong>team/</strong><strong>tier isn&#39;t.</strong></h4><p><em>What it means for you:</em> build your default dashboard around team, and treat user_id breakdowns as a drill-down, not the headline view, once you&#39;re past a handful of keys.</p><h4><strong>The token-usage histogram needs zero configuration to exist</strong></h4><p>but attribution (user_id/team) needs the frontend.metrics policy. Confirm it&#39;s ACCEPTED/ATTACHED the same way post 1 confirmed auth policies, don&#39;t assume.</p><h4><strong>Cost-in-dollars is a separate metric</strong></h4><p>(agentgateway_cost_catalog_lookups) that needs a cost catalog configured to produce real numbers; it showed up in the raw metric list but empty in this post&#39;s setup, since that&#39;s out of scope here.</p><h4><strong>v1.5.0&#39;s token-count-normalization breaking change doesn&#39;t touch this post&#39;s numbers, but it will touch yours if your backend is Anthropic or Bedrock with prompt caching turned on.</strong></h4><p>llm.inputTokens now includes cache-read/cache-creation tokens, feeding straight into agentgateway_gen_ai_client_token_usage and any token-based rate limit or CEL expression built on it. The original provider-reported numbers move to llm.providerInputTokens/llm.providerTotalTokens instead. <em>What it means for you:</em> if a token-attribution dashboard&#39;s numbers jump right after upgrading to v1.5.0 and your backend does prompt caching, that&#39;s this change, not a broken pipeline. Go check llm.providerInputTokens in access logs to see the pre-normalization number.</p><h3>Wrap-up</h3><p>Stack this post on top of Post 1 and here’s what you’re actually running: authenticated users, virtual API keys, per-person token budgets, per-user attribution, per-team attribution, and a production-ready observability pipeline (Prometheus, OpenTelemetry, and Grafana) that turns “who’s burning your tokens?” into a dashboard, not a guess. None of it needed custom code: a Helm install, one AgentgatewayPolicy, and a dashboard JSON.</p><p>You can still only answer “how much” and “who.” You can’t yet answer “what, exactly, did that request say” or “where did those 300ms go.” That’s what <strong>logs</strong> (Loki) and <strong>traces</strong> (Tempo) are for: following a single request end-to-end instead of aggregating across all of them, plus a proper <strong>dollar-cost</strong> dashboard on the cost-catalog metric this post only glanced at. All three build directly on the telemetry namespace and OTel Collector already running here. That&#39;s the next post.</p><p>All manifests used here are in the companion repo, <a href="https://github.com/felipevicens/aaif-labs/tree/main/agentgateway/observability/manifests">felipevicens/aaif-labs</a>, applied and torn down against a disposable kind cluster. Nothing in this post touched any shared infrastructure.</p><h3>Tear down</h3><pre>kind delete cluster --name agentgateway-observability</pre><p>Deleting a cluster removes the gateway, virtual keys, Prometheus, Grafana, and the OTel collector. The entire telemetry namespace is also removed, as it resided within the same cluster. There’s no need to clean up in stages.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e4284789b89" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How agentgateway Reached 1.08M+ req/s (And Why 320 CPU Threads Were Slower Than 32)]]></title>
            <link>https://medium.com/@fjvicens/how-agentgateway-reached-1-08m-req-s-and-why-320-cpu-threads-were-slower-than-32-6623154660be?source=rss-a4abbe6cb818------2</link>
            <guid isPermaLink="false">https://medium.com/p/6623154660be</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[computer-architecture]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Felipe Vicens]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 19:53:11 GMT</pubDate>
            <atom:updated>2026-08-18T19:55:29.084Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*13pCgOMjKcYZTnO2UJURog.png" /></figure><p>What started as a simple benchmark reproduction became a full-day deep dive into how CPUs actually work.</p><p>It started with <a href="https://agentgateway.dev/blog/2026-08-13-benchmarking-agentgateway-vs-litellm-rust-mode/">Lin Sun’s benchmark of agentgateway vs. LiteLLM</a>, which compares proxy overhead between the two gateways under load. The benchmark ran on a massive 320-thread AMD EPYC 9845 server, under the naive assumption that the default setup would simply scale out of the box. It didn’t. In fact, giving agentgateway access to more cores actually degraded performance, so running all 320 threads ended up being slower than using just 32.</p><p>Chasing down why turned into a real investigation into how modern CPUs are actually organized, why “more cores” is a trick question, and how far a single piece of software can go once the fight shifts from its code to its hardware. The climb ended at <strong>1,085,140 requests per second</strong>, up from a starting point of about 97,000.</p><p>This post tells the story of that climb: the decisions that mattered, explained simply enough that no systems-engineering background is needed to follow along.</p><blockquote><strong>TL;DR</strong></blockquote><blockquote>On the same 320-thread AMD EPYC 9845 server, giving agentgateway all 320 visible cores produced 104,292 requests per second, while giving it just 32 cores produced 125,405, more throughput from a tenth of the machine. Chasing that paradox through CPU cache domains, SMT, and horizontal replication eventually pushed throughput past a million: <strong>1,085,140 requests per second</strong>, using roughly 132 of the 320 available cores.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/963/1*AuxcXa0Q63rUUr0ZjTwllA.png" /></figure><h3>The setup</h3><p><a href="https://agentgateway.dev/">agentgateway</a> is a lightweight, Rust-based proxy for AI traffic. <a href="https://www.litellm.ai/">LiteLLM</a> is a popular Python-based alternative that does similar work. Both sit between an application and an LLM backend, forwarding requests and adding routing, auth, and observability along the way.</p><p>To measure <em>pure proxy overhead</em>, not model latency and not network variance, both benchmarks point the gateways at a mock backend that returns a fixed, instant response. The load comes from <a href="https://fortio.org/">fortio</a>, a load generator built for exactly this kind of testing. Requests carried a fixed 1,024-character JSON payload, roughly 1.1 KB, shaped like an OpenAI chat-completion body, sent over HTTP/1.1 with keep-alive enabled. Whatever throughput and latency shows up is the gateway’s own cost, nothing else.</p><p>The tests ran on an AMD EPYC 9845: 160 physical cores, 320 threads with simultaneous multithreading (SMT, more on that shortly), and over a terabyte of RAM. A genuinely huge machine, which is exactly what made the results interesting.</p><h3>The baseline</h3><p>With default settings and no tuning on either side, the gap was already large:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2b0z_Z3zT_vEVPg3UPsZng.png" /><figcaption>Default configuration, same host, same load. No tuning on either side yet.</figcaption></figure><p>agentgateway was already handling <strong>~20× more traffic</strong> than LiteLLM out of the box, with sub-millisecond latency where LiteLLM was in the double-digit milliseconds. The gap held at every percentile: agentgateway’s median response time was <strong>0.323 ms</strong> and its p99 was <strong>0.548 ms,</strong> against LiteLLM’s median of <strong>6.257 ms</strong> and p99 of <strong>19.667 ms</strong>. That’s the headline most benchmarks stop at.</p><p>This investigation didn’t. If agentgateway was already this fast on a fraction of the machine, the obvious next question was what happens when it gets to use the whole thing.</p><h3>Surprise #1: more CPU doesn’t mean more throughput</h3><p>The naive move is to just remove any limits and let the process see all 320 threads. That was tried, alongside smaller allocations, to see the shape of the curve:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pSpfj5910pagr-_QGYymgQ.png" /><figcaption>Same agentgateway instance, only the number of visible cores changes.</figcaption></figure><p>That’s not a typo. Giving agentgateway the <em>entire</em> machine produced <strong>less</strong> throughput than giving it a tenth of it. The expectation going in was that throughput would keep climbing as more CPU got handed over. Instead it peaked around 32 cores and fell from there, and that unexpected drop is what turned this from a benchmark rerun into an investigation. To understand why, there’s one thing worth knowing about how a program like agentgateway is built.</p><p>agentgateway is written in Rust on top of <a href="https://tokio.rs/">Tokio</a>, the standard async runtime for high-performance Rust services. By default, Tokio looks at how many CPUs the operating system says are available and spins up roughly one worker thread per core. That’s normally a sensible default, and it’s the right call for most workloads: more threads, more parallel work.</p><p>But this workload (proxying a JSON request to a backend and returning the response) simply doesn’t have 320 independent chunks of work to hand out. There’s a real ceiling on how much of it can run in parallel, somewhere around 30 cores’ worth of actual computation. Past that, extra threads aren’t doing useful work. They’re competing with each other for the CPU’s attention, getting scheduled on and off cores, and generally getting in each other’s way. The result is a coordination tax that grows with thread count, for work that isn’t growing at all. This isn’t a flaw in Tokio’s defaults; it’s just what happens when coordination overhead outpaces the work available to parallelize, which is a narrower band than most services ever hit.</p><p>The fix isn’t tuning a flag inside agentgateway. It doesn’t expose one. The fix is controlling what the operating system <em>tells it</em> is available. Which led to the next question: does it matter <em>which</em> cores it gets?</p><h3>How the chip is actually organized</h3><p>Actually, it’s organized in a complex way. Modern server CPUs aren’t a single, undifferentiated set of cores. They’re divided into groups, and each group shares its own fast local memory cache (called L3 cache). Cores inside the same group can hand data to each other almost instantly. Cores in <em>different</em> groups have to go further to fetch data from one another, and every handoff is slower.</p><p>The EPYC 9845 chip used here has ten of these groups (“cache domains”), 16 physical cores each. On top of that, every physical core is split into two hardware threads through simultaneous multithreading (SMT, sometimes called hyperthreading): two lightweight execution lanes sharing one core’s circuitry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3SG0PLAsvkVpgBWKkjYp7A.png" /><figcaption>Cores inside a domain share fast memory. Cores in different domains don’t.</figcaption></figure><p>Put together with the CPU quota, this is exactly what had gone wrong in the first pass. Letting the process spread its threads across <em>all ten</em> cache domains meant most <strong>inter-thread communication</strong> was making expensive cross-domain trips instead of cheap same-domain ones.</p><p>The numbers backed this up directly, using the same 32-core budget three different ways:</p><pre># Quota only, threads free to roam anywhere on the chip<br>docker run --cpus 32 agentgateway            # 125,405 qps<br><br># Pinned to one cache domain, using both SMT threads per core<br>docker run --cpuset-cpus 0-15,160-175 agentgateway   # 130,127 qps<br><br># Pinned to two full cache domains, physical cores only, no SMT<br>docker run --cpuset-cpus 0-31 agentgateway    # 134,828 qps</pre><p>Same 32 cores of budget, three placements, three different outcomes. Once agentgateway was pinned to a specific, contiguous set of cores, throughput went up <em>and</em> CPU usage went down at the same time. Confining the work to cores that actually share fast memory stopped the scheduler from scattering it across the chip, which had been pure waste.</p><p>The SMT threads told an equally interesting, if counter-intuitive, story. Giving <em>one</em> agentgateway process both threads of the same physical core barely helped. It was still one workload contending with itself for the same execution pipeline. But giving <em>two independent</em> agentgateway processes one SMT thread each, one per lane on the same core, worked well: each process had its own real work to fill the other’s idle moments with. SMT rewards independent work sharing hardware, not one process trying to use it twice.</p><p>That distinction, independent processes rather than one bigger process, turned out to be the real key to everything that followed.</p><h3>Replicate, don’t enlarge</h3><p>Once it became clear that a single agentgateway process has a real, fairly low ceiling on how many cores it can use <em>well</em>, the path forward stopped being “configure it better” and started being “run more of them.”</p><p>This is the same idea behind horizontally scaling any stateless service. Instead of one giant instance straining against its own internal limits, several small, independent instances run behind a load balancer, each doing an amount of work it’s actually good at. agentgateway keeps no state between requests, so nothing about it resists this. Each replica was pinned to its own cache domain, running side by side with the rest.</p><p>The scaling was close to linear. Four replicas, each confined to its own slice of cores, produced almost exactly four times the throughput of one, with no meaningful interference between them.</p><h3>The final push to 1,000,000</h3><p>Two more decisions closed the rest of the gap.</p><p><strong>Right-size each replica, don’t just multiply the same size.</strong> Each replica had initially been given a generous 32 cores, because that’s roughly where a <em>single</em> instance’s throughput peaked. But CPU monitoring showed something different: even at 32 cores, a replica was only ever <em>using</em> a fraction of them. Testing smaller allocations confirmed it. An 8-core replica, still confined to cores that share one cache domain, delivered almost the same throughput as a 32-core one, using well under half the CPU. The real ceiling per replica was never about how many cores it was given; it was about how much of this workload actually exists to parallelize. That meant twice as many replicas could fit into the same physical core budget: twenty 8-core replicas instead of ten 16-core ones, each pinned to its own contiguous slice (--cpuset-cpus 0-7 for the first, 8-15 for the second, and so on), so that every pair of neighboring replicas shared one 16-core cache domain without ever overlapping.</p><p><strong>Scale the backend too.</strong> Running twenty independent replicas instead of ten roughly doubles the number of simultaneous connections they generate. A single shared backend that easily handled ten replicas’ worth of traffic needed help at twenty, so two independent backend instances ran instead of one, splitting the replicas evenly between them. The same “replicate, don’t enlarge” logic that worked for the proxy applied just as well to what’s behind it.</p><p>Put together, here’s the full climb, on the exact same 320-thread machine the whole way through:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s5VzhHa48-gI6TStc83lVA.png" /><figcaption>Same 320-thread host throughout. Each step is a placement decision, not new hardware.</figcaption></figure><h3>The result</h3><p><strong>1,085,140 requests per second</strong>, zero timeouts. The winning configuration was rerun with full instrumentation to confirm it: twenty agentgateway replicas, eight cores each, evenly split across two independently-pinned backend instances. It measured cleanly at 1,083,257 qps on that repeat run, with zero failed requests across more than 32 million total, and a separate peak run touched 1,096,768. Total CPU usage across every container came out to roughly <strong>132 cores out of the 320 available</strong>, still well under half the machine. Latency held up under that load too: each replica’s median response time landed between 0.38 ms and 0.47 ms, with p99 no worse than 1.70 ms, across all twenty replicas and both backends. The full raw results, configuration, and scripts behind every number in this post are in the <a href="https://github.com/felipevicens/benchmark-agentgateway-on-amd-epyc">companion repository</a>.</p><p>That last number is the one worth sitting with. The million-requests-per-second mark wasn’t reached by using the whole machine. It came from using well under half of it, arranged in the right shape, repeated enough times.</p><p>The more interesting result here wasn’t that agentgateway is fast. It was that the limiting factor stopped being the software long before it stopped being the hardware.</p><h3>What this means for running agentgateway in production</h3><p>None of this requires the exact scale used here. The underlying lessons apply anywhere a compute-bound proxy runs on a modern multi-core machine:</p><ul><li><strong>Pin containers to real hardware boundaries</strong>, not just a CPU count. docker run --cpus 8 limits <em>how much</em> CPU time a process gets. --cpuset-cpus limits <em>which</em> cores it can use, and only the second one respects cache locality. On Kubernetes, the equivalent is CPU pinning via the static CPU manager policy plus topology-aware scheduling.</li><li><strong>Don’t hand one process an entire large machine</strong> and assume it’ll figure out the rest. Check what it’s actually using under load before assuming it needs more.</li><li><strong>Prefer several small, well-placed replicas over one large instance.</strong> It scales more predictably, fails more gracefully, and, as this benchmark found, is often simply faster in aggregate.</li><li><strong>Size each replica to its real compute ceiling, not to what “feels generous.”</strong> A replica that peaks at a third of its CPU allocation is wasting the other two-thirds: cores that could be running an entire extra replica instead.</li></ul><h3>Closing</h3><p>Full credit to Lin Sun for the <a href="https://agentgateway.dev/blog/2026-08-13-benchmarking-agentgateway-vs-litellm-rust-mode/">original benchmark</a> that started this. Reproducing it is what surfaced the question that led here.</p><p>It started at 97,000 requests per second, already a good story on its own. Turns out it was just the beginning.</p><p>The machine had a million requests per second in it all along. It just took the right shape to let them out.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6623154660be" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Give Your Team Their Own API Keys to a Shared Local AI Model (with AgentGateway)]]></title>
            <link>https://medium.com/@fjvicens/give-your-team-their-own-api-keys-to-a-shared-local-ai-model-with-agentgateway-dd1848fc3eec?source=rss-a4abbe6cb818------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd1848fc3eec</guid>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[ai-gateway]]></category>
            <category><![CDATA[agentic-ai-architecture]]></category>
            <dc:creator><![CDATA[Felipe Vicens]]></dc:creator>
            <pubDate>Sun, 26 Jul 2026 00:13:46 GMT</pubDate>
            <atom:updated>2026-07-26T00:13:46.905Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukhm6BQc0ws6S9GdZS-crg.jpeg" /></figure><p>Say you’ve got a capable AI model running on your own hardware. In this post it’s gpt-oss-120b, served by <a href="https://github.com/vllm-project/vllm"><strong><em>vLLM</em></strong></a> on a machine you control. It works, it&#39;s fast, and now the whole team wants to use it. So how do you actually share it?</p><p>The tempting answer is: just give everyone the model’s URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CQUFb91EUZvt2YLNbAu2hw.jpeg" /><figcaption><strong>Sharing a model endpoint may be easy, but it also means shared identity, shared limits, and shared risk.</strong></figcaption></figure><p>It’s one line in a chat message and everybody’s up and running in a minute. But that “solution” quietly creates four problems:</p><ul><li><strong>You have no idea who is using it.</strong> Every request looks identical. When the GPU is pegged at 100%, you can’t tell whose job to blame.</li><li><strong>One person can starve everyone else.</strong> Someone kicks off a batch job that fires thousands of requests, and the rest of the team grinds to a halt.</li><li><strong>You can’t cut anyone off.</strong> A contractor’s engagement ends, someone leaves the company, and the URL is still out there with no per-person “off switch.”</li><li><strong>There’s no security.</strong> The moment that URL leaks into a screenshot, a git commit, or a forwarded message, anyone on the network can use your model.</li></ul><p>The fix that solves all four at once is to stop sharing the model directly and instead put a <strong>gateway</strong> in front of it. Each teammate gets their <em>own</em> key. The gateway checks the key on every request, records who made it, enforces a per-person budget, and can revoke any single key without touching the others. Those per-person keys are what the AI-gateway world calls <strong>virtual keys</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wihelbmdnAEqPEFjXJAW_g.jpeg" /><figcaption><strong>An AI gateway turns a shared model into a managed service by adding authentication, attribution, and policy enforcement.</strong></figcaption></figure><p>This post builds exactly that, from scratch. And importantly, every result you’ll read below (HTTP 200, 401, 429, error messages, timings) was captured from a real request against a live gateway. It runs on <strong>AgentGateway open source</strong>, version <strong>v1.4.0-alpha.1</strong>, on a throwaway (kind) Kubernetes cluster you can delete when you&#39;re done.</p><blockquote><em>📦 </em><strong><em>Companion repo.</em></strong><em> Every manifest in this post is in </em><a href="https://github.com/felipevicens/aaif-labs/tree/main/agentgateway/virtual-keys/manifests"><em>felipevicens/aaif-labs</em></a><em> — apply them as you read.</em></blockquote><blockquote><strong><em>A note on “open source” vs. “Enterprise.”</em></strong><em> AgentGateway has an OSS project and a commercial Solo.io Enterprise distribution. They use </em>differently named<em> Kubernetes objects: OSS uses </em><em>AgentgatewayPolicy, Enterprise uses </em><em>EnterpriseAgentgatewayPolicy. Everything here is the OSS one. If you&#39;ve seen JWT-based per-user auth for AgentGateway elsewhere and assumed it was Enterprise-only, that was my assumption too, and it&#39;s wrong. We&#39;ll prove the OSS one does JWT further down.</em></blockquote><h3>The mental model (read this before the YAML)</h3><p>If you’re new to gateways or Kubernetes, a few ideas up front will make everything after this click into place.</p><p><strong>An LLM gateway is a receptionist in front of your model.</strong> Instead of callers talking to the model directly, they talk to the gateway. The gateway checks who is knocking, decides whether to let them in, keeps a tally of what they’ve used, and only then forwards the request to the real model. Same idea as a reverse proxy, if that term means anything to you; if it doesn’t, “receptionist” is close enough.</p><p><strong>Two completely different kinds of key show up here, and you shouldn’t mix them up.</strong> This is the single most common point of confusion, so let’s kill it now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GllwkVggPfuoQzn93tjp9A.jpeg" /><figcaption><strong>Each teammate authenticates with a personal virtual API key, while the gateway manages access to the shared model behind the scenes.</strong></figcaption></figure><ul><li>The <strong>virtual keys</strong> (sk-alice-…, sk-bob-…) are what your teammates hold. You mint one per person. They&#39;re meaningless strings on their own; they only mean something because the gateway has a list mapping each one to a person.</li><li>The <strong>gateway’s own upstream key</strong> is the single credential the gateway uses to talk to the model behind it (if the model needs one at all; our local vLLM doesn’t). Nobody on the team ever sees this. In this post the model is open on our network, so the gateway needs no upstream key, and we can keep 100% of our attention on the virtual keys.</li></ul><p><strong>A “token” is how LLMs measure work.</strong> Text going in and coming out is chopped into tokens (roughly ¾ of a word each). Providers bill per token, and your GPU time is spent per token, so when we set a per-person budget we’ll count it in <em>tokens</em>, not in number-of-requests. One person asking for a 4,000-token essay should cost more of their budget than someone asking a one-line question.</p><p><strong>And the Kubernetes words you’ll see</strong>, one line each:</p><ul><li><strong>Kubernetes:</strong> the system that runs everything below as small managed units.</li><li><strong>kind:</strong> “Kubernetes IN Docker,” a way to spin up a real-but-disposable cluster on your laptop in one command. Perfect for a tutorial; delete it after.</li><li><strong>Helm:</strong> a package installer for Kubernetes (think apt/brew but for cluster software). We use it to install AgentGateway.</li><li><strong>namespace:</strong> a folder-like grouping for related objects. Ours live in agentgateway-system and ratelimit.</li></ul><p>That’s the whole conceptual toolkit. Now let’s build it.</p><h3>Prerequisites</h3><ul><li>A Kubernetes cluster. We use an ephemeral <strong>kind</strong> cluster so you can throw it away afterward.</li><li>kubectl (the Kubernetes command-line tool) and helm installed.</li><li>An OpenAI-compatible model endpoint to route to. This post uses a self-hosted vLLM serving gpt-oss-120b. To use a hosted provider (OpenAI, Anthropic, Azure…) instead, you&#39;d point the backend at them and give the gateway its own upstream key. See the <a href="https://agentgateway.dev/docs/kubernetes/main/llm/api-keys/"><strong><em>api-keys docs</em></strong></a>. That upstream credential is a <em>separate</em> thing from the per-person virtual keys this post is about.</li></ul><h3>Setup</h3><h3>1. Install AgentGateway OSS</h3><pre># Create a disposable local cluster<br>kind create cluster --name agentgateway-virtual-keys<br><br># Install the Kubernetes Gateway API CRDs (the standard traffic-routing types)<br>kubectl apply --server-side -f \<br>  https://github.com/kubernetes-sigs/gateway-api/releases/download/v1.6.0/experimental-install.yaml<br><br># Install AgentGateway&#39;s own object types (CRDs), then the gateway itself<br>helm upgrade -i --create-namespace -n agentgateway-system \<br>  --version 1.4.0-alpha.1 agentgateway-crds \<br>  oci://cr.agentgateway.dev/charts/agentgateway-crds<br><br>helm upgrade -i -n agentgateway-system agentgateway \<br>  oci://cr.agentgateway.dev/charts/agentgateway \<br>  --version 1.4.0-alpha.1 \<br>  --set controller.image.pullPolicy=Always \<br>  --set controller.extraEnv.KGW_ENABLE_GATEWAY_API_EXPERIMENTAL_FEATURES=true</pre><p>Two terms in there worth a sentence:</p><ul><li>A <strong>CRD</strong> (Custom Resource Definition) teaches Kubernetes a brand-new type of object. Out of the box Kubernetes knows about Pods and Services; AgentGateway’s CRDs add types like AgentgatewayPolicy and AgentgatewayBackend that we&#39;ll create later. Installing the CRDs is just teaching the cluster the vocabulary.</li><li>That last flag, KGW_ENABLE_GATEWAY_API_EXPERIMENTAL_FEATURES=true, <strong>matters</strong>. The per-person token-budget feature (Scenario 2) rides on an experimental part of the Gateway API. Leave the flag off and the budget policy silently won&#39;t apply, with no obvious error to tell you why.</li></ul><p>Confirm the gateway’s “class” registered. This is Kubernetes acknowledging that AgentGateway is now a thing that can handle traffic:</p><pre>$ kubectl get gatewayclass<br>NAME           CONTROLLER                      ACCEPTED   AGE<br>agentgateway   agentgateway.dev/agentgateway   True       1s</pre><h3>2. Point the gateway at your model</h3><p>First, capture where your model lives in three environment variables. This is the only part you edit; everything below reuses them, so the rest is paste-as-is:</p><pre>export LLM_MODEL=&quot;gpt-oss-120b&quot;          # the model name your server advertises<br>export LLM_HOST=&quot;localhost&quot;              # your vLLM host, no http:// prefix<br>export LLM_PORT=&quot;8000&quot;                   # your vLLM port</pre><p>Now apply the three objects. Read the comments; this is the whole “traffic comes in here, goes to there” wiring. The cat &lt;&lt;EOF | kubectl apply -f - pattern expands the variables above into the YAML as it&#39;s applied, so nothing is hard-coded:</p><pre>cat &lt;&lt;EOF | kubectl apply -f -<br># The front door: a Gateway listening on port 8080.<br>apiVersion: gateway.networking.k8s.io/v1<br>kind: Gateway<br>metadata:<br>  name: agentgateway-proxy<br>  namespace: agentgateway-system<br>spec:<br>  gatewayClassName: agentgateway        # use the AgentGateway class from step 1<br>  listeners:<br>    - protocol: HTTP<br>      port: 8080<br>      name: http<br>      allowedRoutes:<br>        namespaces:<br>          from: All<br>---<br># The backend: WHERE the real model lives (and, if needed, how to log into it).<br>apiVersion: agentgateway.dev/v1alpha1<br>kind: AgentgatewayBackend<br>metadata:<br>  name: local-llm<br>  namespace: agentgateway-system<br>spec:<br>  ai:<br>    provider:<br>      openai:                           # &quot;openai&quot; here = OpenAI-compatible API shape<br>        model: &quot;${LLM_MODEL}&quot;<br>      host: ${LLM_HOST}                 # your vLLM host<br>      port: ${LLM_PORT}<br>---<br># The route: match incoming path /llm and forward it to the backend above.<br>apiVersion: gateway.networking.k8s.io/v1<br>kind: HTTPRoute<br>metadata:<br>  name: local-llm<br>  namespace: agentgateway-system<br>spec:<br>  parentRefs:<br>    - name: agentgateway-proxy<br>      namespace: agentgateway-system<br>  rules:<br>    - matches:<br>        - path:<br>            type: PathPrefix<br>            value: /llm                 # callers hit http://&lt;gateway&gt;:8080/llm<br>      filters:<br>        - type: URLRewrite<br>          urlRewrite:<br>            path:<br>              type: ReplaceFullPath<br>              replaceFullPath: /v1/chat/completions   # rewrite to the model&#39;s real path<br>      backendRefs:<br>        - name: local-llm<br>          namespace: agentgateway-system<br>          group: agentgateway.dev<br>          kind: AgentgatewayBackend<br>EOF</pre><p>In plain English: <strong>the </strong><strong>Gateway is the front door</strong>, <strong>the </strong><strong>AgentgatewayBackend says where the real model is</strong>, and <strong>the </strong><strong>HTTPRoute connects the two</strong>: &quot;anything arriving at /llm, rewrite the path to the model&#39;s real /v1/chat/completions and send it on.&quot; The path rewrite is a small convenience: callers get a clean /llm URL and don&#39;t need to know the model&#39;s internal path.</p><p><strong>Reach the gateway.</strong> The gateway is exposed as a LoadBalancer service. On a cloud cluster that gets an external IP; on a local kind cluster there&#39;s no load-balancer provider, so the service sits at EXTERNAL-IP: &lt;pending&gt; forever, which is expected, not a failure. The simplest way in (and what every curl below assumes) is to port-forward it to localhost:8080:</p><pre># leave this running in its own terminal<br>kubectl port-forward -n agentgateway-system svc/agentgateway-proxy 8080:8080</pre><p><strong>Control test. No authentication yet, so anyone can call it. This is the “before” picture we’re about to fix:</strong></p><pre># one reusable request body for every curl below (uses $LLM_MODEL from step 2)<br>BODY=&quot;{\&quot;model\&quot;:\&quot;$LLM_MODEL\&quot;,\&quot;max_tokens\&quot;:20,\&quot;messages\&quot;:[{\&quot;role\&quot;:\&quot;user\&quot;,\&quot;content\&quot;:\&quot;Say OK\&quot;}]}&quot;<br><br>curl -X POST http://localhost:8080/llm -H &#39;Content-Type: application/json&#39; -d &quot;$BODY&quot;<br># → HTTP 200<br># {&quot;model&quot;:&quot;...&quot;,&quot;usage&quot;:{&quot;prompt_tokens&quot;:69,&quot;completion_tokens&quot;:20,&quot;total_tokens&quot;:89}, ...}</pre><p>It works, and notice &quot;total_tokens&quot;:89; we&#39;ll use that number in a moment. Right now, though, this is exactly the insecure free-for-all from the intro: no key, no idea who called, no limits. Let&#39;s lock it down.</p><h3>Scenario 1: Give each teammate their own key</h3><p>First we tell the gateway who’s allowed in. In Kubernetes, sensitive strings live in a <strong>Secret</strong> (a built-in object for exactly this). We create one holding each person’s key alongside a bit of metadata about them:</p><pre>cat &lt;&lt;EOF | kubectl apply -f -<br>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: llm-api-keys<br>  namespace: agentgateway-system<br>type: Opaque<br>stringData:<br>  alice: |<br>    { &quot;key&quot;: &quot;sk-alice-abc123def456&quot;, &quot;metadata&quot;: { &quot;user_id&quot;: &quot;alice&quot; } }<br>  bob: |<br>    { &quot;key&quot;: &quot;sk-bob-xyz789uvw012&quot;, &quot;metadata&quot;: { &quot;user_id&quot;: &quot;bob&quot; } }<br>EOF</pre><p>The shape of each entry matters:</p><ul><li><strong>key</strong> is the actual string the teammate puts in their Authorization header. This is their virtual key. (Use long random strings in real life; openssl rand -hex 24 is a fine generator. These short ones are just readable for the tutorial.)</li><li><strong>metadata</strong> is a free-form bag of facts about the key. Here it&#39;s just a user_id, but you could add team, tier, cost_center, anything. The gateway can read these later. That&#39;s how, in Scenario 2, a budget gets attached to a <em>person</em> rather than to a raw string.</li></ul><p>Now the <strong>policy</strong> that switches authentication on. A policy is a rule you attach to the gateway:</p><pre>cat &lt;&lt;EOF | kubectl apply -f -<br>apiVersion: agentgateway.dev/v1alpha1<br>kind: AgentgatewayPolicy<br>metadata:<br>  name: api-key-auth<br>  namespace: agentgateway-system<br>spec:<br>  targetRefs:<br>    - group: gateway.networking.k8s.io<br>      kind: Gateway<br>      name: agentgateway-proxy          # attach this rule to our front door<br>  traffic:<br>    apiKeyAuthentication:<br>      mode: Strict                       # no valid key =&gt; rejected<br>      secretRef:<br>        name: llm-api-keys               # check keys against the Secret above<br>EOF</pre><p>mode: Strict means exactly what it sounds like: a request with no valid key is turned away. (The other modes: Permissive checks a key if one is present but still lets keyless requests through, and Optional is looser still. Strict is what you want for real access control.)</p><p><strong>Now test both the “yes” and the “no.” Checking only the happy path is how you ship a door that doesn’t actually lock:</strong></p><pre># Alice&#39;s real key → HTTP 200<br>curl -X POST http://localhost:8080/llm -H &#39;Content-Type: application/json&#39; \<br>  -H &#39;Authorization: Bearer sk-alice-abc123def456&#39; -d &quot;$BODY&quot;<br><br># no key at all → HTTP 401  (api key authentication failure: no API Key found)<br>curl -X POST http://localhost:8080/llm -H &#39;Content-Type: application/json&#39; -d &quot;$BODY&quot;<br><br># made-up key → HTTP 401  (api key authentication failure: invalid credentials)<br>curl -X POST http://localhost:8080/llm -H &#39;Content-Type: application/json&#39; \<br>  -H &#39;Authorization: Bearer sk-not-a-real-key&#39; -d &quot;$BODY&quot;</pre><p>Alice’s real key gets a 200; no key and a made-up key both get 401 with a clear reason. That negative test isn&#39;t a formality. A policy that accidentally lets <em>everyone</em> through would still pass the first check. The only way to know your door locks is to try the handle when it should be locked.</p><h3>Scenario 2: Give each person a token budget</h3><p>Authentication answers “who are you?” Budgets answer “how much can you use?” The mechanism is <strong>rate limiting</strong>, and there are two flavors:</p><ul><li><strong>Local</strong> rate limiting is a counter kept <em>inside each copy</em> of the gateway. Simple, but if you run several gateway replicas they each count separately, so the real limit is multiplied by however many copies are running.</li><li><strong>Global</strong> rate limiting keeps <em>one shared counter</em> in an external service (backed by Redis here), so every gateway replica agrees on the running total. That’s what a real per-person budget needs, so that’s what we use.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6O4xy5GfnOBIeSPxNOe3UA.jpeg" /><figcaption><strong>Independent token budgets prevent one user’s workload from consuming resources intended for everyone else.</strong></figcaption></figure><p>Deploy the rate-limit service (this is the standard Envoy rate limiter). It’s a few objects together, a namespace, Redis, the limiter, and its config, so apply the full tested manifest straight from the companion repo:</p><pre>kubectl apply -f https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/virtual-keys/manifests/04-ratelimit-namespace.yaml</pre><p>The interesting part of that file is the ConfigMap, which declares the actual limits:</p><pre># excerpt of 04-ratelimit-namespace.yaml (applied above) — for reference<br>apiVersion: v1<br>kind: ConfigMap<br>metadata:<br>  name: ratelimit-config<br>  namespace: ratelimit<br>data:<br>  config.yaml: |<br>    domain: agentgateway<br>    descriptors:<br>      - key: user_id<br>        value: alice<br>        rate_limit: { unit: day, requests_per_unit: 100 }<br>      - key: user_id<br>        value: bob<br>        rate_limit: { unit: day, requests_per_unit: 100 }</pre><p>Read that as: “for user_id = alice, allow 100 per day; same for bob.&quot; The unit: day window and the number are yours to set per person or per tier.</p><p>Now extend the auth policy from Scenario 1 with a budget. The one line that makes this <em>per person</em> is the CEL expression:</p><pre># excerpt of 05-*: the budget block added under traffic: in the api-key-auth policy<br>rateLimit:<br>  global:<br>    domain: agentgateway              # must match the rate-limit config&#39;s domain<br>    backendRef:<br>      kind: Service<br>      name: ratelimit<br>      namespace: ratelimit<br>      port: 8081<br>    descriptors:<br>      - entries:<br>          - name: user_id<br>            expression: &quot;apiKey.user_id&quot;   # &lt;-- read user_id from the caller&#39;s key<br>         unit: Tokens</pre><p><strong>CEL</strong> (Common Expression Language) is a tiny, safe expression language Kubernetes tools use to pull values out of a request. apiKey.user_id reads the user_id field from the metadata of whichever key authenticated this request. So Alice&#39;s requests get counted against user_id=alice, Bob&#39;s against user_id=bob, automatically, from the key they presented. This is the payoff of putting metadata in the Secret earlier.</p><p>unit: Tokens is the LLM-aware bit: instead of charging 1 per request, the gateway charges the <em>token count of the response</em> against the budget. Recall each of our test calls used ~89 tokens. With a 100-token/day budget, that means the <strong>second</strong> call takes Alice over the line.</p><p>Apply the full policy. It keeps the same name (api-key-auth), so it <em>updates</em> the Scenario 1 policy in place, adding the budget on top of the auth:</p><pre>kubectl apply -f https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/virtual-keys/manifests/05-apikey-auth-plus-budget-policy.yaml</pre><p><strong>Watch Alice burn through her budget:</strong></p><pre># run the same call three times; token usage accumulates against Alice&#39;s budget<br># call 1 -&gt; HTTP 200 (~89 tokens) | call 2 -&gt; HTTP 200 (now over 100) | call 3 -&gt; HTTP 429<br>for i in 1 2 3; do<br>  curl -s -o /dev/null -w &quot;call $i -&gt; HTTP %{http_code}\n&quot; \<br>    -X POST http://localhost:8080/llm -H &#39;Content-Type: application/json&#39; \<br>    -H &#39;Authorization: Bearer sk-alice-abc123def456&#39; -d &quot;$BODY&quot;<br>done</pre><p>429 is HTTP for &quot;Too Many Requests.&quot; Alice is cut off until her daily window resets. <strong>And crucially, Bob, a different key with a separate budget, is completely unaffected:</strong></p><pre># Bob has his own budget → HTTP 200<br>curl -X POST http://localhost:8080/llm -H &#39;Content-Type: application/json&#39; \<br>  -H &#39;Authorization: Bearer sk-bob-xyz789uvw012&#39; -d &quot;$BODY&quot;</pre><p>That isolation is the entire point. One noisy teammate hitting their ceiling does nothing to everyone else. That’s the exact failure the naive “share the URL” approach couldn’t prevent.</p><h3>Scenario 3: API keys vs. JWTs, and a surprise when you use both</h3><p>There’s a second way to prove identity to the gateway, and it’s worth understanding so you can pick the right one for your team.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_BxdeEFLCqfdN2mFhfNB1A.jpeg" /><figcaption><strong>API keys and JWTs solve the same problem — proving identity — but they fit very different operational models.</strong></figcaption></figure><p>An <strong>API key</strong> (what we’ve used so far) is an <em>opaque</em> string. It carries no information; it only means something because the gateway has a list mapping it to a person. A <strong>JWT</strong> (JSON Web Token) is the opposite: a <em>self-describing</em>, signed token, usually handed out by a central login system (an “identity provider” like Keycloak, Auth0, or Okta). It carries facts about the user (their id, team, groups) right inside it, and the gateway verifies it’s genuine by checking its cryptographic signature against the provider’s public keys (published at a URL called a <strong>JWKS</strong>).</p><p>The OSS AgentgatewayPolicy supports JWTs too, via a jwtAuthentication field that sits right next to apiKeyAuthentication:</p><pre># shape only — the inline JWKS below is abbreviated. The runnable version is<br># generated by the demo minter shown right after this block.<br>apiVersion: agentgateway.dev/v1alpha1<br>kind: AgentgatewayPolicy<br>metadata:<br>  name: jwt-auth<br>  namespace: agentgateway-system<br>spec:<br>  targetRefs:<br>    - group: gateway.networking.k8s.io<br>      kind: Gateway<br>      name: agentgateway-proxy<br>  traffic:<br>    jwtAuthentication:<br>      mode: Strict<br>      providers:<br>        - issuer: virtual-keys-demo<br>          audiences: [agentgateway]<br>          jwks:<br>            # Inline keys are for demos only. In production you point<br>            # jwks.remote at your identity provider&#39;s public JWKS URL.<br>            inline: |<br>              {&quot;keys&quot;:[{&quot;kty&quot;:&quot;RSA&quot;,&quot;n&quot;:&quot;...&quot;,&quot;e&quot;:&quot;AQAB&quot;,&quot;use&quot;:&quot;sig&quot;,&quot;alg&quot;:&quot;RS256&quot;,&quot;kid&quot;:&quot;demo-key-1&quot;}]}</pre><p>A JWT policy is only useful if you can present a valid token, so we need a key to sign one. Rather than ship a private key, a small script in the repo generates a <strong>throwaway</strong> demo key locally (never committed), emits a matching policy, and mints tokens signed by it. Grab it, apply the policy, and mint a token, all with cryptography (no PyJWT needed):</p><pre>curl -sO https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/virtual-keys/manifests/jwt/mint-demo-jwt.py<br>python3 mint-demo-jwt.py --policy | kubectl apply -f -   # jwt-auth policy trusting your demo key<br>export JWT=$(python3 mint-demo-jwt.py)                   # a token signed by that same key</pre><p>One thing to watch if you’ve been following along: the api-key-auth policy from Scenarios 1–2 is <strong>still attached</strong> to this gateway. As you&#39;ll see in a moment, two auth policies compose as a strict <strong>AND</strong>, so a JWT-only request would fail with no API Key found until you remove the API-key policy. To test the JWT on its own, detach it first (we&#39;ll re-attach it right after to show the AND):</p><pre>kubectl delete agentgatewaypolicy api-key-auth -n agentgateway-system</pre><p>With only jwt-auth attached, the demo JWT behaves as you&#39;d expect: valid token in, 200; no token or an API key (which isn&#39;t a JWT), 401:</p><pre># $JWT was minted above (iss: virtual-keys-demo, aud: agentgateway)<br>curl -X POST http://localhost:8080/llm -H &#39;Content-Type: application/json&#39; \<br>  -H &quot;Authorization: Bearer $JWT&quot; -d &quot;$BODY&quot;<br># → HTTP 200<br><br># no token → HTTP 401  (authentication failure: no bearer token found)<br>curl -X POST http://localhost:8080/llm -H &#39;Content-Type: application/json&#39; -d &quot;$BODY&quot;<br><br># an API key, not a JWT → HTTP 401  (the token header is malformed: Error(InvalidToken))<br>curl -X POST http://localhost:8080/llm -H &#39;Content-Type: application/json&#39; \<br>  -H &#39;Authorization: Bearer sk-alice-abc123def456&#39; -d &quot;$BODY&quot;</pre><p><strong>Now the surprising part, and a genuinely useful lesson.</strong> What if you attach <em>both</em> policies, api-key-auth <strong>and</strong> jwt-auth, to the same gateway? I expected one of two things: either an error, or &quot;either credential works&quot; (OR logic). Tested live, it&#39;s neither. The two checks compose as a strict <strong>AND</strong>: a request must satisfy <em>both</em> to get through.</p><p>Re-attach the API-key policy we removed above so both are live at once:</p><pre>kubectl apply -f https://raw.githubusercontent.com/felipevicens/aaif-labs/main/agentgateway/virtual-keys/manifests/03-apikey-auth-policy.yaml   # api-key-auth back alongside jwt-auth</pre><pre># both policies attached — valid JWT but no API key → HTTP 401 (no API Key found)<br>curl -X POST http://localhost:8080/llm -H &#39;Content-Type: application/json&#39; \<br>  -H &quot;Authorization: Bearer $JWT&quot; -d &quot;$BODY&quot;<br><br># both policies attached — valid API key but no JWT → HTTP 401 (token malformed: InvalidToken)<br>curl -X POST http://localhost:8080/llm -H &#39;Content-Type: application/json&#39; \<br>  -H &#39;Authorization: Bearer sk-bob-xyz789uvw012&#39; -d &quot;$BODY&quot;</pre><p>The error even tells you which layer said no. <strong>The practical takeaway:</strong> if you want to offer your team a <em>choice</em> (“use an API key OR a JWT”), do <strong>not</strong> stack both auth fields on the same gateway; that gives you “must have both.” To offer a choice, put each auth method on a separate route or listener.</p><p>So which should <em>you</em> use for sharing a local model with a team? Here’s the same comparison the table gave, dimension by dimension:</p><p><strong>What it is</strong></p><ul><li><em>API key</em> (apiKeyAuthentication): an opaque string you hand out.</li><li><em>JWT</em> (jwtAuthentication): a signed token from a login system.</li></ul><p><strong>Where identity lives</strong></p><ul><li><em>API key:</em> in a Secret you manage.</li><li><em>JWT:</em> in an external identity provider.</li></ul><p><strong>Best when</strong></p><ul><li><em>API key:</em> small teams, scripts, services; you want to be handing out keys in minutes.</li><li><em>JWT:</em> you already have SSO/Keycloak/Okta and want central login.</li></ul><p><strong>Revoking access</strong></p><ul><li><em>API key:</em> remove the key from the Secret (see the trap below).</li><li><em>JWT:</em> let the token expire, or drop the key from the provider’s JWKS.</li></ul><p>For a handful of teammates sharing one local model, <strong>API keys are the fast, self-contained choice</strong>, with no identity provider to stand up. Reach for JWTs when you already run central login and want the model to plug into it.</p><h3>Scenario 4: Adding and revoking keys, how fast, and one nasty trap</h3><p>Handing out and taking back keys is the day-to-day of running this. The official docs don’t say how quickly a Secret change takes effect, so I measured it.</p><p>If you came straight from Scenario 3, jwt-auth is still attached alongside api-key-auth — and by that same <strong>AND</strong> rule, an API-key-only request would be rejected by the JWT layer. This scenario is about API keys, so detach the JWT policy first to get back to API-key-only:</p><pre>kubectl delete agentgatewaypolicy jwt-auth -n agentgateway-system</pre><p><strong>Adding a new teammate (Carol):</strong> add her entry to the Secret, re-apply, and poll until her key works:</p><pre># re-apply the Secret with Carol&#39;s entry added (same block as Scenario 1 + carol)<br>cat &lt;&lt;EOF | kubectl apply -f -<br>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: llm-api-keys<br>  namespace: agentgateway-system<br>type: Opaque<br>stringData:<br>  alice: |<br>    { &quot;key&quot;: &quot;sk-alice-abc123def456&quot;, &quot;metadata&quot;: { &quot;user_id&quot;: &quot;alice&quot; } }<br>  bob: |<br>    { &quot;key&quot;: &quot;sk-bob-xyz789uvw012&quot;, &quot;metadata&quot;: { &quot;user_id&quot;: &quot;bob&quot; } }<br>  carol: |<br>    { &quot;key&quot;: &quot;sk-carol-newkey999&quot;, &quot;metadata&quot;: { &quot;user_id&quot;: &quot;carol&quot; } }<br>EOF</pre><pre># Carol&#39;s key is accepted ~120 ms after the apply returns → HTTP 200<br>curl -X POST http://localhost:8080/llm -H &#39;Content-Type: application/json&#39; \<br>  -H &#39;Authorization: Bearer sk-carol-newkey999&#39; -d &quot;$BODY&quot;</pre><p>Basically instant, well under a second. The gateway <em>watches</em> the Secret and picks up changes immediately; there’s no cache to wait out.</p><p><strong>Revoking a key is where I hit a real trap, and it’s worth your attention because it fails silently.</strong> My first instinct was to delete Alice’s entry from the YAML and re-apply. kubectl said secret/llm-api-keys configured, no error… but Alice&#39;s key <em>kept working</em>. For 35 seconds of polling. Here&#39;s the tell:</p><pre>kubectl get secret llm-api-keys -n agentgateway-system -o jsonpath=&#39;{.data}&#39;<br># {&quot;alice&quot;:&quot;...&quot;,&quot;bob&quot;:&quot;...&quot;,&quot;carol&quot;:&quot;...&quot;}   ← alice is STILL there</pre><p>Why? A Kubernetes Secret has two fields: stringData (the human-readable version you write) and data (the base64-encoded version the server actually stores). When you apply, the server only ever keeps data; it never stores stringData back. kubectl apply figures out what to <em>delete</em> by diffing your new YAML against a record of your last-applied YAML, which was stringData. So it looks for stringData.alice to remove, doesn&#39;t find it in the stored object (which only has data.alice), and quietly deletes nothing. <strong>This is a Kubernetes/</strong><strong>kubectl quirk, not an AgentGateway bug.</strong> But if you revoke keys by editing-and-reapplying, your &quot;revoked&quot; key is still live and <em>nothing warns you</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZhxM-6amOtA4mBL03U_THw.jpeg" /><figcaption><strong>Revoking credentials sounds simple until implementation details get in the way. Testing matters as much as configuration.</strong></figcaption></figure><p>The reliable fix is to remove the encoded entry directly:</p><pre>kubectl patch secret llm-api-keys -n agentgateway-system \<br>  --type=json -p &#39;[{&quot;op&quot;:&quot;remove&quot;,&quot;path&quot;:&quot;/data/alice&quot;}]&#39;<br><br># Alice is revoked ~110 ms after the patch → HTTP 401<br>curl -X POST http://localhost:8080/llm -H &#39;Content-Type: application/json&#39; \<br>  -H &#39;Authorization: Bearer sk-alice-abc123def456&#39; -d &quot;$BODY&quot;</pre><p>Done correctly, revocation is as instant as provisioning: ~110 ms, no cache delay. (kubectl delete secret &amp;&amp; kubectl create -f ... also works and avoids the diff problem entirely, since it doesn&#39;t go through apply.) Whichever you use, <strong>verify</strong> afterward with the -o jsonpath=&#39;{.data}&#39; command above. Don&#39;t trust the exit code.</p><h3>Running without Kubernetes</h3><p>Everything above uses AgentGateway’s Kubernetes objects. AgentGateway also runs <strong>standalone</strong>: a single process configured by a local YAML/JSON file, no cluster involved. The same virtual-key and rate-limit ideas apply there; see the <a href="https://agentgateway.dev/docs/standalone/main/configuration/security/apikey-authn/">standalone API-key docs</a> if that fits your setup better.</p><h3>Wrap-up</h3><p>You started with one local model and the messy option of sharing its URL. You now have a gateway in front of it where <strong>every teammate holds their own key</strong>, every request is <strong>attributed to a person</strong>, everyone has an <strong>independent token budget</strong>, and any single key can be <strong>revoked in ~100 ms</strong>. No shared database, no custom code, just a Secret and a policy or two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HF2Heh4taB0UrAOrqIdFfw.jpeg" /><figcaption><strong>From an exposed endpoint to a production-ready AI service: authentication, attribution, rate limiting, and controlled access in a single architecture.</strong></figcaption></figure><p>The concepts, once, in plain terms: a <strong>gateway</strong> is the receptionist; a <strong>virtual key</strong> is a per-person pass it checks; <strong>metadata</strong> on that key lets a <strong>CEL</strong> expression attach a <strong>token budget</strong> to the person behind it; <strong>JWTs</strong> are the alternative when you already run central login. And the rough edges are operational, not architectural. The stringData revoke trap and the experimental flag are the two that&#39;ll bite a newcomer, so test that revocation and budgets actually take effect rather than trusting they did.</p><p>All manifests used here are in the companion repo, <a href="https://github.com/felipevicens/aaif-labs/tree/main/agentgateway/virtual-keys/manifests">felipevicens/aaif-labs</a>, applied and then torn down against a disposable kind cluster.</p><h3>Tear down</h3><p>When you’re done, delete the whole cluster in one shot; it takes everything (gateway, policies, Secret, rate limiter) with it, so there’s nothing to clean up piecemeal:</p><pre>kind delete cluster --name agentgateway-virtual-keys</pre><p>The demo JWT signing key never left your machine; if you want it gone too, remove demo-signing-key.pem next to the minter script.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd1848fc3eec" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>