<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/"><channel><title>Performance | Tobias Theel | Senior Software Engineer</title><link>https://blog.noobygames.de/tags/performance/</link><description>Remote-first Senior Software Engineer specializing in Go, Cloud-Native architecture, and Game Development. 12+ years of experience in distributed environments.</description><generator>Hugo</generator><language>en</language><copyright>© 2026 Tobias Theel</copyright><lastBuildDate>Tue, 24 Nov 2026 06:30:00 +0100</lastBuildDate><atom:link href="https://blog.noobygames.de/tags/performance/index.xml" rel="self" type="application/rss+xml"/><item><title>Where does the time go? Profiling gocloak with pprof</title><link>https://blog.noobygames.de/blog/gocloak-pprof-profiling/</link><pubDate>Tue, 24 Nov 2026 06:30:00 +0100</pubDate><dc:creator>Tobias Theel</dc:creator><guid isPermaLink="true">https://blog.noobygames.de/blog/gocloak-pprof-profiling/</guid><category>Software Engineering</category><category>go</category><category>pprof</category><category>profiling</category><category>performance</category><category>keycloak</category><category>gocloak</category><category>encoding-json-v2</category><category>tls</category><category>graphviz</category><category>open-source</category><description>CPU and heap profiles from gocloak benchmarks with go tool pprof: why encoding/json v1 reads its input twice, why resty's body limit causes two thirds of all allocated bytes, and how a too small connection pool shifts TLS handshake CPU onto the Keycloak side.</description><content:encoded><![CDATA[<blockquote>
<p><strong>Series: The gocloak universe.</strong> <a href="/blog/gocloak-mcp-first-mcp-server-homebrew/">Part 1: gocloak-mcp</a> · <a href="/blog/gocloak-auth-proxy-keycloak/">Part 2: gocloak-auth-proxy</a> · <a href="/blog/gocloak-performance-json-v2-http-clients/">Part 3: gocloak performance</a> · <a href="/blog/gocloak-performance-final-benchmarks/">Part 4: final benchmark numbers</a> · Part 5: pprof (you are here)</p>
</blockquote>
<aside class="tldr" aria-label="Key takeaways">
<p class="tldr-title">TL;DR</p>
<ul>
<li>Go benchmarks write CPU and heap profiles with <code>-cpuprofile</code> and <code>-memprofile</code>, and <code>go tool pprof -sample_index=alloc_space</code> shows all allocated bytes, which are what drive GC work.</li>
<li>encoding/json v1 spends 20.9 % of the CPU in <code>checkValid</code>, a separate validation pass over the whole input, while the json/v2 engine validates and decodes in a single pass.</li>
<li>In <code>gocloak.GetUsers</code> with 1,000 users, resty&rsquo;s <code>readAllWithLimit</code> allocated 61 to 67 % of all bytes, more than the JSON decoding, because it reads the body in 512-byte chunks.</li>
<li>With gocloak&rsquo;s old default pool, TLS handshakes took 27.4 % of the CPU under 16 parallel callers, most of it on the server side; an idle pool of 256 dropped that to 0.74 %.</li>
<li>Decoding Keycloak users into your own 8-field struct instead of <code>gocloak.User</code> saves 54 % time, 72 % bytes and 84 % allocations, while a streaming <code>json.NewDecoder</code> made decoding slower.</li>
</ul>

</aside>

<p>Benchmarks tell you how long something takes. They do not tell you why. In <a href="/blog/gocloak-performance-json-v2-http-clients/">Part 3</a> and <a href="/blog/gocloak-performance-final-benchmarks/">Part 4</a> I measured gocloak against Keycloak and found three things worth explaining: json/v2 decodes faster, gocloak allocates about 60 % more bytes than plain resty, and a small connection pool makes parallel calls much slower. This post opens the profiles behind those numbers.</p>
<p>Two of the three findings below only showed up in the profiles: the body limit as the biggest allocation source, and the handshake CPU that lands on the server side.</p>
<h2 id="profiles-from-benchmarks">Profiles from benchmarks</h2>
<p>Go&rsquo;s testing package can write a CPU and a memory profile for any benchmark. No extra code is needed:</p>
<div class="os-tabs">
<div class="os-tab" data-label="Linux / macOS">
<p class="os-tab-label">Linux / macOS</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">go <span class="nb">test</span> -run <span class="s1">&#39;^$&#39;</span> -bench <span class="s1">&#39;BenchmarkJSONUnmarshal/payload=users1000/api=v1$&#39;</span> <span class="se">\
</span></span></span><span class="line"><span class="cl">  -benchtime 5s -cpu <span class="m">4</span> <span class="se">\
</span></span></span><span class="line"><span class="cl">  -cpuprofile cpu.pprof -memprofile mem.pprof -o bench.test .
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">go tool pprof -top bench.test cpu.pprof                              <span class="c1"># text ranking</span>
</span></span><span class="line"><span class="cl">go tool pprof -svg bench.test cpu.pprof &gt; cpu.svg                    <span class="c1"># call graph</span>
</span></span><span class="line"><span class="cl">go tool pprof -svg -sample_index<span class="o">=</span>alloc_space bench.test mem.pprof &gt; mem.svg
</span></span><span class="line"><span class="cl">go tool pprof -svg -diff_base old/cpu.pprof bench.test new/cpu.pprof &gt; diff-cpu.svg
</span></span><span class="line"><span class="cl">go tool pprof -http<span class="o">=</span>:8080 bench.test cpu.pprof                       <span class="c1"># browser UI with flame graph</span>
</span></span></code></pre></div>
</div>

<div class="os-tab" data-label="Windows (PowerShell)">
<p class="os-tab-label">Windows (PowerShell)</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">go</span> <span class="n">test</span> <span class="n">-run</span> <span class="s1">&#39;^$&#39;</span> <span class="n">-bench</span> <span class="s1">&#39;BenchmarkJSONUnmarshal/payload=users1000/api=v1$&#39;</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">  <span class="n">-benchtime</span> <span class="n">5s</span> <span class="n">-cpu</span> <span class="mf">4</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">  <span class="n">-cpuprofile</span> <span class="n">cpu</span><span class="p">.</span><span class="py">pprof</span> <span class="n">-memprofile</span> <span class="n">mem</span><span class="p">.</span><span class="py">pprof</span> <span class="n">-o</span> <span class="n">bench</span><span class="p">.</span><span class="py">test</span> <span class="p">.</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="n">go</span> <span class="n">tool</span> <span class="n">pprof</span> <span class="n">-top</span> <span class="n">bench</span><span class="p">.</span><span class="py">test</span> <span class="n">cpu</span><span class="p">.</span><span class="py">pprof</span>
</span></span><span class="line"><span class="cl"><span class="n">go</span> <span class="n">tool</span> <span class="n">pprof</span> <span class="n">-svg</span> <span class="n">bench</span><span class="p">.</span><span class="py">test</span> <span class="n">cpu</span><span class="p">.</span><span class="py">pprof</span> <span class="p">&gt;</span> <span class="n">cpu</span><span class="p">.</span><span class="py">svg</span>
</span></span><span class="line"><span class="cl"><span class="n">go</span> <span class="n">tool</span> <span class="n">pprof</span> <span class="n">-svg</span> <span class="n">-sample_index</span><span class="p">=</span><span class="n">alloc_space</span> <span class="n">bench</span><span class="p">.</span><span class="py">test</span> <span class="n">mem</span><span class="p">.</span><span class="py">pprof</span> <span class="p">&gt;</span> <span class="n">mem</span><span class="p">.</span><span class="py">svg</span>
</span></span><span class="line"><span class="cl"><span class="n">go</span> <span class="n">tool</span> <span class="n">pprof</span> <span class="n">-svg</span> <span class="n">-diff_base</span> <span class="n">old</span><span class="p">/</span><span class="n">cpu</span><span class="p">.</span><span class="py">pprof</span> <span class="n">bench</span><span class="p">.</span><span class="py">test</span> <span class="n">new</span><span class="p">/</span><span class="n">cpu</span><span class="p">.</span><span class="py">pprof</span> <span class="p">&gt;</span> <span class="nb">diff-cpu</span><span class="p">.</span><span class="py">svg</span>
</span></span><span class="line"><span class="cl"><span class="n">go</span> <span class="n">tool</span> <span class="n">pprof</span> <span class="n">-http</span><span class="p">=</span><span class="err">:</span><span class="mf">8080</span> <span class="n">bench</span><span class="p">.</span><span class="py">test</span> <span class="n">cpu</span><span class="p">.</span><span class="py">pprof</span>
</span></span></code></pre></div>
</div>

</div>

<p>A few details that matter:</p>
<ul>
<li><code>-o bench.test</code> keeps the compiled test binary. pprof needs it to resolve function names.</li>
<li>The memory profile records several sample types. <code>-sample_index=alloc_space</code> shows all bytes allocated during the run, which is what drives GC work. The default, <code>inuse_space</code>, shows only what is still alive at the end, which for a benchmark is close to nothing.</li>
<li><code>-diff_base</code> subtracts one profile from another. In the diff graph red means more in the new profile, green means less.</li>
<li><code>-focus=&lt;regex&gt;</code> and <code>-nodecount=&lt;n&gt;</code> cut a graph down to the part you care about. The graphs in this post use both.</li>
</ul>
<p>The SVG and PNG output needs <a href="https://graphviz.org/download/" rel="noopener">Graphviz</a>, the browser UI with the flame graph does not:</p>
<div class="os-tabs">
<div class="os-tab" data-label="Linux">
<p class="os-tab-label">Linux</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">sudo apt install graphviz
</span></span></code></pre></div>
</div>

<div class="os-tab" data-label="macOS">
<p class="os-tab-label">macOS</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">brew install graphviz
</span></span></code></pre></div>
</div>

<div class="os-tab" data-label="Windows (PowerShell)">
<p class="os-tab-label">Windows (PowerShell)</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">winget</span> <span class="n">install</span> <span class="p">-</span><span class="n">-id</span> <span class="n">Graphviz</span><span class="p">.</span><span class="py">Graphviz</span>
</span></span><span class="line"><span class="cl"><span class="c"># winget does not add dot to PATH; add it for the current session:</span>
</span></span><span class="line"><span class="cl"><span class="nv">$env:Path</span> <span class="p">+=</span> <span class="s2">&#34;;C:\Program Files\Graphviz\bin&#34;</span>
</span></span></code></pre></div>
</div>

</div>

<p>In the gocloak repository, <a href="https://github.com/Nerzal/gocloak/tree/v15.1.0/benchmarks" rel="noopener"><code>benchmarks/profile.sh</code></a> runs all of this for five scenarios. Each scenario runs 5 seconds twice: &ldquo;old&rdquo; with today&rsquo;s defaults (encoding/json v1, resty&rsquo;s default pool) and &ldquo;new&rdquo; with <code>GOEXPERIMENT=jsonv2</code> and, for the pool scenarios, an idle pool of 256. The numbers in this post come from those single 5-second profiling runs. They are not the benchstat medians from Part 4, and I label them where both appear.</p>
<h3 id="how-to-read-the-graphs">How to read the graphs</h3>
<p>Every box is a function. The first number is the flat time, spent in the function itself; &ldquo;of&rdquo; gives the cumulative time including everything it calls. Bigger font means more flat time, thicker and redder edges mean more time along that path. Dotted edges mean that functions in between were removed by the filter. The <a href="https://github.com/google/pprof/blob/main/doc/README.md#interpreting-the-callgraph" rel="noopener">pprof documentation</a> has the full legend.</p>
<h2 id="finding-1-encodingjson-v1-reads-its-input-twice">Finding 1: encoding/json v1 reads its input twice</h2>
<p>The first scenario only decodes the list of 1,000 users, no HTTP involved. Here is the v1 engine, filtered to everything below <code>json.Unmarshal</code>:</p>
<p><img src="/img/gocloak/pprof/json-v1-cpu.svg" alt="pprof CPU call graph of encoding/json v1 decoding 1,000 users: json.Unmarshal splits into decodeState.value with 3.90 s and checkValid with 1.25 s, which is 20.9 percent of the total CPU"></p>
<p><code>json.Unmarshal</code> has two children. The right one, <code>checkValid</code>, takes 20.9 % of the CPU (13.9 % flat). It runs a scanner over the whole input only to check that it is valid JSON, before the actual decoding starts. Then <code>decodeState.value</code> walks the same bytes a second time and builds the structs. So a fifth of the CPU goes into a pass that produces nothing but a yes or no. <code>unquoteBytes</code>, which turns JSON strings into Go strings, adds another 8.7 %.</p>
<p>The v2 engine under the same v1 API:</p>
<p><img src="/img/gocloak/pprof/json-v2-cpu.svg" alt="pprof CPU call graph of the same decode with GOEXPERIMENT=jsonv2: no checkValid node, the work goes through makeStructArshaler and jsontext consumeValue down to jsonwire.ConsumeSimpleString with 7 percent"></p>
<p><code>checkValid</code> is gone. The v2 engine (<code>encoding/json/jsontext</code> underneath) validates while it decodes, in a single pass. The work goes into the &ldquo;arshalers&rdquo;, v2&rsquo;s generated per-type marshal and unmarshal functions, and down to <code>jsonwire.ConsumeSimpleString</code>, a fast path for strings without escape sequences, which describes most strings in a Keycloak user.</p>
<p>The profiling run for this scenario:</p>
<table>
	<thead>
			<tr>
					<th>Decode 1,000 users</th>
					<th style="text-align: right">v1 engine</th>
					<th style="text-align: right">v2 engine</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>Time per op</td>
					<td style="text-align: right">3.96 ms</td>
					<td style="text-align: right">2.39 ms (-40 %)</td>
			</tr>
			<tr>
					<td>Allocations per op</td>
					<td style="text-align: right">45,018</td>
					<td style="text-align: right">25,122 (-44 %)</td>
			</tr>
			<tr>
					<td>Bytes per op</td>
					<td style="text-align: right">1.41 MiB</td>
					<td style="text-align: right">1.16 MiB (-18 %)</td>
			</tr>
	</tbody>
</table>
<p>Old and new ran one after the other in the profiling run, so the time column is only a rough guide. The interleaved A/B run from <a href="/blog/gocloak-performance-json-v2-http-clients/">Part 3</a> measured -32 % for this decode (4.04 to 2.74 ms), and that is the number I trust. The allocation counts are identical in both.</p>
<p>The heap diff shows where the remaining allocations go: v1 allocates through reflection in <code>decodeState.object</code> and <code>literalStore</code>, v2 through <code>reflect.mapassign</code> for the <code>Attributes</code> maps, <code>reflect.unsafe_New</code> and <code>makeString</code>, fewer in total.</p>
<h2 id="finding-2-the-body-limit-allocates-more-than-the-json-decoder">Finding 2: the body limit allocates more than the JSON decoder</h2>
<p>The second scenario runs the whole <code>gocloak.GetUsers</code> call with <code>max=1000</code> against the in-process fake Keycloak. On the CPU side nothing surprises: <code>json.Unmarshal</code> takes 52 % of the client CPU with v1 and 45 % with v2. <code>runtime.cgocall</code>, the socket syscalls on Windows, takes about 23 %, the in-process server about 22 %, the GC workers 7 to 8 %.</p>
<p>The heap profile is where it gets interesting:</p>
<p><img src="/img/gocloak/pprof/getusers-mem.svg" alt="pprof heap graph (alloc_space) of gocloak.GetUsers with 1,000 users: resty.readAllWithLimit allocated 2579 MB, 61.5 percent of all bytes, while the JSON decoder below decodeState.value allocated 1536 MB"></p>
<p><code>resty.readAllWithLimit</code> allocated 61.5 % of all bytes in this run, 61 to 67 % across runs. The complete JSON decoding of 1,000 users comes in second with about 37 %. Reading the body costs more memory than turning it into Go structs.</p>
<p>The response is about 470 KB, yet reading it allocates about 2.5 MB per call. gocloak sets a response body limit as a hardening measure, so a broken or hostile server cannot make it read an endless response. With a limit set, resty reads the body in 512-byte chunks and appends each chunk to a slice, without looking at <code>Content-Length</code> first. Every time the slice runs out of capacity, <code>append</code> allocates a bigger one and copies everything over. For large slices Go grows by a factor of about 1.25, so the intermediate copies add up to roughly five times the body size. The small boxes under <code>readAllWithLimit</code> in the graph are those growth steps: 344 KB, 432 KB, 544 KB and the many smaller ones before.</p>
<p>CPU barely notices, this is about 7 % of the client CPU. The garbage collector notices, because it has to clean up all of that.</p>
<p>Without the profile I would have blamed the JSON decoder for gocloak&rsquo;s extra bytes. gocloak v15.1.0 now offers an opt-in, <code>gocloak.SetDirectBodyRead()</code>: gocloak reads and decodes the body itself and allocates once from <code>Content-Length</code>, which it trusts only up to the limit. Wrapping the transport was rejected, because it breaks <code>Transport()</code>, <code>SetTLSClientConfig</code> and <code>SetProxy</code> on the resty client. For 1,000 users the bytes per call drop by 39 %. It is opt-in because resty&rsquo;s <code>OnAfterResponse</code> hooks and <code>SetDebug</code> body logging do not run for these calls. The core idea as a sketch; the real implementation also handles gzip and decodes error responses the way resty does:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-go" data-lang="go"><span class="line"><span class="cl"><span class="c1">// sketch: read a body with a hard limit and a single allocation when Content-Length is known</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">func</span><span class="w"> </span><span class="nf">readLimited</span><span class="p">(</span><span class="nx">response</span><span class="w"> </span><span class="o">*</span><span class="nx">http</span><span class="p">.</span><span class="nx">Response</span><span class="p">,</span><span class="w"> </span><span class="nx">limit</span><span class="w"> </span><span class="kt">int64</span><span class="p">)</span><span class="w"> </span><span class="p">([]</span><span class="kt">byte</span><span class="p">,</span><span class="w"> </span><span class="kt">error</span><span class="p">)</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">response</span><span class="p">.</span><span class="nx">ContentLength</span><span class="w"> </span><span class="p">&gt;</span><span class="w"> </span><span class="nx">limit</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="kc">nil</span><span class="p">,</span><span class="w"> </span><span class="nx">fmt</span><span class="p">.</span><span class="nf">Errorf</span><span class="p">(</span><span class="s">&#34;response body of %d bytes exceeds %d&#34;</span><span class="p">,</span><span class="w"> </span><span class="nx">response</span><span class="p">.</span><span class="nx">ContentLength</span><span class="p">,</span><span class="w"> </span><span class="nx">limit</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">response</span><span class="p">.</span><span class="nx">ContentLength</span><span class="w"> </span><span class="o">&gt;=</span><span class="w"> </span><span class="mi">0</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="c1">// net/http already stops reading at Content-Length, so this is one exact allocation</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nx">body</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nb">make</span><span class="p">([]</span><span class="kt">byte</span><span class="p">,</span><span class="w"> </span><span class="nx">response</span><span class="p">.</span><span class="nx">ContentLength</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nx">_</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">io</span><span class="p">.</span><span class="nf">ReadFull</span><span class="p">(</span><span class="nx">response</span><span class="p">.</span><span class="nx">Body</span><span class="p">,</span><span class="w"> </span><span class="nx">body</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="nx">body</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="c1">// unknown length (chunked encoding): read at most limit+1 bytes to detect an oversized body</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nx">body</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">io</span><span class="p">.</span><span class="nf">ReadAll</span><span class="p">(</span><span class="nx">io</span><span class="p">.</span><span class="nf">LimitReader</span><span class="p">(</span><span class="nx">response</span><span class="p">.</span><span class="nx">Body</span><span class="p">,</span><span class="w"> </span><span class="nx">limit</span><span class="o">+</span><span class="mi">1</span><span class="p">))</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">!=</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="kc">nil</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">if</span><span class="w"> </span><span class="nb">int64</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="nx">body</span><span class="p">))</span><span class="w"> </span><span class="p">&gt;</span><span class="w"> </span><span class="nx">limit</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="k">return</span><span class="w"> </span><span class="kc">nil</span><span class="p">,</span><span class="w"> </span><span class="nx">fmt</span><span class="p">.</span><span class="nf">Errorf</span><span class="p">(</span><span class="s">&#34;response body exceeds %d bytes&#34;</span><span class="p">,</span><span class="w"> </span><span class="nx">limit</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="k">return</span><span class="w"> </span><span class="nx">body</span><span class="p">,</span><span class="w"> </span><span class="kc">nil</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><h2 id="finding-3-a-small-pool-burns-cpu-on-tls-handshakes">Finding 3: a small pool burns CPU on TLS handshakes</h2>
<p>The third scenario is the pool benchmark: 16 goroutines call <code>GetUserByID</code> in parallel over TLS with HTTP/1.1 against the in-process server. With gocloak&rsquo;s default pool, filtered to the connection handling:</p>
<p><img src="/img/gocloak/pprof/pool-default-cpu.svg" alt="pprof CPU call graph with the default pool: crypto/tls HandshakeContext takes 27.4 percent of all CPU; serverHandshakeStateTLS13 takes 20.4 percent, most of it in RSA decrypt and bigmod montgomeryMul, while the client handshake takes 6.5 percent"></p>
<p>27.4 % of the whole CPU goes into <code>crypto/tls.(*Conn).HandshakeContext</code>. The server side of the handshake takes 20.4 %, most of it in the RSA-PSS signature of the server certificate (<code>rsa.decrypt</code> and the big-number arithmetic in <code>bigmod</code> below it). The client side takes 6.5 %, opening the connections (<code>dialConn</code>) another 3.8 %.</p>
<p>The same scenario with an idle pool of 256:</p>
<p><img src="/img/gocloak/pprof/pool-tuned-cpu.svg" alt="pprof CPU call graph with an idle pool of 256: no TLS handshake nodes left; the connection path consists of http Transport roundTrip, getConn and queueForIdleConn with well under 2 percent each"></p>
<p>The handshake share drops to 0.74 %. What remains of the connection handling is <code>getConn</code> taking an idle connection out of the pool.</p>
<table>
	<thead>
			<tr>
					<th>Pool scenario (profiling run)</th>
					<th style="text-align: right">Default pool</th>
					<th style="text-align: right">Pool 256</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>Time per op</td>
					<td style="text-align: right">21.7 µs</td>
					<td style="text-align: right">12.5 µs</td>
			</tr>
			<tr>
					<td>New connections per 1,000 calls</td>
					<td style="text-align: right">20.4</td>
					<td style="text-align: right">0.11</td>
			</tr>
			<tr>
					<td>CPU share of TLS handshakes</td>
					<td style="text-align: right">27.4 %</td>
					<td style="text-align: right">0.74 %</td>
			</tr>
	</tbody>
