<?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>Json | Tobias Theel | Senior Software Engineer</title><link>https://blog.noobygames.de/tags/json/</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>Sun, 22 Nov 2026 06:30:00 +0100</lastBuildDate><atom:link href="https://blog.noobygames.de/tags/json/index.xml" rel="self" type="application/rss+xml"/><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>