<?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>Encoding-Json-V2 | Tobias Theel | Senior Software Engineer</title><link>https://blog.noobygames.de/tags/encoding-json-v2/</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/encoding-json-v2/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></channel></rss>