</table>
<p>The absolute times differ from Part 4 (39.2 and 15.2 µs in the interleaved A/B run) because this was a single, longer run with a different load on the machine. The direction is the same. gocloak v15.1.0 keeps 100 idle connections per host.</p>
<p>The part that matters for production: in this benchmark both sides run in one process, and the server&rsquo;s share of the handshake is three times the client&rsquo;s. In a real deployment the server side runs wherever TLS for Keycloak is terminated, in Keycloak itself or in an ingress in front of it. A client with a too small pool does not only slow itself down. It makes the TLS endpoint of the identity provider do expensive RSA signatures over and over, and every other application that talks to the same Keycloak pays for that.</p>
<h2 id="live-keycloak-dominates">Live: Keycloak dominates</h2>
<p>Two scenarios ran against the real Keycloak in Docker over plain HTTP.</p>
<p><code>live-getusers1000</code> went from 41.8 ms to 38.9 ms, allocations from 33,179 to 24,216 and bytes from 3.18 MiB to 3.09 MiB. In the profile the client shows up almost only in decoding and reading the body. The rest of the time it waits for Keycloak.</p>
<p><code>live-pool</code> with 16 parallel callers went from 277.7 µs to 212.5 µs per call (-23 %), with 308.5 against 4.0 new connections per 1,000 calls. Without TLS a new connection is cheap, so the effect is smaller than in the TLS scenario offline.</p>
<h2 id="checking-a-claim-from-another-tool">Checking a claim from another tool</h2>
<p>While I wrote this series, another AI coding tool analyzed an application that uses gocloak. It claimed that the pointer fields in <code>gocloak.User</code> caused 37.6 % of all object allocations, and that a streaming decoder would help. Both claims can be measured (Go 1.27, 1,000 users, n=6):</p>
<ul>
<li>User fields as values instead of pointers: -40 % allocations, so the first half of the claim holds. But it saves no time and costs 49 % more bytes, because every slice element gets bigger. And an update could no longer send <code>false</code>, <code>0</code> or <code>&quot;&quot;</code>, since the zero value would look like &ldquo;not set&rdquo;. gocloak keeps the pointers.</li>
<li>Streaming with <code>json.NewDecoder</code> instead of <code>json.Unmarshal</code>: +10 % time and +82 % bytes. That half of the claim is wrong.</li>
</ul>
<p>The lever is in the application. If you only read a few fields of many users, decode into your own struct. With an 8-field struct that saves 54 % time, 72 % bytes and 84 % allocations. gocloak&rsquo;s README now shows how:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-go" data-lang="go"><span class="line"><span class="cl"><span class="kd">type</span><span class="w"> </span><span class="nx">userRow</span><span class="w"> </span><span class="kd">struct</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nx">ID</span><span class="w">       </span><span class="kt">string</span><span class="w"> </span><span class="s">`json:&#34;id&#34;`</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nx">Username</span><span class="w"> </span><span class="kt">string</span><span class="w"> </span><span class="s">`json:&#34;username&#34;`</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nx">Email</span><span class="w">    </span><span class="kt">string</span><span class="w"> </span><span class="s">`json:&#34;email&#34;`</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="kd">var</span><span class="w"> </span><span class="nx">rows</span><span class="w"> </span><span class="p">[]</span><span class="nx">userRow</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="nx">resp</span><span class="p">,</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">client</span><span class="p">.</span><span class="nf">GetRequestWithBearerAuth</span><span class="p">(</span><span class="nx">ctx</span><span class="p">,</span><span class="w"> </span><span class="nx">token</span><span class="p">.</span><span class="nx">AccessToken</span><span class="p">).</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nf">SetQueryParams</span><span class="p">(</span><span class="kd">map</span><span class="p">[</span><span class="kt">string</span><span class="p">]</span><span class="kt">string</span><span class="p">{</span><span class="s">&#34;briefRepresentation&#34;</span><span class="p">:</span><span class="w"> </span><span class="s">&#34;true&#34;</span><span class="p">,</span><span class="w"> </span><span class="s">&#34;max&#34;</span><span class="p">:</span><span class="w"> </span><span class="s">&#34;1000&#34;</span><span class="p">}).</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nf">SetResult</span><span class="p">(</span><span class="o">&amp;</span><span class="nx">rows</span><span class="p">).</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nf">Get</span><span class="p">(</span><span class="s">&#34;https://keycloak.example.com/admin/realms/myrealm/users&#34;</span><span class="p">)</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="k">if</span><span class="w"> </span><span class="nx">err</span><span class="w"> </span><span class="o">==</span><span class="w"> </span><span class="kc">nil</span><span class="w"> </span><span class="o">&amp;&amp;</span><span class="w"> </span><span class="nx">resp</span><span class="p">.</span><span class="nf">IsError</span><span class="p">()</span><span class="w"> </span><span class="p">{</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nx">err</span><span class="w"> </span><span class="p">=</span><span class="w"> </span><span class="nx">fmt</span><span class="p">.</span><span class="nf">Errorf</span><span class="p">(</span><span class="s">&#34;get users: %s&#34;</span><span class="p">,</span><span class="w"> </span><span class="nx">resp</span><span class="p">.</span><span class="nf">Status</span><span class="p">())</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="p">}</span><span class="w">
</span></span></span></code></pre></div><p>A profile shows where allocations happen. Whether a proposed fix helps still takes a measurement.</p>
<h2 id="what-the-profiles-added">What the profiles added</h2>
<p>The benchmark numbers said &ldquo;gocloak allocates 60 % more than resty&rdquo; and &ldquo;the default pool is slower under parallel load&rdquo;. The profiles explained both:</p>
<ol>
<li>encoding/json v1 validates the whole input in a separate pass before it decodes. v2 does both in one pass, and that accounts for a large part of its advantage.</li>
<li>The extra bytes come from reading the body with a limit in 512-byte steps, not from JSON. <code>SetDirectBodyRead()</code> in v15.1.0 fixes it as an opt-in.</li>
<li>The cost of the small pool is TLS handshakes, and most of that cost lands on the server side, which in production means the Keycloak side. v15.1.0 keeps 100 idle connections per host.</li>
</ol>
<p>The profiles have the same weakness as my first benchmark runs: old and new ran one after the other. For how much faster something is, the interleaved A/B runs from Part 3 and Part 4 are the reference. For where the time and the bytes go, the profiles are.</p>
]]></content:encoded></item><item><title>gocloak benchmarks, final numbers: five HTTP stacks, json/v2 and a cold JVM</title><link>https://blog.noobygames.de/blog/gocloak-performance-final-benchmarks/</link><pubDate>Mon, 23 Nov 2026 06:30:00 +0100</pubDate><dc:creator>Tobias Theel</dc:creator><guid isPermaLink="true">https://blog.noobygames.de/blog/gocloak-performance-final-benchmarks/</guid><category>Software Engineering</category><category>go</category><category>keycloak</category><category>gocloak</category><category>performance</category><category>benchmark</category><category>benchstat</category><category>encoding-json-v2</category><category>fasthttp</category><category>resty</category><category>docker</category><category>open-source</category><description>The complete benchstat tables for gocloak against a fake and a real Keycloak: five HTTP stacks, connection pools, json/v2 over the whole request path, plus four benchmark traps: a cold JVM, a Docker port forwarder that one client poisoned for the next, Git Bash rewriting benchstat flags, and load changes between sequential runs. Plus what gocloak v15.1.0 on Go 1.27 changes.</description><content:encoded><![CDATA[<blockquote>
<p><strong>Series: The gocloak universe.</strong> <a href="/blog/gocloak-mcp-first-mcp-server-homebrew/">Part 1: gocloak-mcp</a> · <a href="/blog/gocloak-auth-proxy-keycloak/">Part 2: gocloak-auth-proxy</a> · <a href="/blog/gocloak-performance-json-v2-http-clients/">Part 3: gocloak performance</a> · Part 4: final benchmark numbers (you are here) · <a href="/blog/gocloak-pprof-profiling/">Part 5: pprof</a></p>
</blockquote>
<aside class="tldr" aria-label="Key takeaways">
<p class="tldr-title">TL;DR</p>
<ul>
<li>Against a real Keycloak 26.8.2 in Docker, all five HTTP stacks were equally fast for single calls, and fasthttp saved only 6 to 10 % on small calls.</li>
<li>With 16 parallel callers over TLS and HTTP/1.1, an idle pool of 256 made gocloak 2.6 times as fast and cut new connections by 98 % in an interleaved A/B run.</li>
<li>Through gocloak&rsquo;s full request path, json/v2 cuts allocations by 9 to 44 % on every call, but only the user lists got measurably faster (19 to 24 % offline).</li>
<li>gocloak v15.1.0 has no breaking API changes: it requires Go 1.27, keeps 100 idle connections per host and adds <code>SetDirectBodyRead()</code> as an opt-in.</li>
<li>A cold Keycloak JVM made 1,000 users take 153 to 185 ms in my first live run, against 39 ms in the final run with the same container and data.</li>
</ul>

</aside>

<p>In <a href="/blog/gocloak-performance-json-v2-http-clients/">Part 3</a> I described how I benchmarked gocloak against Keycloak: the questions, the setup, the things that broke and the conclusions. This post has the complete tables from the final run, for everyone who wants to check the conclusions against the numbers, and four lessons the final run added.</p>
<h2 id="environment">Environment</h2>
<p>All numbers are benchstat medians with n=8 (n=10 for the interleaved A/B runs) and <code>GOMAXPROCS=4</code>, built with Go 1.26.2, against Keycloak 26.8.2 in Docker Desktop on Windows 11 (AMD Ryzen AI 9 HX 370). Other coding agents were running on the same machine. Time values scatter by 30 to 40 % in places, while allocations are deterministic (±0 %). &ldquo;n.s.&rdquo; means not significant.</p>
<p>The five stacks are gocloak with its defaults, gocloak with an idle pool of 256 connections per host, plain resty, net/http with a tuned pool and a streaming decoder, and fasthttp. The benchmark code is in <a href="https://github.com/Nerzal/gocloak/tree/v15.1.0/benchmarks" rel="noopener"><code>benchmarks/</code></a> in the gocloak repository, together with <code>run.sh</code> and <code>profile.sh</code>. In v15.1.0 the default keeps 100 idle connections per host, so the benchmark names changed: <code>gocloak</code> is the new default, <code>gocloak-restypool</code> the old resty pool and <code>gocloak-direct</code> uses <code>SetDirectBodyRead()</code>. The tables below are from before that change.</p>
<h2 id="offline-fake-keycloak-plain-http11-one-caller-at-a-time">Offline: fake Keycloak, plain HTTP/1.1, one caller at a time</h2>
<p>Time per call; the percentage compares with gocloak&rsquo;s default:</p>
<table>
	<thead>
			<tr>
					<th>Endpoint</th>
					<th style="text-align: right">gocloak</th>
					<th style="text-align: right">gocloak, pool 256</th>
					<th style="text-align: right">resty</th>
					<th style="text-align: right">net/http</th>
					<th style="text-align: right">fasthttp</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>Token</td>
					<td style="text-align: right">233 µs</td>
					<td style="text-align: right">238 µs (n.s.)</td>
					<td style="text-align: right">245 µs (n.s.)</td>
					<td style="text-align: right">198 µs (n.s.)</td>
					<td style="text-align: right">127 µs (-46 %)</td>
			</tr>
			<tr>
					<td>One user</td>
					<td style="text-align: right">136 µs</td>
					<td style="text-align: right">157 µs (+15 %)</td>
					<td style="text-align: right">173 µs (+27 %)</td>
					<td style="text-align: right">188 µs (+38 %)</td>
					<td style="text-align: right">111 µs (-19 %)</td>
			</tr>
			<tr>
					<td>100 users</td>
					<td style="text-align: right">1,637 µs</td>
					<td style="text-align: right">1,075 µs (-34 %)</td>
					<td style="text-align: right">833 µs (-49 %)</td>
					<td style="text-align: right">1,148 µs (-30 %)</td>
					<td style="text-align: right">636 µs (-61 %)</td>
			</tr>
			<tr>
					<td>1,000 users</td>
					<td style="text-align: right">5.33 ms</td>
					<td style="text-align: right">6.03 ms (n.s.)</td>
					<td style="text-align: right">5.53 ms (n.s.)</td>
					<td style="text-align: right">7.52 ms (+41 %)</td>
					<td style="text-align: right">5.93 ms (n.s.)</td>
			</tr>
			<tr>
					<td>Groups</td>
					<td style="text-align: right">306 µs</td>
					<td style="text-align: right">252 µs (-18 %)</td>
					<td style="text-align: right">184 µs (-40 %)</td>
					<td style="text-align: right">312 µs (n.s.)</td>
					<td style="text-align: right">354 µs (+15 %)</td>
			</tr>
			<tr>
					<td>Clients</td>
					<td style="text-align: right">502 µs</td>
					<td style="text-align: right">327 µs (-35 %)</td>
					<td style="text-align: right">361 µs (-28 %)</td>
					<td style="text-align: right">1,206 µs (+140 %)</td>
					<td style="text-align: right">436 µs (n.s.)</td>
			</tr>
	</tbody>
</table>
<p>There is no consistent pattern. The pool setting cannot make a sequential call 15 % slower, and net/http is not 140 % slower on clients but 30 % faster on 100 users. These are the swings of a loaded machine. Even with n=8 and a p-value, the time column offline says little more than &ldquo;same order of magnitude&rdquo;.</p>
<p>The bytes per call are deterministic and tell a clear story:</p>
<table>
	<thead>
			<tr>
					<th>Bytes per call</th>
					<th style="text-align: right">gocloak</th>
					<th style="text-align: right">resty</th>
					<th style="text-align: right">net/http</th>
					<th style="text-align: right">fasthttp</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>1,000 users</td>
					<td style="text-align: right">3.88 MiB</td>
					<td style="text-align: right">2.42 MiB (-38 %)</td>
					<td style="text-align: right">2.44 MiB (-37 %)</td>
					<td style="text-align: right">1.93 MiB (-50 %)</td>
			</tr>
			<tr>
					<td>Token</td>
					<td style="text-align: right">35.2 KiB</td>
					<td style="text-align: right">27.6 KiB</td>
					<td style="text-align: right">29.5 KiB</td>
					<td style="text-align: right">9.5 KiB (-73 %)</td>
			</tr>
	</tbody>
</table>
<p>All stacks need 45,100 to 45,200 allocations for 1,000 users, because the objects come from the JSON decoder. The extra 1.5 MiB in gocloak come from resty&rsquo;s body limit handling, which <a href="/blog/gocloak-pprof-profiling/">Part 5</a> shows in the memory profile. v15.1.0 adds <code>SetDirectBodyRead()</code> as an opt-in that closes most of the gap.</p>
<h2 id="offline-16-parallel-callers-over-tls">Offline: 16 parallel callers over TLS</h2>
<p>16 goroutines call <code>GetUserByID</code> in parallel:</p>










<figure class="diagram">
    <div class="diagram-canvas" role="img" aria-label="TLS with HTTP/1.1. The default pool keeps too few idle connections, so many calls pay for a new TCP connection and a TLS handshake.">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 720 268" width="720" height="268">
