<?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>Graphviz | Tobias Theel | Senior Software Engineer</title><link>https://blog.noobygames.de/tags/graphviz/</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/graphviz/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></channel></rss>