<text x="20" y="28" class="d-t d-bold" font-size="15">16 parallel callers, TLS + HTTP/1.1, time per call (lower is better)</text>
<text x="20" y="48" class="d-m" font-size="11.5">benchstat median, n=8, GOMAXPROCS=4. Label: new connections (dials) per 1,000 calls.</text>
<line x1="190.0" y1="76" x2="190.0" y2="234" class="d-divider"/><text x="190.0" y="250" class="d-m" font-size="11" text-anchor="middle">0 µs</text>
<line x1="316.7" y1="76" x2="316.7" y2="234" class="d-divider"/><text x="316.7" y="250" class="d-m" font-size="11" text-anchor="middle">20 µs</text>
<line x1="443.3" y1="76" x2="443.3" y2="234" class="d-divider"/><text x="443.3" y="250" class="d-m" font-size="11" text-anchor="middle">40 µs</text>
<line x1="570.0" y1="76" x2="570.0" y2="234" class="d-divider"/><text x="570.0" y="250" class="d-m" font-size="11" text-anchor="middle">60 µs</text>
<text x="180" y="96" class="d-t" font-size="12" text-anchor="end">gocloak (default)</text>
<path d="M190 84 H509.0 Q513.0 84 513.0 88 V96 Q513.0 100 509.0 100 H190 Z" fill="#d97706"/>
<text x="519.0" y="96" class="d-t" font-size="11">51.0 µs <tspan class="d-m">30.4 dials/1k</tspan></text>
<text x="180" y="126" class="d-t" font-size="12" text-anchor="end">gocloak, pool 256</text>
<path d="M190 114 H364.6 Q368.6 114 368.6 118 V126 Q368.6 130 364.6 130 H190 Z" fill="#4285f4"/>
<text x="374.6" y="126" class="d-t" font-size="11">28.2 µs <tspan class="d-m">1.09 dials/1k</tspan></text>
<text x="180" y="156" class="d-t" font-size="12" text-anchor="end">plain resty</text>
<path d="M190 144 H357.0 Q361.0 144 361.0 148 V156 Q361.0 160 357.0 160 H190 Z" fill="#4285f4"/>
<text x="367.0" y="156" class="d-t" font-size="11">27.0 µs <tspan class="d-m">13.8 dials/1k</tspan></text>
<text x="180" y="186" class="d-t" font-size="12" text-anchor="end">net/http (tuned)</text>
<path d="M190 174 H307.6 Q311.6 174 311.6 178 V186 Q311.6 190 307.6 190 H190 Z" fill="#4285f4"/>
<text x="317.6" y="186" class="d-t" font-size="11">19.2 µs <tspan class="d-m">0.77 dials/1k</tspan></text>
<text x="180" y="216" class="d-t" font-size="12" text-anchor="end">fasthttp</text>
<path d="M190 204 H277.2 Q281.2 204 281.2 208 V216 Q281.2 220 277.2 220 H190 Z" fill="#4285f4"/>
<text x="287.2" y="216" class="d-t" font-size="11">14.4 µs <tspan class="d-m">0.14 dials/1k</tspan></text>
</svg>

    </div>
    <figcaption class="diagram-caption">TLS with HTTP/1.1. The default pool keeps too few idle connections, so many calls pay for a new TCP connection and a TLS handshake.</figcaption>
</figure>

<table>
	<thead>
			<tr>
					<th>Stack</th>
					<th style="text-align: right">TLS + HTTP/1.1</th>
					<th style="text-align: right">Dials per 1,000 calls</th>
					<th style="text-align: right">TLS + HTTP/2</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>gocloak (default)</td>
					<td style="text-align: right">51.0 µs</td>
					<td style="text-align: right">30.4</td>
					<td style="text-align: right">25.2 µs</td>
			</tr>
			<tr>
					<td>gocloak, pool 256</td>
					<td style="text-align: right">28.2 µs (-45 %)</td>
					<td style="text-align: right">1.09 (-96 %)</td>
					<td style="text-align: right">27.8 µs</td>
			</tr>
			<tr>
					<td>plain resty</td>
					<td style="text-align: right">27.0 µs</td>
					<td style="text-align: right">13.8</td>
					<td style="text-align: right">27.1 µs</td>
			</tr>
			<tr>
					<td>net/http (tuned)</td>
					<td style="text-align: right">19.2 µs (-62 %)</td>
					<td style="text-align: right">0.77</td>
					<td style="text-align: right">22.4 µs</td>
			</tr>
			<tr>
					<td>fasthttp</td>
					<td style="text-align: right">14.4 µs (-72 %)</td>
					<td style="text-align: right">0.14</td>
					<td style="text-align: right">9.2 µs (falls back to HTTP/1.1)</td>
			</tr>
	</tbody>
</table>
<p>Under HTTP/2 none of the Go clients opens new connections, and gocloak&rsquo;s default is as fast as the large pool. Plain resty has the same default pool as gocloak but needed only 13.8 dials per 1,000 calls instead of 30.4. That value scatters by ±64 %, live resty was at gocloak&rsquo;s level (237 against 247), and gocloak always runs first in each group. Probably noise or an order effect; I have not verified it.</p>
<p>Default and large pool also ran one after the other here. An interleaved A/B run of just those two gives 39.2 µs against 15.2 µs per call (-61 %, 2.6 times as fast) and 33.0 against 0.67 new connections per 1,000 calls (-98 %). Bytes per call drop by 25 %, allocations by 15 %.</p>
<h2 id="live-real-keycloak-in-docker-plain-http11-one-caller-at-a-time">Live: real Keycloak in Docker, plain HTTP/1.1, one caller at a time</h2>
<table>
	<thead>
			<tr>
					<th>Endpoint</th>
					<th style="text-align: right">gocloak</th>
					<th style="text-align: right">gocloak, pool 256</th>
					<th style="text-align: right">resty</th>
					<th style="text-align: right">net/http</th>
					<th style="text-align: right">fasthttp</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>Token</td>
					<td style="text-align: right">1.81 ms</td>
					<td style="text-align: right">1.76 ms</td>
					<td style="text-align: right">1.74 ms</td>
					<td style="text-align: right">1.75 ms</td>
					<td style="text-align: right">1.63 ms (-10 %)</td>
			</tr>
			<tr>
					<td>One user</td>
					<td style="text-align: right">906 µs</td>
					<td style="text-align: right">938 µs</td>
					<td style="text-align: right">952 µs</td>
					<td style="text-align: right">959 µs</td>
					<td style="text-align: right">820 µs (-9 %)</td>
			</tr>
			<tr>
					<td>100 users</td>
					<td style="text-align: right">4.66 ms</td>
					<td style="text-align: right">4.74 ms</td>
					<td style="text-align: right">4.68 ms</td>
					<td style="text-align: right">4.67 ms</td>
					<td style="text-align: right">4.59 ms (n.s.)</td>
			</tr>
			<tr>
					<td>1,000 users</td>
					<td style="text-align: right">39.8 ms</td>
					<td style="text-align: right">38.9 ms</td>
					<td style="text-align: right">39.4 ms</td>
					<td style="text-align: right">39.0 ms</td>
					<td style="text-align: right">38.6 ms (n.s.)</td>
			</tr>
			<tr>
					<td>Groups</td>
					<td style="text-align: right">3.03 ms</td>
					<td style="text-align: right">2.99 ms</td>
					<td style="text-align: right">3.00 ms</td>
					<td style="text-align: right">3.03 ms</td>
					<td style="text-align: right">2.92 ms (n.s.)</td>
			</tr>
			<tr>
					<td>Clients</td>
					<td style="text-align: right">1.25 ms</td>
					<td style="text-align: right">1.28 ms</td>
					<td style="text-align: right">1.23 ms</td>
					<td style="text-align: right">1.24 ms</td>
					<td style="text-align: right">1.18 ms (-6 %)</td>
			</tr>
	</tbody>
</table>
<p>Live, all Go variants are equally fast. fasthttp saves 80 to 180 µs on small calls and nothing measurable on large ones. Bytes per call for 1,000 users live: gocloak 3.20 MiB, resty 2.19 MiB (-31 %), net/http 2.26 MiB (-29 %), fasthttp 1.35 MiB (-58 %). For the token fasthttp allocates 85 % fewer bytes.</p>
<h3 id="live-with-16-parallel-callers">Live with 16 parallel callers</h3>
<table>
	<thead>
			<tr>
					<th>Stack</th>
					<th style="text-align: right">Time per call</th>
					<th style="text-align: right">Dials per 1,000 calls</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>gocloak (default)</td>
					<td style="text-align: right">359 µs</td>
					<td style="text-align: right">247</td>
			</tr>
			<tr>
					<td>gocloak, pool 256</td>
					<td style="text-align: right">231 µs (-36 %)</td>
					<td style="text-align: right">64 (-74 %)</td>
			</tr>
			<tr>
					<td>plain resty</td>
					<td style="text-align: right">442 µs (n.s.)</td>
					<td style="text-align: right">237</td>
			</tr>
			<tr>
					<td>net/http (tuned)</td>
					<td style="text-align: right">231 µs (-36 %)</td>
					<td style="text-align: right">68</td>
			</tr>
			<tr>
					<td>fasthttp</td>
					<td style="text-align: right">123 µs (-66 %)</td>
					<td style="text-align: right">1.5</td>
			</tr>
	</tbody>
</table>
<p>The 64 dials of the large pool come from the short ramp-up rounds of the benchmark, in which the pool fills. In a longer 5-second profiling run the default opened 309 connections per 1,000 calls and the large pool 4.</p>
<p>Local token verification with <code>DecodeAccessToken</code>, a real Keycloak token and a warm certificate cache: 50.5 µs.</p>
<h2 id="jsonv2-over-the-whole-gocloak-path">json/v2 over the whole gocloak path</h2>
<p>Part 3 compared the JSON engines in isolation. Here is the same comparison through gocloak&rsquo;s full request path, default build against <code>GOEXPERIMENT=jsonv2</code>, as an interleaved A/B run against the fake Keycloak (n=10). Why interleaved: see the fourth lesson below.</p>
<table>
	<thead>
			<tr>
					<th>gocloak call, offline</th>
					<th style="text-align: right">v1 engine</th>
					<th style="text-align: right">v2 engine</th>
					<th style="text-align: right">Change</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><code>GetUsers</code>, 100 users</td>
					<td style="text-align: right">697 µs</td>
					<td style="text-align: right">529 µs</td>
					<td style="text-align: right">-24 %</td>
			</tr>
			<tr>
					<td><code>GetUsers</code>, 1,000 users</td>
					<td style="text-align: right">6.53 ms</td>
					<td style="text-align: right">5.30 ms</td>
					<td style="text-align: right">-19 %</td>
			</tr>
			<tr>
					<td>Token, one user, groups, clients</td>
					<td style="text-align: right"></td>
					<td style="text-align: right"></td>
					<td style="text-align: right">not significant</td>
			</tr>
			<tr>
					<td><code>DecodeAccessToken</code></td>
					<td style="text-align: right">31.7 µs</td>
					<td style="text-align: right">32.2 µs</td>
					<td style="text-align: right">not significant</td>
			</tr>
	</tbody>
</table>
<p>Only the user lists get measurably faster. For the other endpoints the JSON part is too small next to HTTP handling and the in-process server. The geometric mean over all A/B time values is -22 %.</p>
<p>Allocations drop everywhere: geometric mean -40 %, <code>GetUsers</code> -44 %, clients -29 %, one user -19 %, token -9 %, <code>DecodeAccessToken</code> -21 %.</p>
<p>Live I only have the sequential <code>run.sh</code> comparison. Latency does not change significantly there: 1,000 users go from 39.8 to 38.1 ms with p=0.065, and the remaining differences are within noise. Allocations drop as offline.</p>
<p>So json/v2 saves allocations and some CPU in the client. That counts for throughput under load. The latency of a single call does not change, because Keycloak dominates it. On Go 1.27 the v2 engine is the default, see <a href="/blog/gocloak-performance-json-v2-http-clients/">Part 3</a>.</p>
<h2 id="v150-on-go-126-against-v151-on-go-127">v15.0 on Go 1.26 against v15.1 on Go 1.27</h2>
<p>The findings of this series went into gocloak v15.1.0 (<a href="https://github.com/Nerzal/gocloak/releases/tag/v15.1.0" rel="noopener">release notes</a>, released on 21 November 2026): Go 1.27 as minimum version, which makes json/v2 the default engine, 100 idle connections per host, and <code>SetDirectBodyRead()</code> as an opt-in. <code>./ab.sh ref main</code> compares the branch against main, with the baseline built on Go 1.26.2, interleaved as before.</p>
<p>Offline (n=10): <code>GetUsers</code> with 1,000 users -24 % time and -44 % allocations, clients -20 % and -29 %; geometric mean over all endpoints -21 % time and -27 % allocations. The pool benchmark drops from 37.2 to 15.8 µs per call (-57 %) and from 33.3 to 0.64 new connections per 1,000 calls.</p>
<p>Live against Keycloak (n=6): no latency change, because Keycloak dominates. Allocations drop by 10 % (token) to 27 % (user lists), bytes by 3 to 12 %, and with 16 parallel callers the new connections by 70 % (187 to 55 per 1,000 calls).</p>
<p>v15.1.0 has no breaking API changes. The models and the generated <code>GoCloakIface</code> are unchanged, and the only new export is <code>SetDirectBodyRead()</code>. Three things still change for users:</p>
<ul>
<li><code>go.mod</code> requires Go 1.27. With the default <code>GOTOOLCHAIN=auto</code> the go command downloads 1.27 itself; with <code>GOTOOLCHAIN=local</code> and an older Go the build fails.</li>
<li>The idle pool is 100 connections per host instead of GOMAXPROCS+1.</li>
<li>On Go 1.27 <code>encoding/json</code> can return different error texts for invalid JSON. If your code matches error strings, check it. <code>GOEXPERIMENT=nojsonv2</code> selects the old engine.</li>
</ul>
<p>If you look at the diff, the test files now write <code>PolicyRepresentation{Clients: []string{...}}</code> instead of going through the embedded <code>ClientPolicyRepresentation</code>. That is new Go 1.27 syntax: composite literals can set promoted fields of embedded structs directly, and the linter&rsquo;s <code>embedlit</code> modernize check asks for it. The struct is the same, and the old notation still compiles.</p>
<h2 id="four-lessons-from-the-final-run">Four lessons from the final run</h2>
<h3 id="a-cold-jvm-lies-to-you">A cold JVM lies to you</h3>
<p>In my very first live run, 1,000 users took 153 to 185 ms. In the final run it was 39 ms. Same Keycloak container, same data, same client. The difference is the JVM: Keycloak keeps getting faster over many requests while the JIT compiler optimizes hot paths and caches fill. The 300 warm-up calls per endpoint in the setup were not enough for the first run.</p>
<p>With a JVM server like Keycloak, warm up generously and compare several runs before you trust a number. A benchmark against a freshly started Keycloak measures the warm-up, not the steady state.</p>
<h3 id="one-benchmark-client-can-poison-the-next">One benchmark client can poison the next</h3>
<p>The first complete run failed in the live pool benchmark. After the default gocloak client with its massive connection churn, the following clients ran into dial timeouts against <code>[::1]:8080</code>. The churn had overloaded Docker Desktop&rsquo;s port forwarder on Windows. Even the large pool suddenly showed 300 dials per 1,000 calls and 1.1 ms instead of 0.2 ms per call. The previous client had ruined the conditions for the next one.</p>
<p>The fix is a configurable cool-down per target before each pool client: 2 seconds offline, 15 seconds live. After that the whole run went through without errors. If benchmarks run in a fixed order against shared infrastructure, check that a later candidate does not inherit the mess of an earlier one. Running them in a different order is a cheap test.</p>
<h3 id="git-bash-rewrites-arguments-that-start-with-a-slash">Git Bash rewrites arguments that start with a slash</h3>
<p><code>go tool benchstat -col /client</code> failed under Git Bash on Windows:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">parsing -col: syntax error: expected key
</span></span></code></pre></div><p>MSYS, the layer under Git Bash, converts arguments that look like absolute Unix paths into Windows paths. <code>/client</code> became something like <code>C:/Program Files/Git/client</code>. Setting <code>MSYS_NO_PATHCONV=1</code> turns that off:</p>
<div class="os-tabs">
<div class="os-tab" data-label="Linux / macOS">
<p class="os-tab-label">Linux / macOS</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="c1"># no conversion happens here, the variable is harmless</span>
</span></span><span class="line"><span class="cl">go tool benchstat -col /client results/offline-v1.txt
</span></span></code></pre></div>
</div>

<div class="os-tab" data-label="Windows (PowerShell)">
<p class="os-tab-label">Windows (PowerShell)</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="c"># PowerShell passes /client unchanged</span>
</span></span><span class="line"><span class="cl"><span class="n">go</span> <span class="n">tool</span> <span class="n">benchstat</span> <span class="n">-col</span> <span class="p">/</span><span class="n">client</span> <span class="n">results</span><span class="p">/</span><span class="nb">offline-v1</span><span class="p">.</span><span class="py">txt</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c"># in Git Bash on Windows instead:</span>
</span></span><span class="line"><span class="cl"><span class="c"># MSYS_NO_PATHCONV=1 go tool benchstat -col /client results/offline-v1.txt</span>
</span></span></code></pre></div>
</div>

</div>

<p>A smaller note: <code>run.sh</code> uses <code>set -o pipefail</code>, so a single failed benchmark aborts the rest of the run. That is intended. I prefer an aborted run over half a data set that looks complete.</p>
<h3 id="interleave-old-and-new">Interleave old and new</h3>
<p>The <code>run.sh</code> comparisons of the JSON engines ran the v1 suite and the v2 suite one after the other, minutes apart. The load on the machine changed in between and faked effects of up to ±40 %. <code>DecodeAccessToken</code> looked 35 % slower with json/v2 offline and 39 % faster live; the interleaved A/B run shows no difference. <code>go test -count</code> makes it worse, because it runs the same sub-benchmark eight times in a row, so a load spike hits all eight samples of one variant.</p>
<p>The same artifact produced an open question in my first draft of this post: the token response seemed to profit only through the direct v2 API (32.4 against 4.4 µs). In the A/B run the v1 API on the v2 engine is 74 % faster too (14.2 to 3.7 µs). The 32 µs came from a load phase.</p>
<p><code>benchmarks/ab.sh</code> builds both variants once with <code>go test -c</code> and runs them alternately for 10 rounds, one sample per round, with the order flipped every round. <a href="/blog/gocloak-performance-json-v2-http-clients/">Part 3</a> shows the loop. If you compare old against new on a machine whose load you do not control, interleave the runs.</p>
<h2 id="what-the-final-numbers-change">What the final numbers change</h2>
<p>The conclusions from Part 3 hold, with sharper numbers:</p>
<ul>
<li>Live, the HTTP client does not matter for latency. All Go stacks are within noise of each other; fasthttp saves 6 to 10 % on small calls.</li>
<li>The connection pool matters under parallel load: 2.6 times faster offline over TLS in the interleaved A/B run, 36 % faster live without TLS, and 98 % fewer new connections. v15.1.0 keeps 100 idle connections per host.</li>
<li>json/v2 cuts allocations by 9 to 44 % on every call. Through the whole gocloak path only the user lists get measurably faster (19 to 24 % offline), and live latency does not change.</li>
<li>gocloak allocates 30 to 60 % more bytes than plain resty because of the body limit handling. <code>SetDirectBodyRead()</code> in v15.1.0 cuts 39 % for 1,000 users.</li>
</ul>
<p>The question that remained: where exactly does the time go, and why does gocloak allocate so much? That is what the profiles in <a href="/blog/gocloak-pprof-profiling/">Part 5</a> answer.</p>
]]></content:encoded></item><item><title>How fast can gocloak talk to Keycloak? json/v2, fasthttp and the connection pool</title><link>https://blog.noobygames.de/blog/gocloak-performance-json-v2-http-clients/</link><pubDate>Sun, 22 Nov 2026 06:30:00 +0100</pubDate><dc:creator>Tobias Theel</dc:creator><guid isPermaLink="true">https://blog.noobygames.de/blog/gocloak-performance-json-v2-http-clients/</guid><category>Software Engineering</category><category>go</category><category>keycloak</category><category>gocloak</category><category>performance</category><category>benchmark</category><category>json</category><category>encoding-json-v2</category><category>fasthttp</category><category>resty</category><category>http</category><category>open-source</category><description>Benchmarking gocloak against Keycloak 26: encoding/json/v2 decodes Keycloak payloads 26 to 74 % faster with no code change but encodes small structs more slowly, fasthttp wins micro-benchmarks but barely matters against a real Keycloak, and resty's default connection pool is the real bottleneck under parallel load. Go 1.27 makes json/v2 the default, and gocloak v15.1.0 fixes the pool.</description><content:encoded><![CDATA[<blockquote>
<p><strong>Series: The gocloak universe.</strong> <a href="/blog/gocloak-mcp-first-mcp-server-homebrew/">Part 1: gocloak-mcp</a> · <a href="/blog/gocloak-auth-proxy-keycloak/">Part 2: gocloak-auth-proxy</a> · Part 3: gocloak performance (you are here) · <a href="/blog/gocloak-performance-final-benchmarks/">Part 4: final benchmark numbers</a> · <a href="/blog/gocloak-pprof-profiling/">Part 5: pprof</a></p>
</blockquote>
<aside class="tldr" aria-label="Key takeaways">
<p class="tldr-title">TL;DR</p>
<ul>
<li>The json/v2 engine decodes Keycloak payloads 26 to 74 % faster without a code change in gocloak, but encodes small structs 39 to 51 % more slowly.</li>
<li>fasthttp is the fastest stack in most micro-benchmarks, but against a real Keycloak it saves only 6 to 10 % on small calls, nothing on large ones, and it cannot speak HTTP/2.</li>
<li>resty&rsquo;s default <code>MaxIdleConnsPerHost</code> of <code>GOMAXPROCS + 1</code> is the bottleneck under parallel load; a pool of 256 made gocloak 2.6 times as fast in an interleaved A/B run.</li>
<li>gocloak v15.1.0 requires Go 1.27, where json/v2 is the default engine, sets both idle connection limits to 100 and adds the opt-in <code>SetDirectBodyRead()</code>, which cuts bytes per call for 1,000 users by 39 %.</li>
<li>Every old-against-new number in this post comes from an interleaved A/B run, because sequential runs on my loaded machine faked effects of up to ±40 %.</li>
</ul>

</aside>

<p>Can gocloak, the Go client for the Keycloak REST API, get &ldquo;massively&rdquo; faster at talking to Keycloak? I wanted a number for that, not a gut feeling, so I checked three things:</p>
<ol>
<li>Does the new <a href="https://pkg.go.dev/encoding/json/v2" rel="noopener"><code>encoding/json/v2</code></a> help with typical Keycloak payloads?</li>
<li>Does a different HTTP client, <a href="https://github.com/valyala/fasthttp" rel="noopener">fasthttp</a> or something else, help?</li>
<li>Are there other levers?</li>
</ol>
<p>The short answer: json/v2 decodes Keycloak payloads 26 to 74 % faster without a single code change (user lists about a third), but encodes small structs 39 to 51 % more slowly. fasthttp is the fastest stack in most micro-benchmarks, but against a real Keycloak it saves at most a tenth on small calls and nothing on large ones. And the biggest problem under parallel load is a default in the connection pool that nobody looks at. Two of the results already changed gocloak: v15.1.0 requires Go 1.27, where json/v2 is the default engine, and keeps 100 idle connections per host.</p>
<p>This post covers how I approached it, what went wrong along the way and the results. <a href="/blog/gocloak-performance-final-benchmarks/">Part 4</a> has the complete benchstat tables and what the final run taught me, <a href="/blog/gocloak-pprof-profiling/">Part 5</a> the CPU and memory profiles.</p>
<p>The setup: gocloak v15, Go 1.26.2, <a href="https://github.com/go-resty/resty" rel="noopener">resty</a> v2.17.2 as the HTTP layer, Keycloak 26.8.2 in Docker, on an AMD Ryzen AI 9 HX 370 (24 logical cores) with Windows 11.</p>
<h2 id="read-the-code-before-you-measure">Read the code before you measure</h2>
<p>All gocloak calls go through one shared resty client. <code>NewClient</code> creates it with <code>resty.New()</code>, a timeout, a response body limit and a redirect policy that only follows redirects to the same origin. resty reads the whole response body into memory and then calls <code>json.Unmarshal</code> on it. Nothing is streamed.</p>
<p>Before writing a single benchmark I checked the facts I thought I knew, because half of them were wrong or outdated:</p>
<ul>
<li><code>go list encoding/json/v2</code> without any flag answers with <code>build constraints exclude all Go files</code>. In Go 1.26, json/v2 is still behind <code>GOEXPERIMENT=jsonv2</code>. Go 1.27 changed that, which I missed at first; more on that below.</li>
<li>resty v3 exists only as a release candidate (v3.0.0-rc.4), so it was out.</li>
<li>fasthttp v1.79.0 is current.</li>
<li>resty has <code>SetJSONMarshaler</code> and <code>SetJSONUnmarshaler</code>. A user can swap the JSON implementation without gocloak changing anything.</li>
</ul>
<p>I also checked the usual suspects for hidden overhead. gocloak caches the JWKS certificates, parses the public keys once per fetch and keeps them in a map by <code>kid</code>, so token verification has no hidden network call or parsing step. The server version is cached too.</p>
<p>Reading resty&rsquo;s source turned up the first real finding. Its default transport sets <code>MaxIdleConnsPerHost</code> to <code>GOMAXPROCS + 1</code>. Keycloak is exactly one host for gocloak, and since <a href="https://go.dev/doc/go1.25#container-aware-gomaxprocs" rel="noopener">Go 1.25 GOMAXPROCS respects cgroup CPU limits</a>. A pod with a CPU limit of 1 keeps at most two idle connections to Keycloak open. More on why that hurts below.</p>
<h2 id="the-benchmark-setup">The benchmark setup</h2>
<p>The benchmarks live in their own Go module under <a href="https://github.com/Nerzal/gocloak/tree/v15.1.0/benchmarks" rel="noopener"><code>benchmarks/</code></a> in the gocloak repository, with its own <code>go.mod</code> and a <code>replace</code> directive pointing at the main module. That way fasthttp and benchstat never end up in the library&rsquo;s dependencies.</p>
<p>There are two stages:</p>
<ul>
<li><strong>Offline:</strong> an in-process fake Keycloak built with <a href="https://pkg.go.dev/net/http/httptest" rel="noopener"><code>net/http/httptest</code></a> serves realistic payloads on the real gocloak URL paths. This runs without Docker, is reproducible and isolates the client overhead.</li>
<li><strong>Live:</strong> the same benchmarks against the real Keycloak in Docker, behind the build tag <code>keycloak</code>. The setup creates 1,000 users and 20 groups with 5 subgroups each, then warms Keycloak up with 300 calls per endpoint so the JIT and the caches are hot. Afterwards it deletes the data again, and it also cleans up leftovers of an aborted run before it starts. The admin token lives 60 seconds in the master realm, so a background goroutine renews it and no login ever lands inside a measurement.</li>
</ul>
<p>The payloads are what an application actually gets from Keycloak: a token response with really signed RS256 JWTs, the JWKS, a single user, lists of 100 and 1,000 users, a group tree, the clients and the full realm export from <code>testdata/gocloak-realm.json</code> (73 KB, a real Keycloak export).</p>
<p>I compared five HTTP stacks:</p>
<table>
	<thead>
			<tr>
					<th>Stack</th>
					<th>What it shows</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>gocloak (default)</td>
					<td>What users get today</td>
			</tr>
			<tr>
					<td>gocloak with an idle pool of 256</td>
					<td>Effect of a single transport setting</td>
			</tr>
			<tr>
					<td>plain resty</td>
					<td>gocloak&rsquo;s own overhead, subtracted</td>
			</tr>
			<tr>
					<td>net/http, tuned pool, streaming decoder</td>
					<td>What the standard library can do</td>
			</tr>
			<tr>
					<td>fasthttp</td>
					<td>The usual &ldquo;just use fasthttp&rdquo; suggestion</td>
			</tr>
	</tbody>
</table>
<p>A script, <code>run.sh</code>, runs everything with fixed parameters: <code>COUNT=10</code>, <code>GOMAXPROCS=4</code>, <code>-benchtime 1s</code>. Every suite runs once with the standard JSON and once with <code>GOEXPERIMENT=jsonv2</code>. Raw output, benchstat comparisons, the Go version and the commit hash go into <code>results/&lt;timestamp&gt;/</code>. The script says in its header to run it only on an otherwise idle machine.</p>
<p><a href="https://pkg.go.dev/golang.org/x/perf/cmd/benchstat" rel="noopener">benchstat</a> is wired in as a Go tool dependency (<code>go tool benchstat</code>). If you want it globally:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">go install golang.org/x/perf/cmd/benchstat@latest
</span></span></code></pre></div><p>Running the suites looks like this. <code>run.sh</code> needs a Bash, so on Windows use Git Bash or WSL, or call <code>go test</code> directly:</p>
<div class="os-tabs">
<div class="os-tab" data-label="Linux / macOS">
<p class="os-tab-label">Linux / macOS</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="nb">cd</span> benchmarks
</span></span><span class="line"><span class="cl">./run.sh offline              <span class="c1"># no Docker needed</span>
</span></span><span class="line"><span class="cl">./run.sh live                 <span class="c1"># starts Keycloak via docker compose if needed</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># single suite by hand, once per JSON engine</span>
</span></span><span class="line"><span class="cl">go <span class="nb">test</span> -run <span class="s1">&#39;^$&#39;</span> -bench <span class="s1">&#39;^BenchmarkJSON&#39;</span> -benchmem -count <span class="m">10</span> -cpu <span class="m">4</span> . &gt; v1.txt
</span></span><span class="line"><span class="cl"><span class="nv">GOEXPERIMENT</span><span class="o">=</span>jsonv2 go <span class="nb">test</span> -run <span class="s1">&#39;^$&#39;</span> -bench <span class="s1">&#39;^BenchmarkJSON&#39;</span> -benchmem -count <span class="m">10</span> -cpu <span class="m">4</span> . &gt; v2.txt
</span></span><span class="line"><span class="cl">go tool benchstat <span class="nv">v1engine</span><span class="o">=</span>v1.txt <span class="nv">v2engine</span><span class="o">=</span>v2.txt
</span></span></code></pre></div>
</div>

<div class="os-tab" data-label="Windows (PowerShell)">
<p class="os-tab-label">Windows (PowerShell)</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nb">cd </span><span class="n">benchmarks</span>
</span></span><span class="line"><span class="cl"><span class="n">go</span> <span class="n">test</span> <span class="n">-run</span> <span class="s1">&#39;^$&#39;</span> <span class="n">-bench</span> <span class="s1">&#39;^BenchmarkJSON&#39;</span> <span class="n">-benchmem</span> <span class="n">-count</span> <span class="mf">10</span> <span class="n">-cpu</span> <span class="mf">4</span> <span class="p">.</span> <span class="p">&gt;</span> <span class="n">v1</span><span class="p">.</span><span class="py">txt</span>
</span></span><span class="line"><span class="cl"><span class="nv">$env:GOEXPERIMENT</span> <span class="p">=</span> <span class="s2">&#34;jsonv2&#34;</span>
</span></span><span class="line"><span class="cl"><span class="n">go</span> <span class="n">test</span> <span class="n">-run</span> <span class="s1">&#39;^$&#39;</span> <span class="n">-bench</span> <span class="s1">&#39;^BenchmarkJSON&#39;</span> <span class="n">-benchmem</span> <span class="n">-count</span> <span class="mf">10</span> <span class="n">-cpu</span> <span class="mf">4</span> <span class="p">.</span> <span class="p">&gt;</span> <span class="n">v2</span><span class="p">.</span><span class="py">txt</span>
</span></span><span class="line"><span class="cl"><span class="nb">Remove-Item</span> <span class="n">Env</span><span class="err">:</span><span class="n">GOEXPERIMENT</span>
</span></span><span class="line"><span class="cl"><span class="n">go</span> <span class="n">tool</span> <span class="n">benchstat</span> <span class="n">v1engine</span><span class="p">=</span><span class="n">v1</span><span class="p">.</span><span class="py">txt</span> <span class="n">v2engine</span><span class="p">=</span><span class="n">v2</span><span class="p">.</span><span class="py">txt</span>
</span></span></code></pre></div>
</div>

</div>

<h3 id="traps-in-the-methodology">Traps in the methodology</h3>
<p>The in-process server burns CPU too, on the same cores as the client. That inflates the totals, so I compare absolute differences in ns/op and allocs/op between clients, not percentages of the total.</p>
<p>The bigger problem was my own machine. Other coding agents were running in parallel, and single runs scattered wildly: one JSON benchmark jumped to 2.4 times its value between two runs. A single number from a busy machine says nothing. So every result in this post is a benchstat median (n=8, or n=10 for the A/B runs), which reports the median, a confidence interval and a p-value. Even so, time values on that machine scatter by up to 30 to 40 %. Allocations and bytes per operation are deterministic, so I trust those more. The script exists so anyone can repeat the run on an idle machine.</p>
<p>Medians do not protect against a load change between two runs. My first comparison of the JSON engines ran the v1 suite and then, minutes later, the v2 suite. The load on the machine changed in between, and that alone faked effects of up to ±40 %. The clearest example was local token verification: with json/v2 it looked 35 % slower offline and 39 % faster live. In a fair comparison there is no difference at all.</p>
<p>So every old-against-new number in this post comes from an interleaved A/B run (<code>benchmarks/ab.sh</code>). Both variants are compiled once as test binaries, then run alternately for 10 rounds with one sample each, and the order flips every round. A load spike then hits both variants equally:</p>
<div class="os-tabs">
<div class="os-tab" data-label="Linux / macOS">
<p class="os-tab-label">Linux / macOS</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">go <span class="nb">test</span> -c -o v1.test .
</span></span><span class="line"><span class="cl"><span class="nv">GOEXPERIMENT</span><span class="o">=</span>jsonv2 go <span class="nb">test</span> -c -o v2.test .
</span></span><span class="line"><span class="cl"><span class="k">for</span> round in <span class="k">$(</span>seq <span class="m">1</span> 10<span class="k">)</span><span class="p">;</span> <span class="k">do</span>
</span></span><span class="line"><span class="cl">  <span class="k">if</span> <span class="o">[</span> <span class="k">$((</span>round <span class="o">%</span> <span class="m">2</span><span class="k">))</span> -eq <span class="m">1</span> <span class="o">]</span><span class="p">;</span> <span class="k">then</span> <span class="nv">order</span><span class="o">=</span><span class="s2">&#34;v1 v2&#34;</span><span class="p">;</span> <span class="k">else</span> <span class="nv">order</span><span class="o">=</span><span class="s2">&#34;v2 v1&#34;</span><span class="p">;</span> <span class="k">fi</span>
</span></span><span class="line"><span class="cl">  <span class="k">for</span> variant in <span class="nv">$order</span><span class="p">;</span> <span class="k">do</span>
</span></span><span class="line"><span class="cl">    ./<span class="nv">$variant</span>.test -test.run <span class="s1">&#39;^$&#39;</span> -test.bench <span class="s1">&#39;^BenchmarkJSON&#39;</span> -test.benchmem -test.count <span class="m">1</span> -test.cpu <span class="m">4</span> &gt;&gt; <span class="nv">$variant</span>.txt
</span></span><span class="line"><span class="cl">  <span class="k">done</span>
</span></span><span class="line"><span class="cl"><span class="k">done</span>
</span></span><span class="line"><span class="cl">go tool benchstat <span class="nv">v1engine</span><span class="o">=</span>v1.txt <span class="nv">v2engine</span><span class="o">=</span>v2.txt
</span></span></code></pre></div>
</div>

<div class="os-tab" data-label="Windows (PowerShell)">
<p class="os-tab-label">Windows (PowerShell)</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">go</span> <span class="n">test</span> <span class="n">-c</span> <span class="n">-o</span> <span class="n">v1</span><span class="p">.</span><span class="py">test</span><span class="p">.</span><span class="py">exe</span> <span class="p">.</span>
</span></span><span class="line"><span class="cl"><span class="nv">$env:GOEXPERIMENT</span> <span class="p">=</span> <span class="s2">&#34;jsonv2&#34;</span><span class="p">;</span> <span class="n">go</span> <span class="n">test</span> <span class="n">-c</span> <span class="n">-o</span> <span class="n">v2</span><span class="p">.</span><span class="py">test</span><span class="p">.</span><span class="py">exe</span> <span class="p">.;</span> <span class="nb">Remove-Item</span> <span class="n">Env</span><span class="err">:</span><span class="n">GOEXPERIMENT</span>
</span></span><span class="line"><span class="cl"><span class="k">foreach</span> <span class="p">(</span><span class="nv">$round</span> <span class="k">in</span> <span class="mf">1</span><span class="p">.</span><span class="mf">.10</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">  <span class="nv">$order</span> <span class="p">=</span> <span class="k">if</span> <span class="p">(</span><span class="nv">$round</span> <span class="p">%</span> <span class="mf">2</span><span class="p">)</span> <span class="p">{</span> <span class="s2">&#34;v1&#34;</span><span class="p">,</span> <span class="s2">&#34;v2&#34;</span> <span class="p">}</span> <span class="k">else</span> <span class="p">{</span> <span class="s2">&#34;v2&#34;</span><span class="p">,</span> <span class="s2">&#34;v1&#34;</span> <span class="p">}</span>
</span></span><span class="line"><span class="cl">  <span class="k">foreach</span> <span class="p">(</span><span class="nv">$variant</span> <span class="k">in</span> <span class="nv">$order</span><span class="p">)</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="p">&amp;</span> <span class="s2">&#34;.\</span><span class="nv">$variant</span><span class="s2">.test.exe&#34;</span> <span class="n">-test</span><span class="p">.</span><span class="py">run</span> <span class="s1">&#39;^$&#39;</span> <span class="n">-test</span><span class="p">.</span><span class="py">bench</span> <span class="s1">&#39;^BenchmarkJSON&#39;</span> <span class="n">-test</span><span class="p">.</span><span class="py">benchmem</span> <span class="n">-test</span><span class="p">.</span><span class="py">count</span> <span class="mf">1</span> <span class="n">-test</span><span class="p">.</span><span class="py">cpu</span> <span class="mf">4</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">      <span class="nb">Out-File</span> <span class="n">-Append</span> <span class="n">-Encoding</span> <span class="n">utf8</span> <span class="s2">&#34;</span><span class="nv">$variant</span><span class="s2">.txt&#34;</span>
</span></span><span class="line"><span class="cl">  <span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl"><span class="n">go</span> <span class="n">tool</span> <span class="n">benchstat</span> <span class="n">v1engine</span><span class="p">=</span><span class="n">v1</span><span class="p">.</span><span class="py">txt</span> <span class="n">v2engine</span><span class="p">=</span><span class="n">v2</span><span class="p">.</span><span class="py">txt</span>
</span></span></code></pre></div>
</div>

</div>

<p><code>go test -count 8</code> does the opposite: it runs the same sub-benchmark eight times in a row, so one load spike lands in all eight samples of one variant and none of the other.</p>
<p>fasthttp returns pooled buffers that get reused after the request is released. I checked that this is safe here: <code>json.Unmarshal</code> copies the strings out of the buffer before the buffer goes back to the pool.</p>
<h2 id="things-that-broke-along-the-way">Things that broke along the way</h2>
<h3 id="fasthttp-meets-http2">fasthttp meets HTTP/2</h3>
<p>The first fasthttp run against the TLS test server failed with:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">http2: server: error reading preface from client: bogus greeting
</span></span></code></pre></div><p>The test server&rsquo;s TLS config offers <code>h2</code> via ALPN, and fasthttp speaks only HTTP/1.1. The fix for the benchmark was to set <code>NextProtos</code> to <code>[&quot;http/1.1&quot;]</code> for fasthttp. For production that means fasthttp cannot use HTTP/2 at all.</p>
<h3 id="the-pool-benchmark-that-took-down-the-listener">The pool benchmark that took down the listener</h3>
<p>The pool benchmark sends many parallel callers over TLS with HTTP/1.1. With the gocloak/resty default pool it failed outright. 32 to 192 goroutines shared 5 or 25 idle connections, so connections were closed and re-dialed constantly, each with a new TLS handshake, until the Windows listener started refusing new connections:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-text" data-lang="text"><span class="line"><span class="cl">connectex: No connection could be made because the target machine actively refused it.
</span></span></code></pre></div><p>net/http and fasthttp with a large pool ran through the same test without errors. I changed the benchmark so it counts errors and new connections as metrics (<code>dials/1k-op</code> and <code>fails/1k-op</code>) instead of aborting, and gave each client two seconds of cool-down before its measurement, so it does not inherit a full accept backlog from the previous client.</p>
<p>My first version of that cool-down sat inside the measured loop. With <code>b.N = 1</code> in the first ramp-up round that meant two seconds per operation, which skewed how the testing package scaled <code>b.N</code>. The fix: sleep only in the first round, before <code>b.ResetTimer()</code>.</p>
<h2 id="result-1-encodingjsonv2">Result 1: encoding/json/v2</h2>
<p>With <code>GOEXPERIMENT=jsonv2</code>, the old <code>encoding/json</code> API (v1) runs on the new v2 engine. gocloak&rsquo;s code stays exactly as it is, and the decoding gets faster. On Go 1.27 this happens without the flag, see below.</p>










<figure class="diagram">
    <div class="diagram-canvas" role="img" aria-label="Unmarshal with the v1 API, default build vs `GOEXPERIMENT=jsonv2`. Interleaved A/B run, median of 10, GOMAXPROCS=4.">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 720 452" width="720" height="452">
<text x="20" y="28" class="d-t d-bold" font-size="15">Unmarshal time, encoding/json v1 API: v1 engine vs v2 engine</text>
<text x="20" y="48" class="d-m" font-size="11.5">Interleaved A/B run, median of 10, GOMAXPROCS=4. Bars relative to the v1 engine (shorter is faster).</text>
<rect x="20" y="62" width="12" height="12" rx="3" fill="#9aa0a6"/><text x="38" y="72" class="d-t" font-size="11.5">default build (v1 engine)</text>
<rect x="222" y="62" width="12" height="12" rx="3" fill="#4285f4"/><text x="240" y="72" class="d-t" font-size="11.5">GOEXPERIMENT=jsonv2 (v2 engine)</text>
<line x1="190.0" y1="84" x2="190.0" y2="412" class="d-divider"/><text x="190.0" y="428" class="d-m" font-size="11" text-anchor="middle">0%</text>
<line x1="290.0" y1="84" x2="290.0" y2="412" class="d-divider"/><text x="290.0" y="428" class="d-m" font-size="11" text-anchor="middle">25%</text>
<line x1="390.0" y1="84" x2="390.0" y2="412" class="d-divider"/><text x="390.0" y="428" class="d-m" font-size="11" text-anchor="middle">50%</text>
<line x1="490.0" y1="84" x2="490.0" y2="412" class="d-divider"/><text x="490.0" y="428" class="d-m" font-size="11" text-anchor="middle">75%</text>
<line x1="590.0" y1="84" x2="590.0" y2="412" class="d-divider"/><text x="590.0" y="428" class="d-m" font-size="11" text-anchor="middle">100%</text>
<text x="180" y="111" class="d-t" font-size="12" text-anchor="end">Token response</text>
<path d="M190 92 H587.0 Q590.0 92 590.0 95 V103 Q590.0 106 587.0 106 H190 Z" fill="#9aa0a6"/>
<text x="596" y="103" class="d-m" font-size="11">14.2 µs</text>
<path d="M190 108 H291.2 Q294.2 108 294.2 111 V119 Q294.2 122 291.2 122 H190 Z" fill="#4285f4"/>
<text x="300.2" y="119" class="d-t" font-size="11">3.7 µs <tspan class="d-m">-74%</tspan></text>
<text x="180" y="151" class="d-t" font-size="12" text-anchor="end">Certs (JWKS)</text>
<path d="M190 132 H587.0 Q590.0 132 590.0 135 V143 Q590.0 146 587.0 146 H190 Z" fill="#9aa0a6"/>
<text x="596" y="143" class="d-m" font-size="11">5.2 µs</text>
<path d="M190 148 H333.2 Q336.2 148 336.2 151 V159 Q336.2 162 333.2 162 H190 Z" fill="#4285f4"/>
<text x="342.2" y="159" class="d-t" font-size="11">1.9 µs <tspan class="d-m">-65%</tspan></text>
<text x="180" y="191" class="d-t" font-size="12" text-anchor="end">One user</text>
<path d="M190 172 H587.0 Q590.0 172 590.0 175 V183 Q590.0 186 587.0 186 H190 Z" fill="#9aa0a6"/>
<text x="596" y="183" class="d-m" font-size="11">4.1 µs</text>
<path d="M190 188 H440.7 Q443.7 188 443.7 191 V199 Q443.7 202 440.7 202 H190 Z" fill="#4285f4"/>
<text x="449.7" y="199" class="d-t" font-size="11">2.6 µs <tspan class="d-m">-36%</tspan></text>
<text x="180" y="231" class="d-t" font-size="12" text-anchor="end">100 users</text>
<path d="M190 212 H587.0 Q590.0 212 590.0 215 V223 Q590.0 226 587.0 226 H190 Z" fill="#9aa0a6"/>
<text x="596" y="223" class="d-m" font-size="11">413 µs</text>
<path d="M190 228 H448.5 Q451.5 228 451.5 231 V239 Q451.5 242 448.5 242 H190 Z" fill="#4285f4"/>
<text x="457.5" y="239" class="d-t" font-size="11">270 µs <tspan class="d-m">-35%</tspan></text>
<text x="180" y="271" class="d-t" font-size="12" text-anchor="end">1000 users</text>
<path d="M190 252 H587.0 Q590.0 252 590.0 255 V263 Q590.0 266 587.0 266 H190 Z" fill="#9aa0a6"/>
<text x="596" y="263" class="d-m" font-size="11">4.04 ms</text>
<path d="M190 268 H458.3 Q461.3 268 461.3 271 V279 Q461.3 282 458.3 282 H190 Z" fill="#4285f4"/>
<text x="467.3" y="279" class="d-t" font-size="11">2.74 ms <tspan class="d-m">-32%</tspan></text>
<text x="180" y="311" class="d-t" font-size="12" text-anchor="end">Group tree</text>
<path d="M190 292 H587.0 Q590.0 292 590.0 295 V303 Q590.0 306 587.0 306 H190 Z" fill="#9aa0a6"/>
<text x="596" y="303" class="d-m" font-size="11">102 µs</text>
<path d="M190 308 H508.6 Q511.6 308 511.6 311 V319 Q511.6 322 508.6 322 H190 Z" fill="#4285f4"/>
<text x="517.6" y="319" class="d-t" font-size="11">82 µs <tspan class="d-m">n.s.</tspan></text>
<text x="180" y="351" class="d-t" font-size="12" text-anchor="end">Clients</text>
<path d="M190 332 H587.0 Q590.0 332 590.0 335 V343 Q590.0 346 587.0 346 H190 Z" fill="#9aa0a6"/>
<text x="596" y="343" class="d-m" font-size="11">91 µs</text>
<path d="M190 348 H420.0 Q423.0 348 423.0 351 V359 Q423.0 362 420.0 362 H190 Z" fill="#4285f4"/>
<text x="429.0" y="359" class="d-t" font-size="11">53 µs <tspan class="d-m">-42%</tspan></text>
<text x="180" y="391" class="d-t" font-size="12" text-anchor="end">Realm export</text>
<path d="M190 372 H587.0 Q590.0 372 590.0 375 V383 Q590.0 386 587.0 386 H190 Z" fill="#9aa0a6"/>
<text x="596" y="383" class="d-m" font-size="11">472 µs</text>
<path d="M190 388 H483.6 Q486.6 388 486.6 391 V399 Q486.6 402 483.6 402 H190 Z" fill="#4285f4"/>
<text x="492.6" y="399" class="d-t" font-size="11">350 µs <tspan class="d-m">-26%</tspan></text>
</svg>

    </div>
    <figcaption class="diagram-caption">Unmarshal with the v1 API, default build vs <code>GOEXPERIMENT=jsonv2</code>. Interleaved A/B run, median of 10, GOMAXPROCS=4.</figcaption>
</figure>

<table>
	<thead>
			<tr>
					<th>Unmarshal</th>
					<th style="text-align: right">v1 engine</th>
					<th style="text-align: right">v2 engine</th>
					<th style="text-align: right">Change</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>Token response</td>
					<td style="text-align: right">14.2 µs</td>
					<td style="text-align: right">3.7 µs</td>
					<td style="text-align: right">-74 %</td>
			</tr>
			<tr>
					<td>Certs (JWKS)</td>
					<td style="text-align: right">5.2 µs</td>
					<td style="text-align: right">1.9 µs</td>
					<td style="text-align: right">-65 %</td>
			</tr>
			<tr>
					<td>One user</td>
					<td style="text-align: right">4.1 µs</td>
					<td style="text-align: right">2.6 µs</td>
					<td style="text-align: right">-36 %</td>
			</tr>
			<tr>
					<td>100 users</td>
					<td style="text-align: right">413 µs</td>
					<td style="text-align: right">270 µs</td>
					<td style="text-align: right">-35 %</td>
			</tr>
			<tr>
					<td>1,000 users</td>
					<td style="text-align: right">4.04 ms</td>
					<td style="text-align: right">2.74 ms</td>
					<td style="text-align: right">-32 %</td>
			</tr>
			<tr>
					<td>Group tree</td>
					<td style="text-align: right">102 µs</td>
					<td style="text-align: right">82 µs</td>
					<td style="text-align: right">not significant</td>
			</tr>
			<tr>
					<td>Clients</td>
					<td style="text-align: right">91 µs</td>
					<td style="text-align: right">53 µs</td>
					<td style="text-align: right">-42 %</td>
			</tr>
			<tr>
					<td>Realm export</td>
					<td style="text-align: right">472 µs</td>
					<td style="text-align: right">350 µs</td>
					<td style="text-align: right">-26 %</td>
			</tr>
	</tbody>
</table>
<p>The token response, three long JWT strings, gains the most. User lists get about a third faster.</p>
<p>Encoding goes the other way. With the v1 API on the v2 engine, marshalling a new user takes 2.00 instead of 1.44 µs (+39 %) and a client 2.60 instead of 1.72 µs (+51 %); the realm export is level (not significant). For request bodies that does not matter in practice, because Keycloak needs milliseconds to process them.</p>
<p>Allocations are deterministic and need no A/B run. The user lists allocate 44 % fewer objects, marshalling the realm drops from 1,220 to 197 allocations (-84 %), and across all JSON and HTTP benchmarks the geometric mean is -40 %.</p>
<p>My first, sequential run had shown -65 % for 1,000 users and -59 % on average. The load change between the runs inflated those numbers, so I no longer use them.</p>
<h3 id="is-the-output-the-same">Is the output the same?</h3>
<p>Speed is worthless if the decoded structs differ. A dedicated test, <code>TestJSONv2Equivalence</code>, decodes every payload with v1 and with the direct v2 API and compares the results with <code>reflect.DeepEqual</code>. Everything is identical, including gocloak&rsquo;s custom types <code>StringOrArray</code> and <code>EnforcedString</code>. That test means most for the realm export and the clients, which are real Keycloak output; the other payloads come from gocloak&rsquo;s own <code>json.Marshal</code>, so their field names match trivially. The stronger evidence is the complete gocloak integration test suite, which ran green under <code>GOEXPERIMENT=jsonv2</code> against the real Keycloak.</p>
<h3 id="what-go-127-changes">What Go 1.27 changes</h3>
<p>Everything above was measured with Go 1.26.2, the version installed on my machine. I checked whether json/v2 needs a flag, but not whether 1.26 was still the current Go. It was not. In Go 1.27 (1.27.4 at the time of writing) JSONv2 is part of the baseline experiment set: <code>encoding/json</code> runs on the v2 engine by default, and <code>encoding/json/v2</code> can be imported without a flag. I only noticed when someone asked later why I was measuring with an older toolchain.</p>
<p>So I repeated the engine comparison on Go 1.27.4, with <code>GOEXPERIMENT=nojsonv2</code> as the old baseline (interleaved A/B, n=10). Unmarshalling: token response -70 %, JWKS -61 %, one user -37 %, 100 users -30 %, 1,000 users -35 %, clients -39 %, realm export -28 %. Marshalling a user +50 %, a client +44 %. Through gocloak, <code>GetUsers</code> gets 27 % faster for 1,000 users and 19 % for 100. Allocations drop by 40 % on geometric mean. The magnitudes match the experiment on Go 1.26; only the reason changes.</p>
<p>gocloak v15.1.0 (<a href="https://github.com/Nerzal/gocloak/releases/tag/v15.1.0" rel="noopener">release notes</a>, released on 21 November 2026) requires Go 1.27, which makes the v2 engine the baseline for every user without anyone setting a flag. If you stay on an older gocloak with Go 1.26, <code>GOEXPERIMENT=jsonv2</code> gives you the same engine.</p>
<p>If you use the v2 API directly, be aware that its defaults differ from v1: field names match case-sensitively, and duplicate names and invalid UTF-8 are rejected. The <a href="https://pkg.go.dev/encoding/json/v2" rel="noopener">package documentation</a> lists all differences. v1 code under the experiment flag keeps the v1 behavior, because the v1 API runs the v2 engine with v1-compatible options. When decoding the Keycloak payloads, none of this changed anything.</p>
<h3 id="why-gocloak-keeps-the-v1-api">Why gocloak keeps the v1 API</h3>
<p>The gains above come from the engine alone: gocloak still calls <code>encoding/json</code>, and on Go 1.27 that runs on the v2 engine. I also measured the direct <code>encoding/json/v2</code> API against the v1 API, both on the v2 engine. This was a single run with n=8, not interleaved, so it is less reliable than the A/B numbers. Decoding one user or the JWKS got 28 to 43 % faster with the v2 API. User lists, groups, clients and the realm export showed no significant difference. Encoding got 13 % faster and needed 45 to 57 % fewer allocations. The token response looked 86 % faster, but that value scattered by ±24 % and the v1 API on the v2 engine was already at 4 µs, so I do not count it.</p>
<p><code>TestJSONv2Equivalence</code> shows that the v2 API decodes every payload exactly like v1. Encoding is different: nil slices become <code>[]</code> instead of <code>null</code>, <code>omitempty</code> omits different values, and field names match case-sensitively. For a Keycloak client that matters, because Keycloak treats a field missing from a PUT body as &ldquo;keep the current value&rdquo;. If the encoding changes, an update can change different things than before. With <code>json.DefaultOptionsV1()</code> the v2 API behaves like v1 again, and then the advantage is gone too.</p>
<p>So gocloak stays on the v1 API. If you want v2 for request bodies anyway, you can set it on the resty client with <code>client.RestyClient().SetJSONMarshaler(...)</code>, without a change in gocloak. The big gain came for free from the engine. The new API would only help where Keycloak dominates the call anyway: small request bodies.</p>
<h2 id="result-2-http-clients">Result 2: HTTP clients</h2>
<p>All numbers below are benchstat medians from the final run (n=8, <code>GOMAXPROCS=4</code>). The machine was still busy, so time values scatter by up to 30 to 40 %, while allocations are deterministic. <a href="/blog/gocloak-performance-final-benchmarks/">Part 4</a> has the complete tables; here are the results that matter.</p>
<h3 id="offline-bytes-tell-more-than-time">Offline: bytes tell more than time</h3>
<p>With the fake Keycloak and one caller at a time, the time values jumped around from endpoint to endpoint. Plain resty was 49 % faster than gocloak for 100 users and 27 % slower for a single user. That is the noise of a loaded machine, not a pattern. The bytes per call are reliable:</p>
<table>
	<thead>
			<tr>
					<th>1,000 users, offline</th>
					<th style="text-align: right">Bytes per call</th>
					<th style="text-align: right">vs gocloak</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>gocloak</td>
					<td style="text-align: right">3.88 MiB</td>
					<td style="text-align: right"></td>
			</tr>
			<tr>
					<td>plain resty</td>
					<td style="text-align: right">2.42 MiB</td>
					<td style="text-align: right">-38 %</td>
			</tr>
			<tr>
					<td>net/http</td>
					<td style="text-align: right">2.44 MiB</td>
					<td style="text-align: right">-37 %</td>
			</tr>
			<tr>
					<td>fasthttp</td>
					<td style="text-align: right">1.93 MiB</td>
					<td style="text-align: right">-50 %</td>
			</tr>
	</tbody>
</table>
<p>All stacks need about 45,100 allocations for this call. The objects are created by the JSON decoder, not by the HTTP client.</p>
<h3 id="many-callers-in-parallel">Many callers in parallel</h3>
<p>16 goroutines with <code>GOMAXPROCS=4</code> fetching a single user over TLS with HTTP/1.1:</p>
<table>
	<thead>
			<tr>
					<th>Stack</th>
					<th style="text-align: right">Time per call</th>
					<th style="text-align: right">New connections per 1,000 calls</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>gocloak (default)</td>
					<td style="text-align: right">51.0 µs</td>
					<td style="text-align: right">30.4</td>
			</tr>
			<tr>
					<td>gocloak, pool 256</td>
					<td style="text-align: right">28.2 µs</td>
					<td style="text-align: right">1.09</td>
			</tr>
			<tr>
					<td>net/http (tuned)</td>
					<td style="text-align: right">19.2 µs</td>
					<td style="text-align: right">0.77</td>
			</tr>
			<tr>
					<td>fasthttp</td>
					<td style="text-align: right">14.4 µs</td>
					<td style="text-align: right">0.14</td>
			</tr>
	</tbody>
</table>
<p>In this run the larger pool made gocloak 1.8 times faster. Default and large pool ran one after the other, so I repeated just that comparison as an interleaved A/B run: 39.2 µs with the default pool against 15.2 µs with 256 idle connections, 2.6 times as fast (-61 %), and new connections dropped from 33.0 to 0.67 per 1,000 calls (-98 %). That is one transport setting. Over HTTP/2 none of the Go clients opened new connections, because HTTP/2 multiplexes all requests over a single connection.</p>
<p>gocloak v15.1.0 sets <code>MaxIdleConns</code> and <code>MaxIdleConnsPerHost</code> to 100. Measured as v15.0 on Go 1.26 against v15.1 on Go 1.27 in an interleaved run (n=10), the same benchmark drops from 37.2 to 15.8 µs per call (-57 %) and from 33.3 to 0.64 new connections per 1,000 calls. Live over plain HTTP the new connections drop by 70 % (187 to 55 per 1,000 calls); the time difference is not significant there.</p>
<h3 id="live-against-keycloak">Live against Keycloak</h3>
<p>Against the real Keycloak in Docker, plain HTTP, one caller at a time, all Go variants are equally fast. A single user takes about 0.9 ms, a token 1.8 ms, the list of 1,000 users about 39 ms. fasthttp saves 80 to 180 µs on small calls (6 to 10 %) and nothing measurable on large ones.</p>
<p>In my very first live run the 1,000 users took 153 to 185 ms. The JVM in Keycloak was not warm yet, even after 300 warm-up calls per endpoint. Part 4 has the details.</p>
<p>The connection pool shows up live too. With 16 parallel callers gocloak&rsquo;s default opened 247 new connections per 1,000 calls and needed 359 µs per call; with a pool of 256 it was 231 µs. In a longer 5-second profiling run the default opened 309 connections per 1,000 calls, the large pool 4.</p>
<p>Local token verification (<code>DecodeAccessToken</code> with a real Keycloak token and a warm certificate cache) takes 50.5 µs, pure CPU for the RSA signature check. json/v2 does not change that time measurably; it only saves 21 % of the allocations.</p>
<h2 id="result-3-other-findings">Result 3: other findings</h2>
<h3 id="the-response-body-limit-costs-memory">The response body limit costs memory</h3>
<p>gocloak sets a response body limit so a misbehaving server cannot make it read a gigantic response. When a limit is set, resty reads the body in 512-byte chunks with <code>append</code> (<code>readAllWithLimit</code>) and does not preallocate from <code>Content-Length</code>. According to the <a href="https://pkg.go.dev/runtime/pprof" rel="noopener">pprof</a> memory profile, <code>readAllWithLimit</code> causes 61 to 67 % of all allocated bytes when fetching 1,000 users, more than the JSON decoding. That is why gocloak allocates 3.88 MiB per call where plain resty needs 2.42 MiB, roughly 60 % more. The run time barely changes, but the garbage collector has more to do. <a href="/blog/gocloak-pprof-profiling/">Part 5</a> shows the profile.</p>
<p>gocloak v15.1.0 adds an opt-in option for this, <code>gocloak.SetDirectBodyRead()</code>. With it gocloak reads and decodes the body itself, into a buffer sized from <code>Content-Length</code> (trusted only up to the limit), with the same limit, the same gzip handling and the same error decoding as resty. A parity test demands identical results and errors. Wrapping the transport instead was rejected, because it would break <code>Transport()</code>, <code>SetTLSClientConfig</code> and <code>SetProxy</code> on the resty client.</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-go" data-lang="go"><span class="line"><span class="cl"><span class="nx">client</span><span class="w"> </span><span class="o">:=</span><span class="w"> </span><span class="nx">gocloak</span><span class="p">.</span><span class="nf">NewClient</span><span class="p">(</span><span class="s">&#34;https://keycloak.example.com&#34;</span><span class="p">,</span><span class="w"> </span><span class="nx">gocloak</span><span class="p">.</span><span class="nf">SetDirectBodyRead</span><span class="p">())</span><span class="w">
</span></span></span></code></pre></div><p>In an interleaved run offline, <code>GetUsers</code> with 1,000 users drops from 3.65 to 2.22 MiB per call (-39 %) and from 6.56 to 5.14 ms (-22 %). 100 users: -24 % bytes, -19 % time. Clients: -34 % bytes. Token and single user are unchanged. Live, 1,000 users go from 3.09 to 2.18 MiB (-29 %) with no significant time difference.</p>
<p>It is opt-in because resty skips its response middleware for these calls: <code>OnAfterResponse</code> hooks on <code>RestyClient()</code> do not run, and <code>SetDebug</code> does not log the response body. resty v2 keeps those hooks unexported, so gocloak cannot run them itself.</p>
<h3 id="fewer-round-trips-beat-a-faster-client">Fewer round trips beat a faster client</h3>
<p>The biggest lever for applications is the number of Keycloak round trips, not the client:</p>
<ul>
<li>Reuse tokens instead of logging in per request. Each login costs about 1.8 ms on a warm local Keycloak, more over a real network.</li>
<li>Use <code>briefRepresentation</code> and small <code>max</code> values for lists. 1,000 users take about 39 ms in a warm Keycloak, and several times that while the JVM is cold.</li>
<li>Verify tokens locally against the JWKS instead of calling <a href="https://www.rfc-editor.org/rfc/rfc7662" rel="noopener">token introspection</a>. Local verification costs about 50 µs of CPU; introspection is a network round trip plus Keycloak&rsquo;s work. <a href="/blog/gocloak-auth-proxy-keycloak/">gocloak-auth-proxy</a> is built around exactly that.</li>
</ul>
<h2 id="what-i-take-away">What I take away</h2>
<ol>
<li>There is nothing &ldquo;massive&rdquo; to gain in the HTTP client. Keycloak needs milliseconds, the client microseconds. fasthttp is the fastest stack in most micro-benchmarks, saves 6 to 10 % on small live calls and nothing on large ones. It also cannot do HTTP/2, is not an <code>http.RoundTripper</code> and would break <code>RestyClient()</code>/<code>SetRestyClient</code> as well as users&rsquo; proxy, TLS and tracing configuration. My recommendation: don&rsquo;t switch.</li>
<li>The real lever under load is the connection pool. resty&rsquo;s default ties <code>MaxIdleConnsPerHost</code> to <code>GOMAXPROCS + 1</code>, which in containers often means 2 or 3. Parallel load over HTTP/1.1 then keeps opening new connections and TLS handshakes: 2.6 times slower in an interleaved A/B test, and refused connections in the extreme case. gocloak v15.1.0 raises both idle limits to 100 in <code>NewClient</code>: -57 % time and 98 % fewer new connections in that benchmark. If you talk to Keycloak over TLS with HTTP/2, you do not have the problem.</li>
<li>json/v2 makes decoding 26 to 74 % faster with no code change (user lists about a third) and cuts allocations by about 40 %. Encoding small structs gets 39 to 51 % slower, which does not matter next to Keycloak&rsquo;s response times. Through gocloak only the user lists get measurably faster, and the latency of a live call does not change, because Keycloak dominates it. On Go 1.27 the v2 engine is the default, and gocloak v15.1.0 requires Go 1.27.</li>
<li><code>SetDirectBodyRead()</code> cuts the bytes per call for 1,000 users by 39 %, at the price of skipping resty&rsquo;s response hooks, which is why it is opt-in.</li>
<li>On method: check the facts first (<code>go list</code>, module versions, the library&rsquo;s source), then measure. That includes which toolchain is current; I measured on the Go version that happened to be installed. Make benchmarks reproducible with a script, fixed parameters, benchstat and a recorded environment, and keep offline and live apart. On a loaded machine single numbers are worthless; only median comparisons with a p-value count. And never compare old against new in separate runs on a machine whose load changes; interleave them.</li>
</ol>
<p><a href="/blog/gocloak-performance-final-benchmarks/">Part 4</a> has the complete benchstat tables, offline and live, and what the final run taught me about JVM warm-up and benchmark clients that poison each other. <a href="/blog/gocloak-pprof-profiling/">Part 5</a> looks at the CPU and memory profiles.</p>
]]></content:encoded></item><item><title>gocloak-auth-proxy: a fast, Keycloak-native auth proxy in Go</title><link>https://blog.noobygames.de/blog/gocloak-auth-proxy-keycloak/</link><pubDate>Sat, 21 Nov 2026 11:30:00 +0100</pubDate><dc:creator>Tobias Theel</dc:creator><guid isPermaLink="true">https://blog.noobygames.de/blog/gocloak-auth-proxy-keycloak/</guid><category>Software Engineering</category><category>go</category><category>keycloak</category><category>gocloak</category><category>oidc</category><category>jwt</category><category>traefik</category><category>nginx</category><category>oauth2-proxy</category><category>security</category><category>performance</category><category>open-source</category><description>gocloak-auth-proxy verifies Keycloak JWTs locally for Traefik and nginx forward-auth, as a reverse proxy or with OIDC browser SSO. Benchmarks against oauth2-proxy, gogatekeeper and reference proxies in Rust, Java and Python, the security model and a setup guide.</description><content:encoded><![CDATA[<blockquote>
<p><strong>Series: The gocloak universe.</strong> <a href="/blog/gocloak-mcp-first-mcp-server-homebrew/">Part 1: gocloak-mcp</a> · Part 2: gocloak-auth-proxy (you are here) · <a href="/blog/gocloak-performance-json-v2-http-clients/">Part 3: gocloak performance</a> · <a href="/blog/gocloak-performance-final-benchmarks/">Part 4: final benchmark numbers</a> · <a href="/blog/gocloak-pprof-profiling/">Part 5: pprof</a></p>
</blockquote>
<aside class="tldr" aria-label="Key takeaways">
<p class="tldr-title">TL;DR</p>
<ul>
<li>gocloak-auth-proxy is a Keycloak-only authentication proxy in Go, built on gocloak v15, that runs as forward-auth for Traefik and nginx, as a reverse proxy, or with OIDC browser SSO.</li>
<li>JWT checks in gocloak-auth-proxy run against an in-memory JWKS snapshot, so a valid request never waits for the network.</li>
<li>Only asymmetric algorithms pass (default <code>RS256,ES256</code>): the proxy rejects <code>none</code> and <code>HS*</code> and strips client identity headers in both dash and underscore spellings.</li>
<li>In the project&rsquo;s benchmark, gocloak-auth-proxy v0.2.0 answered 15,002 forward-auth requests per second with a full signature check on every request, 2.5 times as many as oauth2-proxy v7.15.6.</li>
<li>A Rust reference proxy (21,616 requests per second) beats gocloak-auth-proxy without its token cache; with the v0.2.0 cache, gocloak-auth-proxy reaches 25,169.</li>
</ul>

</aside>

<p><strong>Update, 21 November 2026:</strong> gocloak-auth-proxy v0.2.0 is out, with a faster token verifier, a cache for verified tokens and a benchmark suite in the repository. I added its numbers and charts to the benchmark section and updated the install commands; the v0.1.0 numbers stay below for comparison.</p>
<p>In <a href="/blog/gocloak-mcp-first-mcp-server-homebrew/">Part 1</a> I wrote about gocloak v15 and the Keycloak MCP server built on it. At the same time a second project went public: <a href="https://github.com/Nerzal/gocloak-auth-proxy" rel="noopener">gocloak-auth-proxy</a>, an authentication proxy that sits in front of your services and lets only requests with a valid Keycloak token through.</p>
<p>It runs in three modes:</p>
<ul>
<li>Forward-auth: Traefik&rsquo;s <code>forwardAuth</code> or nginx&rsquo;s <code>auth_request</code> ask the proxy on <code>/auth</code> whether a request may pass. The proxy answers 200 with identity headers, or 401/403.</li>
<li>Reverse proxy: the proxy itself forwards verified requests to one upstream.</li>
<li>Browser SSO: OIDC authorization code flow with PKCE, an encrypted session cookie and logout, for web apps that should not deal with OIDC themselves.</li>
</ul>
<p>In the project&rsquo;s own benchmark, v0.2.0 answered 15,002 forward-auth requests per second with a full signature check on every request, 2.5 times as many as oauth2-proxy on the same machine, and 25,169 with its token cache. Below are those numbers with their caveats, my own micro-benchmark run, the security model and a setup for Traefik and nginx.</p>
<p>v0.1.0 was released on 2026-11-21, v0.2.0 the same afternoon. Nobody has audited it yet, and most of the alternatives below have years of production use behind them.</p>
<h2 id="why-another-proxy-for-keycloak">Why another proxy for Keycloak</h2>
<p>Keycloak used to ship its own proxy, Keycloak Gatekeeper, later renamed Louketo. In August 2020 the Keycloak team <a href="https://www.keycloak.org/2020/08/sunsetting-louketo-project.adoc" rel="noopener">announced its end of life</a> and recommended <a href="https://github.com/oauth2-proxy/oauth2-proxy" rel="noopener">oauth2-proxy</a> instead; the last release is 1.0.0 from July 2020 and the <a href="https://github.com/louketo/louketo-proxy" rel="noopener">repository</a> is archived. Since then most Keycloak setups use one of these:</p>
<table>
	<thead>
			<tr>
					<th>Project</th>
					<th>Language</th>
					<th style="text-align: right">Stars</th>
					<th>Latest release</th>
					<th>Keycloak focus</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><a href="https://github.com/oauth2-proxy/oauth2-proxy" rel="noopener">oauth2-proxy</a></td>
					<td>Go</td>
					<td style="text-align: right">15,392</td>
					<td>v7.15.6 (2026-11-05)</td>
					<td>Generic, with <code>keycloak</code> and <code>keycloak_oidc</code> providers</td>
			</tr>
			<tr>
					<td><a href="https://github.com/pomerium/pomerium" rel="noopener">Pomerium</a></td>
					<td>Go</td>
					<td style="text-align: right">5,113</td>
					<td>v0.34.1 (2026-11-11)</td>
					<td>Generic OIDC, full identity-aware proxy</td>
			</tr>
			<tr>
					<td><a href="https://github.com/ory/oathkeeper" rel="noopener">Ory Oathkeeper</a></td>
					<td>Go</td>
					<td style="text-align: right">3,610</td>
					<td>v26.2.0 (2026-03-20)</td>
					<td>Generic; JWKS URLs configured by hand</td>
			</tr>
			<tr>
					<td><a href="https://github.com/vouch/vouch-proxy" rel="noopener">Vouch Proxy</a></td>
					<td>Go</td>
					<td style="text-align: right">3,290</td>
					<td>v0.50.0</td>
					<td>Generic, nginx <code>auth_request</code></td>
			</tr>
			<tr>
					<td><a href="https://github.com/thomseddon/traefik-forward-auth" rel="noopener">traefik-forward-auth</a></td>
					<td>Go</td>
					<td style="text-align: right">2,396</td>
					<td>v2.3.0 (2024-05-06)</td>
					<td>Generic OIDC</td>
			</tr>
			<tr>
					<td><a href="https://github.com/gogatekeeper/gatekeeper" rel="noopener">gogatekeeper</a></td>
					<td>Go</td>
					<td style="text-align: right">324</td>
					<td>5.1.0 (2026-11-18)</td>
					<td>Yes, the community fork of Keycloak Gatekeeper</td>
			</tr>
			<tr>
					<td><strong>gocloak-auth-proxy</strong></td>
					<td>Go</td>
					<td style="text-align: right">new</td>
					<td>v0.2.0 (2026-11-21)</td>
					<td>Yes, built on gocloak v15</td>
			</tr>
	</tbody>
</table>
<p>(Stars as of 2026-11-21.)</p>
<p>oauth2-proxy is the default answer and a good one. It supports a dozen identity providers, which also means its configuration and code have to cover a dozen identity providers. gogatekeeper is the closest relative: Keycloak-specific, with forward-auth, PKCE, role and group rules, UMA (marked as not production ready in <a href="https://gogatekeeper.github.io/gatekeeper/" rel="noopener">its docs</a>) and OPA. gocloak-auth-proxy is narrower than both: only Keycloak, few dependencies, and a hot path on which a valid request never waits for the network.</p>
<h2 id="how-a-request-is-verified">How a request is verified</h2>
<p>For a request with <code>Authorization: Bearer &lt;JWT&gt;</code> the proxy goes through these steps:</p>
<ol>
<li>Strip every identity header the client sent: <code>X-Auth-Request-*</code>, <code>X-Forwarded-*</code>, <code>Forwarded</code>, <code>X-Real-IP</code>, <code>Authorization</code> after reading it, configured custom headers, and their <code>_</code> variants (more on that below).</li>
<li>Normalize the path and apply the ACL: public paths, optional-auth paths, CORS preflight, route rules. Encoded traversal (<code>..</code>, <code>%2f</code>, <code>%2e</code>, <code>%5c</code>, <code>%23</code>, <code>%00</code>) is rejected.</li>
<li>Parse the JWT header and check the algorithm against the allowlist.</li>
<li>Look up the signing key by <code>kid</code> in an in-memory JWKS snapshot and verify the signature.</li>
<li>Check <code>iss</code>, <code>aud</code>, <code>exp</code>, <code>nbf</code>, <code>typ</code> (only <code>Bearer</code>) and the authorization rules: realm and client roles, groups, scopes, <code>acr</code>, <code>amr</code>, <code>email_verified</code>, <code>azp</code>, Keycloak organization.</li>
<li>Optionally call Keycloak&rsquo;s token introspection or UMA endpoint.</li>
<li>Answer with identity headers (forward-auth) or forward the request upstream (reverse proxy).</li>
</ol>
<p>Steps 1 to 5 need no network call. The JWKS snapshot lives behind a Go <code>atomic.Pointer</code>, so readers never take a lock. When a token arrives with an unknown <code>kid</code>, for example right after a key rotation in Keycloak, the proxy refreshes the key set once, no matter how many requests are waiting for it, with a rate limit and exponential backoff so a flood of forged <code>kid</code> values cannot turn into a flood of requests against Keycloak. A snapshot expires after twice the refresh interval (bounded to one minute through 24 hours). After that <code>/readyz</code> returns 503 and Kubernetes stops sending traffic, instead of the proxy accepting tokens against stale keys forever.</p>
<h3 id="which-tokens-it-refuses">Which tokens it refuses</h3>
<p>The algorithm allowlist defaults to <code>RS256,ES256</code> and accepts only asymmetric algorithms: RS256/384/512, PS256/384/512, ES256/384/512 and EdDSA with Ed25519. <code>none</code> and the HMAC family <code>HS*</code> are rejected at configuration time and at verification time. That closes the classic algorithm confusion attack where a token signed with HS256, using the public RSA key as the HMAC secret, passes a naive verifier. The proxy also refuses tokens with <code>crit</code>, <code>b64</code>, <code>jku</code>, <code>x5u</code> or <code>jwk</code> headers, because those let a token tell the verifier where to fetch its key. <a href="https://www.rfc-editor.org/rfc/rfc8725" rel="noopener">RFC 8725</a>, the JWT best current practices, recommends both.</p>
<p>The relevant standards, if you want to dig deeper: <a href="https://www.rfc-editor.org/rfc/rfc7519" rel="noopener">RFC 7519</a> (JWT), <a href="https://www.rfc-editor.org/rfc/rfc7515" rel="noopener">RFC 7515</a> (JWS), <a href="https://www.rfc-editor.org/rfc/rfc7517" rel="noopener">RFC 7517</a> (JWK), <a href="https://www.rfc-editor.org/rfc/rfc7662" rel="noopener">RFC 7662</a> (token introspection), <a href="https://www.rfc-editor.org/rfc/rfc7636" rel="noopener">RFC 7636</a> (PKCE), <a href="https://openid.net/specs/openid-connect-backchannel-1_0.html" rel="noopener">OpenID Connect Back-Channel Logout</a> and Keycloak&rsquo;s <a href="https://www.keycloak.org/docs/latest/authorization_services/index.html#_service_uma_authorization_process" rel="noopener">UMA 2.0 docs</a>.</p>
<h3 id="header-and-path-confusion">Header and path confusion</h3>
<p>The JWT library takes care of the cryptography. Most auth proxy vulnerabilities come from somewhere else: the proxy and the backend disagree about a header or a path. oauth2-proxy&rsquo;s advisory list from the last 16 months is a good catalog of what goes wrong:</p>
<table>
	<thead>
			<tr>
					<th>Advisory</th>
					<th>Severity</th>
					<th>What happened</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><a href="https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-7rh7-c77v-6434" rel="noopener">CVE-2025-54576</a></td>
					<td>critical</td>
					<td><code>skip_auth_routes</code> matched against the URL including the query string</td>
			</tr>
			<tr>
					<td><a href="https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-vjrc-mh2v-45x6" rel="noopener">CVE-2025-64484</a></td>
					<td>high</td>
					<td>Header smuggling: identity headers spelled with underscores passed through, and WSGI/CGI backends read them as the dash version</td>
			</tr>
			<tr>
					<td><a href="https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-7x63-xv5r-3p2x" rel="noopener">CVE-2026-40575</a></td>
					<td>critical</td>
					<td>Authentication bypass through a spoofed <code>X-Forwarded-Uri</code></td>
			</tr>
			<tr>
					<td><a href="https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-pxq7-h93f-9jrg" rel="noopener">CVE-2026-41059</a></td>
					<td>high</td>
					<td>Fragment confusion in <code>skip_auth_routes</code> and <code>skip_auth_regex</code></td>
			</tr>
			<tr>
					<td><a href="https://github.com/oauth2-proxy/oauth2-proxy/security/advisories/GHSA-5hvv-m4w4-gf6v" rel="noopener">CVE-2026-34457</a></td>
					<td>critical</td>
					<td>A health-check User-Agent match skipped authentication in <code>auth_request</code> mode</td>
			</tr>
	</tbody>
</table>
<p>All of them are fixed in current releases. I list them because they are exactly the cases gocloak-auth-proxy has tests for: it strips identity headers in both spellings (<code>X-Auth-Request-User</code> and <code>X_Auth_Request_User</code>), never trusts <code>X-Forwarded-*</code> from the client, rejects encoded delimiters and fragments in paths, and has no User-Agent-based exceptions. Tests only cover the cases someone thought of. oauth2-proxy&rsquo;s bugs were found because many people run it and researchers study it. gocloak-auth-proxy has not had that scrutiny yet, and reviews are welcome.</p>
<h2 id="benchmarks">Benchmarks</h2>
<h3 id="head-to-head-v020">Head to head (v0.2.0)</h3>
<p>v0.2.0 brings its benchmark suite into the repository: <code>make bench-compare</code> runs <a href="https://github.com/Nerzal/gocloak-auth-proxy/blob/main/bench/run_compare.sh" rel="noopener"><code>bench/run_compare.sh</code></a>. All proxies ran on the same Linux host (Intel Xeon 6985P-C) with <code>GOMAXPROCS=2</code>, 32 concurrent connections for 5 seconds, a 2048-bit RS256 bearer token, a local mock JWKS and a local mock upstream, with zero errors in every run.</p>
<p>Two token modes matter for reading the numbers. &ldquo;Warm&rdquo; sends the same token on every request. &ldquo;Cold&rdquo; rotates through 2,000 different tokens, and for gocloak-auth-proxy the token cache is switched off (<code>TOKEN_CACHE_SIZE=0</code>), so every request pays for a full signature check.</p>
<p><img src="/img/gocloak/auth-proxy/benchmark-overview.svg" alt="Throughput, latency and memory of gocloak-auth-proxy v0.2.0 against oauth2-proxy and reference proxies in Rust, Java and Python"></p>
<table>
	<thead>
			<tr>
					<th>Proxy</th>
					<th>Tokens</th>
					<th style="text-align: right">Forward-auth RPS</th>
					<th style="text-align: right">p50</th>
					<th style="text-align: right">Reverse proxy RPS</th>
					<th style="text-align: right">p50</th>
					<th style="text-align: right">Memory under load</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>gocloak-auth-proxy v0.2.0</td>
					<td>warm</td>
					<td style="text-align: right">25,169</td>
					<td style="text-align: right">1.08 ms</td>
					<td style="text-align: right">11,248</td>
					<td style="text-align: right">2.51 ms</td>
					<td style="text-align: right">15.3 to 16.1 MB</td>
			</tr>
			<tr>
					<td>gocloak-auth-proxy v0.2.0</td>
					<td>cold</td>
					<td style="text-align: right">15,002</td>
					<td style="text-align: right">1.99 ms</td>
					<td style="text-align: right">7,583</td>
					<td style="text-align: right">3.90 ms</td>
					<td style="text-align: right">15.7 to 16.2 MB</td>
			</tr>
			<tr>
					<td>Rust reference (Axum, <code>jsonwebtoken</code>)</td>
					<td>cold</td>
					<td style="text-align: right">21,616</td>
					<td style="text-align: right">1.32 ms</td>
					<td style="text-align: right">10,629</td>
					<td style="text-align: right">2.86 ms</td>
					<td style="text-align: right">3.8 to 6.3 MB</td>
			</tr>
			<tr>
					<td>oauth2-proxy v7.15.6</td>
					<td>warm</td>
					<td style="text-align: right">6,023</td>
					<td style="text-align: right">4.47 ms</td>
					<td style="text-align: right">2,245</td>
					<td style="text-align: right">13.39 ms</td>
					<td style="text-align: right">26.7 to 27.8 MB</td>
			</tr>
			<tr>
					<td>Java 17 reference (<code>HttpServer</code>)</td>
					<td>cold</td>
					<td style="text-align: right">6,839</td>
					<td style="text-align: right">3.71 ms</td>
					<td style="text-align: right">1,978</td>
					<td style="text-align: right">14.23 ms</td>
					<td style="text-align: right">104.9 to 114.4 MB</td>
			</tr>
			<tr>
					<td>Python 3.11 reference (Uvicorn, PyJWT)</td>
					<td>cold</td>
					<td style="text-align: right">5,811</td>
					<td style="text-align: right">5.14 ms</td>
					<td style="text-align: right">734</td>
					<td style="text-align: right">32.95 ms</td>
					<td style="text-align: right">14.7 MB (master process)</td>
			</tr>
	</tbody>
</table>
<p>The Rust, Java and Python proxies are not products. They are small reference implementations in <a href="https://github.com/Nerzal/gocloak-auth-proxy/tree/main/bench/competitors" rel="noopener"><code>bench/competitors/</code></a>, written for this benchmark to show what each runtime does with the same job. oauth2-proxy is the only established product in the run; gogatekeeper is no longer part of it.</p>
<p>Compared fairly, with a full signature check on every request, gocloak-auth-proxy does 2.5 times the forward-auth throughput of oauth2-proxy and 3.4 times in reverse-proxy mode. With the cache it reaches 4.2 and 5 times. The Rust reference is faster than gocloak-auth-proxy without the cache (21,616 against 15,002 forward-auth requests per second) and needs a quarter of the memory; only with the cache does the Go proxy get ahead. The chart&rsquo;s &ldquo;#1&rdquo; badge counts the warm run. That is a fair description of production, where a client sends the same token until it expires, but it is not the same workload as the cold runs of the reference proxies.</p>
<h3 id="what-v020-changed">What v0.2.0 changed</h3>
<p><img src="/img/gocloak/auth-proxy/pprof-progression.svg" alt="Bytes and allocations per token verification from v0.1.0 to v0.2.0"></p>
<p>Two changes came out of profiling. The JWS verifier now reads the claims with the streaming <code>jsontext</code> package from <code>encoding/json/v2</code> instead of decoding them into maps. For a cold RS256 verification that cuts the bytes from 6,412 to 1,728 (-73 %) and the allocations from 79 to 33 (-58 %); for EdDSA with custom claim headers from 8,540 to 624 bytes (-93 %) and from 104 to 24 allocations (-77 %). The second change is a sharded cache of verified tokens, keyed by the SHA-256 of the token. A hit takes 463 ns and allocates nothing. It still checks <code>exp</code> and <code>nbf</code> on every hit, and whether the signing key is still in the current JWKS snapshot, so a key rotation in Keycloak also invalidates cached tokens. Reading an OIDC session cookie got 40 % faster on top.</p>
<p>The micro-benchmarks from the v0.2.0 README (Go 1.27.4, gocloak v15.1.0, Intel Xeon 6985P-C):</p>
<table>
	<thead>
			<tr>
					<th>Benchmark</th>
					<th style="text-align: right">Time per op</th>
					<th style="text-align: right">Bytes per op</th>
					<th style="text-align: right">Allocs per op</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><code>BenchmarkPolicy</code></td>
					<td style="text-align: right">128 ns</td>
					<td style="text-align: right">0</td>
					<td style="text-align: right">0</td>
			</tr>
			<tr>
					<td><code>BenchmarkIntrospectorCacheHit</code></td>
					<td style="text-align: right">192 ns</td>
					<td style="text-align: right">0</td>
					<td style="text-align: right">0</td>
			</tr>
			<tr>
					<td><code>BenchmarkVerifyCached</code></td>
					<td style="text-align: right">463 ns</td>
					<td style="text-align: right">0</td>
					<td style="text-align: right">0</td>
			</tr>
			<tr>
					<td><code>BenchmarkForwardAuth</code></td>
					<td style="text-align: right">1.62 µs</td>
					<td style="text-align: right">2,336</td>
					<td style="text-align: right">17</td>
			</tr>
			<tr>
					<td><code>BenchmarkReadSession</code></td>
					<td style="text-align: right">2.76 µs</td>
					<td style="text-align: right">1,328</td>
					<td style="text-align: right">3</td>
			</tr>
			<tr>
					<td><code>BenchmarkVerify/RS256</code></td>
					<td style="text-align: right">30.0 µs</td>
					<td style="text-align: right">1,728</td>
					<td style="text-align: right">33</td>
			</tr>
			<tr>
					<td><code>BenchmarkVerifyEdDSA</code></td>
					<td style="text-align: right">45.5 µs</td>
					<td style="text-align: right">624</td>
					<td style="text-align: right">24</td>
			</tr>
			<tr>
					<td><code>BenchmarkVerify/ES256</code></td>
					<td style="text-align: right">67.7 µs</td>
					<td style="text-align: right">1,536</td>
					<td style="text-align: right">44</td>
			</tr>
	</tbody>
</table>
<p>These come from a different machine than my v0.1.0 run below, so compare the allocation columns, not the times.</p>
<h3 id="the-v010-comparison">The v0.1.0 comparison</h3>
<p>The v0.1.0 comparison came from the project README. All three proxies ran on the same Linux host (Intel Xeon 6985P-C) with <code>GOMAXPROCS=2</code>, against a local mock Keycloak JWKS and a local mock upstream, with a 2048-bit RS256 bearer token on every request, 32 concurrent connections, access logging off and zero errors in every run. The load scripts and the competitor configurations were not in the repository at that point, so this run cannot be reproduced one to one.</p>










<figure class="diagram">
    <div class="diagram-canvas" role="img" aria-label="Forward-auth is the mode Traefik and nginx use. The gap is largest there because the proxy only verifies and answers; in reverse-proxy mode it also forwards the request body upstream.">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 720 296" width="720" height="296">
<text x="20" y="28" class="d-t d-bold" font-size="15">Requests per second at 32 concurrent connections (higher is better)</text>
<text x="20" y="48" class="d-m" font-size="11.5">Every request carries a 2048-bit RS256 JWT that the proxy verifies before it answers.</text>
<rect x="20" y="62" width="12" height="12" rx="3" fill="#4285f4"/>
<text x="38" y="72" class="d-t" font-size="11.5">gocloak-auth-proxy v0.1.0</text>
<rect x="222.0" y="62" width="12" height="12" rx="3" fill="#d97706"/>
<text x="240.0" y="72" class="d-t" font-size="11.5">gogatekeeper v5.1.0</text>
<rect x="385.6" y="62" width="12" height="12" rx="3" fill="#a142f4"/>
<text x="403.6" y="72" class="d-t" font-size="11.5">oauth2-proxy v7.15.6</text>
<line x1="190.0" y1="84" x2="190.0" y2="244" class="d-divider"/>
<text x="190.0" y="260" class="d-m" font-size="11" text-anchor="middle">0</text>
<line x1="317.8" y1="84" x2="317.8" y2="244" class="d-divider"/>
<text x="317.8" y="260" class="d-m" font-size="11" text-anchor="middle">5k</text>
<line x1="445.6" y1="84" x2="445.6" y2="244" class="d-divider"/>
<text x="445.6" y="260" class="d-m" font-size="11" text-anchor="middle">10k</text>
<line x1="573.3" y1="84" x2="573.3" y2="244" class="d-divider"/>
<text x="573.3" y="260" class="d-m" font-size="11" text-anchor="middle">15k</text>
<text x="180" y="127.0" class="d-t" font-size="12" text-anchor="end">Forward-auth</text>
<path d="M190 92 H590.4 Q594.4 92 594.4 96 V106 Q594.4 110 590.4 110 H190 Z" fill="#4285f4"/>
<text x="600.4" y="105" class="d-t" font-size="11">15,825 RPS <tspan class="d-m">p50 1.80 ms</tspan></text>
<path d="M190 114 H334.2 Q338.2 114 338.2 118 V128 Q338.2 132 334.2 132 H190 Z" fill="#d97706"/>
<text x="344.2" y="127" class="d-t" font-size="11">5,801 RPS <tspan class="d-m">p50 5.04 ms</tspan></text>
<path d="M190 136 H355.3 Q359.3 136 359.3 140 V150 Q359.3 154 355.3 154 H190 Z" fill="#a142f4"/>
<text x="365.3" y="149" class="d-t" font-size="11">6,625 RPS <tspan class="d-m">p50 4.09 ms</tspan></text>
<text x="180" y="211.0" class="d-t" font-size="12" text-anchor="end">Reverse proxy</text>
<path d="M190 176 H409.3 Q413.3 176 413.3 180 V190 Q413.3 194 409.3 194 H190 Z" fill="#4285f4"/>
<text x="419.3" y="189" class="d-t" font-size="11">8,737 RPS <tspan class="d-m">p50 3.36 ms</tspan></text>
<path d="M190 198 H307.5 Q311.5 198 311.5 202 V212 Q311.5 216 307.5 216 H190 Z" fill="#d97706"/>
<text x="317.5" y="211" class="d-t" font-size="11">4,754 RPS <tspan class="d-m">p50 6.22 ms</tspan></text>
<path d="M190 220 H258.9 Q262.9 220 262.9 224 V234 Q262.9 238 258.9 238 H190 Z" fill="#a142f4"/>
<text x="268.9" y="233" class="d-t" font-size="11">2,851 RPS <tspan class="d-m">p50 10.55 ms</tspan></text>
<line x1="190" y1="84" x2="190" y2="244" class="d-arrow"/>
<text x="20" y="284" class="d-m" font-size="10.5">Source: gocloak-auth-proxy README. Same host, Xeon 6985P-C, GOMAXPROCS=2, RS256 JWT, 0 errors.</text>
</svg>

    </div>
    <figcaption class="diagram-caption">Forward-auth is the mode Traefik and nginx use. The gap is largest there because the proxy only verifies and answers; in reverse-proxy mode it also forwards the request body upstream.</figcaption>
</figure>

<table>
	<thead>
			<tr>
					<th>Proxy</th>
					<th style="text-align: right">Forward-auth RPS</th>
					<th style="text-align: right">p50</th>
					<th style="text-align: right">Reverse proxy RPS</th>
					<th style="text-align: right">p50</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td>gocloak-auth-proxy v0.1.0</td>
					<td style="text-align: right">15,825</td>
					<td style="text-align: right">1.80 ms</td>
					<td style="text-align: right">8,737</td>
					<td style="text-align: right">3.36 ms</td>
			</tr>
			<tr>
					<td>gogatekeeper v5.1.0</td>
					<td style="text-align: right">5,801</td>
					<td style="text-align: right">5.04 ms</td>
					<td style="text-align: right">4,754</td>
					<td style="text-align: right">6.22 ms</td>
			</tr>
			<tr>
					<td>oauth2-proxy v7.15.6</td>
					<td style="text-align: right">6,625</td>
					<td style="text-align: right">4.09 ms</td>
					<td style="text-align: right">2,851</td>
					<td style="text-align: right">10.55 ms</td>
			</tr>
	</tbody>
</table>










<figure class="diagram">
    <div class="diagram-canvas" role="img" aria-label="Binary size and idle memory from the README. Dependencies are the require entries in each project&#39;s go.mod at the release tag, direct and indirect.">
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 720 240" width="720" height="240">
<text x="20" y="28" class="d-t d-bold" font-size="15">Footprint: smaller is better in every panel</text>
<text x="20" y="48" class="d-m" font-size="11.5">Each panel has its own scale. Dependencies = require entries (direct + indirect) in go.mod at each release tag, counted 2026-11-21.</text>
<rect x="20" y="62" width="12" height="12" rx="3" fill="#4285f4"/>
<text x="38" y="72" class="d-t" font-size="11.5">gocloak-auth-proxy v0.1.0</text>
<rect x="222.0" y="62" width="12" height="12" rx="3" fill="#d97706"/>
<text x="240.0" y="72" class="d-t" font-size="11.5">gogatekeeper v5.1.0</text>
<rect x="385.6" y="62" width="12" height="12" rx="3" fill="#a142f4"/>
<text x="403.6" y="72" class="d-t" font-size="11.5">oauth2-proxy v7.15.6</text>
<text x="20" y="104" class="d-t d-bold" font-size="12.5">Binary size</text>
<path d="M20 116 H45.9 Q49.9 116 49.9 120 V130 Q49.9 134 45.9 134 H20 Z" fill="#4285f4"/>
<text x="55.9" y="129" class="d-t" font-size="11">8.6 MB</text>
<path d="M20 142 H151.6 Q155.6 142 155.6 146 V156 Q155.6 160 151.6 160 H20 Z" fill="#d97706"/>
<text x="161.6" y="155" class="d-t" font-size="11">39 MB</text>
<path d="M20 168 H162.0 Q166.0 168 166.0 172 V182 Q166.0 186 162.0 186 H20 Z" fill="#a142f4"/>
<text x="172.0" y="181" class="d-t" font-size="11">42 MB</text>
<line x1="20" y1="112" x2="20" y2="194" class="d-arrow"/>
<text x="256" y="104" class="d-t d-bold" font-size="12.5">Idle memory (RSS)</text>
<path d="M256 116 H298.8 Q302.8 116 302.8 120 V130 Q302.8 134 298.8 134 H256 Z" fill="#4285f4"/>
<text x="308.8" y="129" class="d-t" font-size="11">9.1 MB</text>
<path d="M256 142 H398.0 Q402.0 142 402.0 146 V156 Q402.0 160 398.0 160 H256 Z" fill="#d97706"/>
<text x="408.0" y="155" class="d-t" font-size="11">28.4 MB</text>
<path d="M256 168 H359.4 Q363.4 168 363.4 172 V182 Q363.4 186 359.4 186 H256 Z" fill="#a142f4"/>
<text x="369.4" y="181" class="d-t" font-size="11">20.9 MB</text>
<line x1="256" y1="112" x2="256" y2="194" class="d-arrow"/>
<text x="492" y="104" class="d-t d-bold" font-size="12.5">go.mod dependencies</text>
<path d="M492 116 H504.8 Q508.8 116 508.8 120 V130 Q508.8 134 504.8 134 H492 Z" fill="#4285f4"/>
<text x="514.8" y="129" class="d-t" font-size="11">12 </text>
<path d="M492 142 H634.0 Q638.0 142 638.0 146 V156 Q638.0 160 634.0 160 H492 Z" fill="#d97706"/>
<text x="644.0" y="155" class="d-t" font-size="11">104 </text>
<path d="M492 168 H590.5 Q594.5 168 594.5 172 V182 Q594.5 186 590.5 186 H492 Z" fill="#a142f4"/>
<text x="600.5" y="181" class="d-t" font-size="11">73 </text>
<line x1="492" y1="112" x2="492" y2="194" class="d-arrow"/>
<text x="20" y="228" class="d-m" font-size="10.5">Size and memory: gocloak-auth-proxy README (Xeon 6985P-C). Dependencies: go.mod require entries at each release tag.</text>
</svg>

    </div>
    <figcaption class="diagram-caption">Binary size and idle memory from the README. Dependencies are the require entries in each project&rsquo;s go.mod at the release tag, direct and indirect.</figcaption>
</figure>

<p>At the v0.1.0 tag, gocloak-auth-proxy&rsquo;s go.mod has 12 require entries (2 direct, 10 indirect; the README still says 8). gogatekeeper 5.1.0 has 104 and oauth2-proxy v7.15.6 has 73. Fewer dependencies does not make code correct, but every module is code you have to trust and update.</p>
<p>In forward-auth mode a valid request costs one signature verification and a few map lookups, as the micro-benchmarks below show. A benchmark against mock services measures the proxy alone; in production the upstream will usually dominate.</p>
<h3 id="micro-benchmarks-on-my-machine">Micro-benchmarks on my machine</h3>
<p>I ran <code>make bench</code> on v0.1.0 on my machine (AMD Ryzen AI 9 HX 370, Windows 11, Go 1.26.2):</p>
<table>
	<thead>
			<tr>
					<th>Benchmark</th>
					<th style="text-align: right">Time per op</th>
					<th style="text-align: right">Bytes per op</th>
					<th style="text-align: right">Allocs per op</th>
					<th>What it covers</th>
			</tr>
	</thead>
	<tbody>
			<tr>
					<td><code>BenchmarkIntrospectorCacheHit</code></td>
					<td style="text-align: right">55 ns</td>
					<td style="text-align: right">0</td>
					<td style="text-align: right">0</td>
					<td>Introspection cache hit, SHA-256 keyed</td>
			</tr>
			<tr>
					<td><code>BenchmarkPolicy</code></td>
					<td style="text-align: right">90 ns</td>
					<td style="text-align: right">0</td>
					<td style="text-align: right">0</td>
					<td>Path normalization, ACL, route role check</td>
			</tr>
			<tr>
					<td><code>BenchmarkForwardAuth</code></td>
					<td style="text-align: right">1.75 µs</td>
					<td style="text-align: right">2,416</td>
					<td style="text-align: right">25</td>
					<td>Header scrubbing and identity headers (mock verifier)</td>
			</tr>
			<tr>
					<td><code>BenchmarkReadSession</code></td>
					<td style="text-align: right">7.3 µs</td>
					<td style="text-align: right">3,024</td>
					<td style="text-align: right">10</td>
					<td>AES-256-GCM session cookie decryption and decode</td>
			</tr>
			<tr>
					<td><code>BenchmarkVerify/RS256</code></td>
					<td style="text-align: right">38.3 µs</td>
					<td style="text-align: right">7,704</td>
					<td style="text-align: right">113</td>
					<td>Full RS256 verification with claims and roles</td>
			</tr>
			<tr>
					<td><code>BenchmarkVerify/ES256</code></td>
					<td style="text-align: right">51.4 µs</td>
					<td style="text-align: right">7,352</td>
					<td style="text-align: right">125</td>
					<td>Same with ES256 (P-256)</td>
			</tr>
			<tr>
					<td><code>BenchmarkVerifyEdDSA</code></td>
					<td style="text-align: right">85.0 µs</td>
					<td style="text-align: right">10,576</td>
					<td style="text-align: right">176</td>
					<td>Ed25519 plus custom claim headers</td>
			</tr>
	</tbody>
</table>
<p>The v0.1.0 README&rsquo;s numbers came from Go 1.27 on Linux and show fewer allocations (79 for RS256, for example), so the toolchain matters here; compare runs only on the same setup. The picture is the same on both: signature verification is about 95 percent of the CPU time of a request, and everything around it is small change. RS256 is the fastest algorithm to verify, which is convenient because it is Keycloak&rsquo;s default.</p>
<h2 id="setting-it-up">Setting it up</h2>
<h3 id="1-a-client-in-keycloak">1. A client in Keycloak</h3>
<p>For forward-auth and reverse-proxy mode the proxy only needs the issuer URL and an audience; it does not need a client secret. Keycloak puts <code>account</code> into <code>aud</code> by default, so add an <em>Audience</em> mapper to a client scope of the clients that call your API, with your API&rsquo;s name (for example <code>my-api</code>) as the included audience.</p>
<p>For browser SSO, create a confidential client with the standard flow enabled and <code>https://app.example.com/oauth2/callback</code> as the redirect URI.</p>
<h3 id="2-run-it">2. Run it</h3>
<p>There are static binaries for Linux and macOS (amd64 and arm64) with checksums and GitHub build provenance, and a multi-arch distroless image on GHCR. On Windows use the container or <code>go install</code>.</p>
<div class="os-tabs">
<div class="os-tab" data-label="Linux / macOS">
<p class="os-tab-label">Linux / macOS</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl">docker run --rm -p 8080:8080 <span class="se">\
</span></span></span><span class="line"><span class="cl">  -e <span class="nv">ISSUER</span><span class="o">=</span>https://keycloak.example.com/realms/myrealm <span class="se">\
</span></span></span><span class="line"><span class="cl">  -e <span class="nv">AUDIENCE</span><span class="o">=</span>my-api <span class="se">\
</span></span></span><span class="line"><span class="cl">  -e <span class="nv">REQUIRED_REALM_ROLES</span><span class="o">=</span>reader <span class="se">\
</span></span></span><span class="line"><span class="cl">  ghcr.io/nerzal/gocloak-auth-proxy:v0.2.0
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c1"># or the binary, with provenance check</span>
</span></span><span class="line"><span class="cl"><span class="nv">VERSION</span><span class="o">=</span>0.2.0<span class="p">;</span> <span class="nv">OS</span><span class="o">=</span>linux<span class="p">;</span> <span class="nv">ARCH</span><span class="o">=</span>amd64
</span></span><span class="line"><span class="cl">curl -fsSLO <span class="s2">&#34;https://github.com/Nerzal/gocloak-auth-proxy/releases/download/v</span><span class="si">${</span><span class="nv">VERSION</span><span class="si">}</span><span class="s2">/gocloak-auth-proxy_</span><span class="si">${</span><span class="nv">VERSION</span><span class="si">}</span><span class="s2">_</span><span class="si">${</span><span class="nv">OS</span><span class="si">}</span><span class="s2">_</span><span class="si">${</span><span class="nv">ARCH</span><span class="si">}</span><span class="s2">.tar.gz&#34;</span>
</span></span><span class="line"><span class="cl">gh attestation verify <span class="s2">&#34;gocloak-auth-proxy_</span><span class="si">${</span><span class="nv">VERSION</span><span class="si">}</span><span class="s2">_</span><span class="si">${</span><span class="nv">OS</span><span class="si">}</span><span class="s2">_</span><span class="si">${</span><span class="nv">ARCH</span><span class="si">}</span><span class="s2">.tar.gz&#34;</span> -R Nerzal/gocloak-auth-proxy
</span></span></code></pre></div>
</div>

<div class="os-tab" data-label="Windows (PowerShell)">
<p class="os-tab-label">Windows (PowerShell)</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="n">docker</span> <span class="n">run</span> <span class="p">-</span><span class="n">-rm</span> <span class="n">-p</span> <span class="mf">8080</span><span class="err">:</span><span class="mf">8080</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">  <span class="n">-e</span> <span class="n">ISSUER</span><span class="p">=</span><span class="n">https</span><span class="err">:</span><span class="p">//</span><span class="n">keycloak</span><span class="p">.</span><span class="py">example</span><span class="p">.</span><span class="n">com</span><span class="p">/</span><span class="n">realms</span><span class="p">/</span><span class="n">myrealm</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">  <span class="n">-e</span> <span class="n">AUDIENCE</span><span class="p">=</span><span class="nb">my-api</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">  <span class="n">-e</span> <span class="n">REQUIRED_REALM_ROLES</span><span class="p">=</span><span class="n">reader</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">  <span class="n">ghcr</span><span class="p">.</span><span class="n">io</span><span class="p">/</span><span class="n">nerzal</span><span class="p">/</span><span class="nb">gocloak-auth</span><span class="n">-proxy:v0</span><span class="p">.</span><span class="py">2</span><span class="p">.</span><span class="py">0</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="c"># or build it with Go 1.27+</span>
</span></span><span class="line"><span class="cl"><span class="n">go</span> <span class="n">install</span> <span class="n">github</span><span class="p">.</span><span class="n">com</span><span class="p">/</span><span class="n">Nerzal</span><span class="p">/</span><span class="nb">gocloak-auth</span><span class="n">-proxy</span><span class="p">/</span><span class="n">cmd</span><span class="p">/</span><span class="nb">gocloak-auth</span><span class="n">-proxy</span><span class="nv">@latest</span>
</span></span></code></pre></div>
</div>

</div>

<p>Without <code>UPSTREAM_URL</code> the proxy runs in forward-auth mode on <code>/auth</code>. <code>/healthz</code> and <code>/readyz</code> are public, and Prometheus metrics go to a separate port if you set <code>METRICS_ADDR</code>. Docker is at <a href="https://docs.docker.com/get-started/get-docker/" rel="noopener">docs.docker.com</a>, the GitHub CLI for <code>gh attestation</code> at <a href="https://cli.github.com/" rel="noopener">cli.github.com</a>.</p>
<p>Test it with a token from Keycloak:</p>
<div class="os-tabs">
<div class="os-tab" data-label="Linux / macOS">
<p class="os-tab-label">Linux / macOS</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="nv">TOKEN</span><span class="o">=</span><span class="k">$(</span>curl -s https://keycloak.example.com/realms/myrealm/protocol/openid-connect/token <span class="se">\
</span></span></span><span class="line"><span class="cl">  -d <span class="nv">grant_type</span><span class="o">=</span>client_credentials -d <span class="nv">client_id</span><span class="o">=</span>my-client -d <span class="nv">client_secret</span><span class="o">=</span><span class="s2">&#34;</span><span class="nv">$CLIENT_SECRET</span><span class="s2">&#34;</span> <span class="se">\
</span></span></span><span class="line"><span class="cl">  <span class="p">|</span> jq -r .access_token<span class="k">)</span>
</span></span><span class="line"><span class="cl">curl -i -H <span class="s2">&#34;Authorization: Bearer </span><span class="nv">$TOKEN</span><span class="s2">&#34;</span> http://localhost:8080/auth
</span></span></code></pre></div>
</div>

<div class="os-tab" data-label="Windows (PowerShell)">
<p class="os-tab-label">Windows (PowerShell)</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$token</span> <span class="p">=</span> <span class="p">(</span><span class="nb">Invoke-RestMethod</span> <span class="n">-Method</span> <span class="n">Post</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">  <span class="n">-Uri</span> <span class="n">https</span><span class="err">:</span><span class="p">//</span><span class="n">keycloak</span><span class="p">.</span><span class="py">example</span><span class="p">.</span><span class="n">com</span><span class="p">/</span><span class="n">realms</span><span class="p">/</span><span class="n">myrealm</span><span class="p">/</span><span class="n">protocol</span><span class="p">/</span><span class="nb">openid-connect</span><span class="p">/</span><span class="n">token</span> <span class="p">`</span>
</span></span><span class="line"><span class="cl">  <span class="n">-Body</span> <span class="vm">@</span><span class="p">{</span> <span class="n">grant_type</span> <span class="p">=</span> <span class="s2">&#34;client_credentials&#34;</span><span class="p">;</span> <span class="n">client_id</span> <span class="p">=</span> <span class="s2">&#34;my-client&#34;</span><span class="p">;</span> <span class="n">client_secret</span> <span class="p">=</span> <span class="nv">$env:CLIENT_SECRET</span> <span class="p">}).</span><span class="py">access_token</span>
</span></span><span class="line"><span class="cl"><span class="nb">Invoke-WebRequest</span> <span class="n">-Uri</span> <span class="n">http</span><span class="err">:</span><span class="p">//</span><span class="n">localhost</span><span class="err">:</span><span class="mf">8080</span><span class="p">/</span><span class="n">auth</span> <span class="n">-Headers</span> <span class="vm">@</span><span class="p">{</span> <span class="n">Authorization</span> <span class="p">=</span> <span class="s2">&#34;Bearer </span><span class="nv">$token</span><span class="s2">&#34;</span> <span class="p">}</span> <span class="p">|</span>
</span></span><span class="line"><span class="cl">  <span class="nb">Select-Object</span> <span class="n">StatusCode</span><span class="p">,</span> <span class="n">Headers</span>
</span></span></code></pre></div>
</div>

</div>

<p>A 200 with <code>X-Auth-Request-User</code>, <code>-Email</code>, <code>-Groups</code> and <code>-Roles</code> headers means it works. A 401 means the token was rejected; the JSON log on stderr says why, without logging the token.</p>
<h3 id="3-traefik">3. Traefik</h3>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-yaml" data-lang="yaml"><span class="line"><span class="cl"><span class="nt">http</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">  </span><span class="nt">middlewares</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">    </span><span class="nt">keycloak-auth</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">      </span><span class="nt">forwardAuth</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">address</span><span class="p">:</span><span class="w"> </span><span class="s2">&#34;http://auth-proxy:8080/auth&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">trustForwardHeader</span><span class="p">:</span><span class="w"> </span><span class="kc">false</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">        </span><span class="nt">authResponseHeaders</span><span class="p">:</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span>- <span class="s2">&#34;X-Auth-Request-User&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span>- <span class="s2">&#34;X-Auth-Request-Email&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span>- <span class="s2">&#34;X-Auth-Request-Groups&#34;</span><span class="w">
</span></span></span><span class="line"><span class="cl"><span class="w">          </span>- <span class="s2">&#34;X-Auth-Request-Roles&#34;</span><span class="w">
</span></span></span></code></pre></div><p><code>trustForwardHeader: false</code> matters. With <code>true</code>, Traefik passes the client&rsquo;s own <code>X-Forwarded-*</code> headers to the auth service. The proxy strips them anyway, but there is no reason to send them.</p>
<h3 id="4-nginx">4. nginx</h3>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-nginx" data-lang="nginx"><span class="line"><span class="cl"><span class="k">location</span> <span class="p">=</span> <span class="s">/_auth</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="kn">internal</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_pass</span> <span class="s">http://auth_proxy/auth</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_pass_request_body</span> <span class="no">off</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_set_header</span> <span class="s">Content-Length</span> <span class="s">&#34;&#34;</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_set_header</span> <span class="s">Authorization</span> <span class="nv">$http_authorization</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl"><span class="k">location</span> <span class="s">/</span> <span class="p">{</span>
</span></span><span class="line"><span class="cl">    <span class="kn">auth_request</span> <span class="s">/_auth</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">auth_request_set</span> <span class="nv">$auth_user</span> <span class="nv">$upstream_http_x_auth_request_user</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">auth_request_set</span> <span class="nv">$auth_roles</span> <span class="nv">$upstream_http_x_auth_request_roles</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">
</span></span><span class="line"><span class="cl">    <span class="c1"># do not forward client headers, including spoofed identity headers
</span></span></span><span class="line"><span class="cl">    <span class="kn">proxy_pass_request_headers</span> <span class="no">off</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_set_header</span> <span class="s">Content-Type</span> <span class="nv">$http_content_type</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_set_header</span> <span class="s">Accept</span> <span class="nv">$http_accept</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_set_header</span> <span class="s">X-Auth-Request-User</span> <span class="nv">$auth_user</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_set_header</span> <span class="s">X-Auth-Request-Roles</span> <span class="nv">$auth_roles</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_set_header</span> <span class="s">Authorization</span> <span class="s">&#34;&#34;</span><span class="p">;</span>
</span></span><span class="line"><span class="cl">    <span class="kn">proxy_pass</span> <span class="s">http://application</span><span class="p">;</span>
</span></span><span class="line"><span class="cl"><span class="p">}</span>
</span></span></code></pre></div><p><code>proxy_pass_request_headers off</code> looks drastic, but it is the only reliable way to make sure the backend never sees an <code>X_Auth_Request_User</code> the client made up. Add back the headers your app needs explicitly.</p>
<h3 id="5-route-rules-step-up-and-sso">5. Route rules, step-up and SSO</h3>
<p>In reverse-proxy mode, <code>ROUTE_RULES</code> sets requirements per method and path. This requires the <code>admin</code> realm role, authentication level <code>aal2</code> and an MFA login for every <code>POST</code> under <code>/admin</code>:</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="nv">ROUTE_RULES</span><span class="o">=</span><span class="s1">&#39;POST:/admin/*=realm:admin,acr:aal2,amr:mfa&#39;</span>
</span></span></code></pre></div><p>For browser SSO set <code>OIDC_ENABLED=true</code>, <code>CLIENT_ID</code>, <code>CLIENT_SECRET</code>, <code>OIDC_REDIRECT_URL</code> and a cookie secret of at least 32 characters:</p>
<div class="os-tabs">
<div class="os-tab" data-label="Linux / macOS">
<p class="os-tab-label">Linux / macOS</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-bash" data-lang="bash"><span class="line"><span class="cl"><span class="nb">export</span> <span class="nv">OIDC_COOKIE_SECRET</span><span class="o">=</span><span class="s2">&#34;</span><span class="k">$(</span>openssl rand -base64 32<span class="k">)</span><span class="s2">&#34;</span>
</span></span></code></pre></div>
</div>

<div class="os-tab" data-label="Windows (PowerShell)">
<p class="os-tab-label">Windows (PowerShell)</p>
<div class="highlight"><pre tabindex="0" class="chroma"><code class="language-powershell" data-lang="powershell"><span class="line"><span class="cl"><span class="nv">$bytes</span> <span class="p">=</span> <span class="p">[</span><span class="no">byte[]</span><span class="p">]::</span><span class="n">new</span><span class="p">(</span><span class="mf">32</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="p">[</span><span class="no">System.Security.Cryptography.RandomNumberGenerator</span><span class="p">]::</span><span class="n">Fill</span><span class="p">(</span><span class="nv">$bytes</span><span class="p">)</span>
</span></span><span class="line"><span class="cl"><span class="nv">$env:OIDC_COOKIE_SECRET</span> <span class="p">=</span> <span class="p">[</span><span class="no">Convert</span><span class="p">]::</span><span class="n">ToBase64String</span><span class="p">(</span><span class="nv">$bytes</span><span class="p">)</span>
</span></span></code></pre></div>
</div>

</div>

<p>The session lives in AES-256-GCM encrypted cookies, split into chunks because Keycloak tokens with many roles easily exceed the 4 KB cookie limit. The default cookie name has the <code>__Host-</code> prefix, which browsers only accept with <code>Secure</code>, without <code>Domain</code> and with <code>Path=/</code>. Refresh tokens are rotated once even when several tabs ask at the same moment, <code>/oauth2/logout</code> is CSRF protected, and Keycloak can end sessions through back-channel logout. The proxy strips its own cookies before forwarding, so the upstream never sees the session.</p>
<p>If you run Keycloak behind your own CA or with mutual TLS, <code>KEYCLOAK_CA_FILE</code> and <code>KEYCLOAK_CLIENT_CERT_FILE</code>/<code>KEYCLOAK_CLIENT_KEY_FILE</code> cover that. In my <span class="link-upcoming">Neuroclip post about Kubernetes behind Keycloak</span> I describe the same pattern from the application side: the app knows nothing about OIDC, and the proxy in front handles it.</p>
<h2 id="which-one-should-you-use">Which one should you use?</h2>
<ul>
<li>Several identity providers, or GitHub and Google login next to Keycloak: oauth2-proxy.</li>
<li>Identity-aware access for a whole company, with device posture and a policy language: Pomerium.</li>
<li>Keycloak only, and you want OPA policies, Redis-backed sessions and a project with years of history: gogatekeeper.</li>
<li>Keycloak only, forward-auth in Traefik or nginx with the lowest latency and a small dependency tree, and you are fine with v0.2.0: gocloak-auth-proxy.</li>
</ul>
<p>Reports from real traffic, and especially about where it breaks, are welcome as issues or private security reports in the <a href="https://github.com/Nerzal/gocloak-auth-proxy" rel="noopener">repository</a>.</p>
]]></content:encoded></item></channel></rss>