<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Satyaki Saha</title>
    <description>The latest articles on DEV Community by Satyaki Saha (@satyaki_saha_367d015583da).</description>
    <link>https://dev.to/satyaki_saha_367d015583da</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F4138121%2Fe1e94ef8-3a9a-43c7-8876-dffabbc8935c.png</url>
      <title>DEV Community: Satyaki Saha</title>
      <link>https://dev.to/satyaki_saha_367d015583da</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/satyaki_saha_367d015583da"/>
    <language>en</language>
    <item>
      <title>A Missing Timeout, a Synchronised Block, and 205 Stuck Threads</title>
      <dc:creator>Satyaki Saha</dc:creator>
      <pubDate>Sun, 22 Nov 2026 06:45:17 +0000</pubDate>
      <link>https://dev.to/satyaki_saha_367d015583da/a-missing-timeout-a-synchronised-block-and-205-stuck-threads-1m93</link>
      <guid>https://dev.to/satyaki_saha_367d015583da/a-missing-timeout-a-synchronised-block-and-205-stuck-threads-1m93</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbfs1tfx8im1v1sn0hgva.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2Fbfs1tfx8im1v1sn0hgva.png" alt=" " width="800" height="339"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A few days ago our highest-traffic service started returning 504s on every call. There were no errors in the logs, no traces, and Kubernetes swore every pod was healthy. The root cause turned out to be one HTTP call without a timeout, sitting inside a &lt;code&gt;synchronized&lt;/code&gt; block.&lt;/p&gt;

&lt;p&gt;This is the story of how we found it, and the fixes I would apply to any service that has a cache, a lock and a remote call stacked together.&lt;/p&gt;

&lt;h2&gt;
  
  
  TL;DR
&lt;/h2&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Symptom:&lt;/strong&gt; every request returned 504 and the server logged nothing.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cause:&lt;/strong&gt; a token refresh ran inside a &lt;code&gt;synchronized&lt;/code&gt; method and called an auth service with no timeout. The call never returned, so all other threads queued behind the lock.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Why it stayed up:&lt;/strong&gt; the pod kept passing its health checks, so Kubernetes never restarted it.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Fix:&lt;/strong&gt; timeouts everywhere, &lt;code&gt;ReentrantLock&lt;/code&gt; with &lt;code&gt;tryLock&lt;/code&gt;, granular locks, no distributed lock for this case, and never &lt;code&gt;synchronized&lt;/code&gt; together with &lt;code&gt;@Transactional&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  The symptom: 504s and complete silence
&lt;/h2&gt;

&lt;p&gt;It was the service that handles more API calls than any other in our system. Every request began returning &lt;strong&gt;504 Gateway Timeout&lt;/strong&gt;. On the client side the call sat in the &lt;em&gt;transfer&lt;/em&gt; phase until the gateway gave up.&lt;/p&gt;

&lt;p&gt;On the server side there was nothing: no exception, no slow-query warning, no error log. We had no distributed tracing on this path either, so there was no span to open and no trail to follow. From the outside the service looked alive. From the inside it was saying nothing at all.&lt;/p&gt;

&lt;h2&gt;
  
  
  The wrong suspect: our Kubernetes setup
&lt;/h2&gt;

&lt;p&gt;When requests die before your code logs anything, the instinct is to blame what sits in front of it. So we went deep on the platform:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Ingress: configuration and logs were healthy.&lt;/li&gt;
&lt;li&gt;Load balancer: IP configuration and routing looked correct.&lt;/li&gt;
&lt;li&gt;Cluster: &lt;code&gt;kubectl describe&lt;/code&gt; on pods, services and endpoints showed nothing unusual.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Everything came back clean. That was the first real clue, although we did not read it that way yet. &lt;strong&gt;When the infrastructure is innocent and the application is silent, the process is usually alive but no longer doing work.&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;So we took a heap dump and a thread dump. The heap dump gave us nothing: memory looked normal, and a heap dump shows what objects exist, not what threads are doing. The thread dump did not disappoint.&lt;/p&gt;

&lt;h2&gt;
  
  
  What the thread dump said
&lt;/h2&gt;

&lt;p&gt;&lt;strong&gt;205 platform threads were sitting in a waiting state.&lt;/strong&gt; That is roughly the size of a default servlet container worker pool (Tomcat ships with 200), so in practice &lt;em&gt;every thread that could serve a request was stuck&lt;/em&gt;. New requests had nowhere to run, queued up, and the gateway timed them out with a 504. That also explains the silence: a request that never gets a thread never reaches a log statement.&lt;/p&gt;

&lt;p&gt;All 205 stacks looked the same, and they all led to one place:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Feign client call
  -&amp;gt; request interceptor needs an access token
    -&amp;gt; token provider: cached token expired
      -&amp;gt; synchronized refresh method   &amp;lt;- every other thread queues here
        -&amp;gt; HTTP GET to the authentication service   &amp;lt;- the first thread is stuck here
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Two habits made this findable:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Take two or three dumps a few seconds apart.&lt;/strong&gt; If the same threads sit on the same frames each time, you are looking at a stall, not slow work.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Find the lock owner.&lt;/strong&gt; Waiters show &lt;code&gt;waiting to lock &amp;lt;0x...&amp;gt;&lt;/code&gt;, and one thread shows &lt;code&gt;locked &amp;lt;0x...&amp;gt;&lt;/code&gt; for that same address. That thread is the one to read first. A thread blocked on a socket read still looks &lt;em&gt;runnable&lt;/em&gt; to the JVM, so the culprit is easy to skip if you only scan for blocked threads.&lt;/li&gt;
&lt;/ol&gt;

&lt;h2&gt;
  
  
  Anatomy of the stall
&lt;/h2&gt;

&lt;p&gt;dev.to does not render diagrams from code, so here is the flow as text:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Incoming request
      |
      v
Feign call needs a token
      |
      v
Cached token has expired
      |
      v
synchronized refresh method
      |
      +--&amp;gt; FIRST thread in: holds the lock
      |      HTTP GET to the auth service, no timeout, no reply   &amp;lt;-- root cause
      |
      +--&amp;gt; EVERY OTHER thread: waits for the same lock
             queued behind the first thread, which never completes
                          |
                          v
   All worker threads parked: new requests queue, gateway returns 504
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first thread to find an expired token took the lock and called the authentication service, and with no timeout that call never came back. Every other thread that needed a token joined the queue behind it, until none were left to serve requests.&lt;/p&gt;

&lt;h2&gt;
  
  
  Why Kubernetes never restarted the pod
&lt;/h2&gt;

&lt;p&gt;The service was completely stalled, and Kubernetes still considered every pod healthy. That is not a Kubernetes bug. A probe answers one narrow question, &lt;em&gt;is this process responding the way I check?&lt;/em&gt;, and a JVM with every worker thread parked can still answer a TCP check, or an endpoint served from a separate management port and thread pool.&lt;/p&gt;

&lt;p&gt;What we needed was signals that measure &lt;em&gt;ability to do work&lt;/em&gt;, not just liveness:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Signal&lt;/th&gt;
&lt;th&gt;What it would have shown&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;Busy worker threads vs. pool max&lt;/td&gt;
&lt;td&gt;Pinned at the maximum within seconds of the stall&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Latency histogram on the outbound auth call&lt;/td&gt;
&lt;td&gt;One call that never completes, so the p99 grows without bound&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Distributed tracing&lt;/td&gt;
&lt;td&gt;A single span stuck inside the token fetch, with 200+ requests queued behind it&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;Alert on in-flight requests&lt;/td&gt;
&lt;td&gt;A line going up and never coming down&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;

&lt;p&gt;A word of caution: do not make your liveness probe call downstream dependencies. If the auth service is down, you would restart every healthy pod and turn a partial outage into a total one. Alert on saturation instead and let a human or an autoscaler decide.&lt;/p&gt;

&lt;h2&gt;
  
  
  The second trap: &lt;code&gt;synchronized&lt;/code&gt; and &lt;code&gt;@Transactional&lt;/code&gt; together
&lt;/h2&gt;

&lt;p&gt;While digging through this code we found a related pattern that deserves its own warning. It looks harmless:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;AccountService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Transactional&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;synchronized&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;debit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;accountId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;BigDecimal&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;Account&lt;/span&gt; &lt;span class="n"&gt;account&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;accountRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findById&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;accountId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;orElseThrow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="n"&gt;account&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setBalance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;account&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getBalance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;subtract&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It reads like "only one thread at a time can debit, inside a transaction". It does not do that, for four reasons:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;The lock is released before the commit.&lt;/strong&gt; Spring wraps the method in a proxy. The transaction starts before the method runs and commits after it returns, and &lt;code&gt;synchronized&lt;/code&gt; only covers the method body. Thread B can enter, read the old balance, and overwrite thread A's change. The lock gave you a feeling of safety and none of the guarantee.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Waiting threads hold database connections.&lt;/strong&gt; The proxy usually opens the transaction, and takes a connection, before the thread ever reaches the monitor. Threads queued on the lock sit on pooled connections, and a small pool is exhausted by a handful of waiters. Then even endpoints that never touch this lock start timing out.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;It only works inside one JVM.&lt;/strong&gt; Two pods have two monitors, so they can still race each other on the same row.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Slow work inside the lock stretches the transaction.&lt;/strong&gt; Put a remote call in there and you have rebuilt our incident, with an open transaction on top.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;The correct tool for protecting a row is the database, which is where the cure section ends up.&lt;/p&gt;

&lt;h2&gt;
  
  
  The cure: five fixes, in the order they matter
&lt;/h2&gt;

&lt;p&gt;The root cause was a missing timeout. The lock only turned one slow call into a service-wide outage. Fix the cause first, then make the lock safe.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Put a timeout on every outbound call
&lt;/h3&gt;

&lt;p&gt;Many HTTP clients wait forever by default, including &lt;code&gt;HttpURLConnection&lt;/code&gt; and &lt;code&gt;java.net.http.HttpClient&lt;/code&gt;. An unbounded wait is a bug waiting for its worst day. Every call needs a connect timeout, a read timeout and an overall deadline.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight yaml"&gt;&lt;code&gt;&lt;span class="na"&gt;spring&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
  &lt;span class="na"&gt;cloud&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
    &lt;span class="na"&gt;openfeign&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
      &lt;span class="na"&gt;client&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
        &lt;span class="na"&gt;config&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
          &lt;span class="na"&gt;default&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt;
            &lt;span class="na"&gt;connectTimeout&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;2000&lt;/span&gt;   &lt;span class="c1"&gt;# ms
&lt;/span&gt;            &lt;span class="na"&gt;readTimeout&lt;/span&gt;&lt;span class="p"&gt;:&lt;/span&gt; &lt;span class="mi"&gt;5000&lt;/span&gt;      &lt;span class="c1"&gt;# ms
&lt;/span&gt;&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nc"&gt;HttpClient&lt;/span&gt; &lt;span class="n"&gt;client&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;HttpClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;newBuilder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;connectTimeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Duration&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ofSeconds&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nc"&gt;HttpRequest&lt;/span&gt; &lt;span class="n"&gt;request&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="nc"&gt;HttpRequest&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;newBuilder&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;tokenUri&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;timeout&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;Duration&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;ofSeconds&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;3&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;   &lt;span class="c1"&gt;// total time for the response&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;GET&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
        &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Pair this with a circuit breaker such as Resilience4j so that a dead dependency fails fast instead of being retried by every thread.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Replace &lt;code&gt;synchronized&lt;/code&gt; with &lt;code&gt;ReentrantLock&lt;/code&gt; and &lt;code&gt;tryLock&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;The real weakness of &lt;code&gt;synchronized&lt;/code&gt; is not that it is slow. It is that &lt;strong&gt;a waiting thread cannot give up&lt;/strong&gt;. &lt;code&gt;ReentrantLock&lt;/code&gt; lets a thread wait for a bounded time, fall back, or fail fast. Reentrancy itself is a minor feature here; &lt;code&gt;tryLock(timeout)&lt;/code&gt; is the point.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Component&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;TokenProvider&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;ReentrantLock&lt;/span&gt; &lt;span class="n"&gt;refreshLock&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ReentrantLock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="k"&gt;volatile&lt;/span&gt; &lt;span class="nc"&gt;CachedToken&lt;/span&gt; &lt;span class="n"&gt;cached&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;AuthClient&lt;/span&gt; &lt;span class="n"&gt;authClient&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;TokenProvider&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;AuthClient&lt;/span&gt; &lt;span class="n"&gt;authClient&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;authClient&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;authClient&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;getToken&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="nc"&gt;CachedToken&lt;/span&gt; &lt;span class="n"&gt;token&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;cached&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;token&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;token&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;nearExpiry&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;token&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;value&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;                       &lt;span class="c1"&gt;// fast path, no lock&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;

        &lt;span class="kt"&gt;boolean&lt;/span&gt; &lt;span class="n"&gt;locked&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="kc"&gt;false&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;locked&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;refreshLock&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;tryLock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;TimeUnit&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;SECONDS&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;locked&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="c1"&gt;// someone else is refreshing and it is taking too long&lt;/span&gt;
                &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;token&lt;/span&gt; &lt;span class="o"&gt;!=&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt; &lt;span class="o"&gt;&amp;amp;&amp;amp;&lt;/span&gt; &lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;token&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;expired&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;token&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;value&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;               &lt;span class="c1"&gt;// stale but still valid&lt;/span&gt;
                &lt;span class="p"&gt;}&lt;/span&gt;
                &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;TokenUnavailableException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Token refresh timed out"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="n"&gt;token&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;cached&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;                             &lt;span class="c1"&gt;// double-check after locking&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;token&lt;/span&gt; &lt;span class="o"&gt;==&lt;/span&gt; &lt;span class="k"&gt;null&lt;/span&gt; &lt;span class="o"&gt;||&lt;/span&gt; &lt;span class="n"&gt;token&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;nearExpiry&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;token&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;authClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fetchToken&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;        &lt;span class="c1"&gt;// has its own read timeout&lt;/span&gt;
                &lt;span class="n"&gt;cached&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;token&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;token&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;value&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;catch&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;InterruptedException&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="nc"&gt;Thread&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;currentThread&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;interrupt&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;TokenUnavailableException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Interrupted while waiting"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;e&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;finally&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;locked&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
                &lt;span class="n"&gt;refreshLock&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;unlock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
            &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Three details carry the design: the unlocked fast path, the double-check after acquiring the lock, and the fallback to a stale-but-valid token. Refreshing a little &lt;em&gt;before&lt;/em&gt; expiry (say at 80% of the token lifetime) makes that fallback available almost every time.&lt;/p&gt;

&lt;h3&gt;
  
  
  3. Use granular locks
&lt;/h3&gt;

&lt;p&gt;One global lock means one slow dependency stalls everything that shares it. Lock per key instead, here per client or scope, so a stuck refresh blocks only the callers that truly need that token.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;ConcurrentMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;TokenSlot&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;slots&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;ConcurrentHashMap&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&amp;gt;&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;tokenFor&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;clientId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
    &lt;span class="nc"&gt;TokenSlot&lt;/span&gt; &lt;span class="n"&gt;slot&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;slots&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;computeIfAbsent&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;clientId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;TokenSlot&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;slot&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="o"&gt;-&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;authClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;fetchToken&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;clientId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;   &lt;span class="c1"&gt;// same tryLock logic, one lock per slot&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The same principle applies anywhere you lock: keep the critical section as small as you can and never perform network I/O inside it unless that I/O is strictly bounded.&lt;/p&gt;

&lt;h3&gt;
  
  
  4. Do not reach for a distributed lock here
&lt;/h3&gt;

&lt;p&gt;It is tempting to say "let us coordinate the refresh across all pods with Redis or the database". For a token cache it does not help, and it adds risk:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Each pod needs its own valid token anyway, so duplicate refreshes across pods are harmless. The lock only needs to stop a stampede &lt;em&gt;inside one JVM&lt;/em&gt;.&lt;/li&gt;
&lt;li&gt;A distributed lock is a new dependency with its own network calls, and those calls need timeouts too. A lock holder that dies leaves a lock that nobody releases unless it carries an expiry (a lease or TTL).&lt;/li&gt;
&lt;li&gt;You have swapped one remote call that can hang for another.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Distributed locks are the right tool when pods must not run the same job at once, such as a scheduled task (ShedLock does this well). Always give them a TTL.&lt;/p&gt;

&lt;h3&gt;
  
  
  5. Never combine &lt;code&gt;synchronized&lt;/code&gt; with &lt;code&gt;@Transactional&lt;/code&gt;
&lt;/h3&gt;

&lt;p&gt;Let the database arbitrate, because it is the only party that sees all pods and knows when a commit really happened. With JPA you have two options. &lt;strong&gt;Optimistic locking&lt;/strong&gt; lets concurrent writers race and makes the loser retry:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Entity&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;Account&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Id&lt;/span&gt;
    &lt;span class="nd"&gt;@GeneratedValue&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="nc"&gt;BigDecimal&lt;/span&gt; &lt;span class="n"&gt;balance&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="nd"&gt;@Version&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kt"&gt;long&lt;/span&gt; &lt;span class="n"&gt;version&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;   &lt;span class="c1"&gt;// an update fails if another writer got there first&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;Pessimistic locking&lt;/strong&gt; serialises writers on the row, with a bounded wait:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;interface&lt;/span&gt; &lt;span class="nc"&gt;AccountRepository&lt;/span&gt; &lt;span class="k"&gt;extends&lt;/span&gt; &lt;span class="nc"&gt;JpaRepository&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Lock&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;LockModeType&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;PESSIMISTIC_WRITE&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nd"&gt;@QueryHints&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@QueryHint&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;name&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"jakarta.persistence.lock.timeout"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;value&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="s2"&gt;"3000"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"select a from Account a where a.id = :id"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
    &lt;span class="nc"&gt;Optional&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Account&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;findByIdForUpdate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"id"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="kt"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Service&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;AccountService&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="nd"&gt;@Transactional&lt;/span&gt;
    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;void&lt;/span&gt; &lt;span class="nf"&gt;debit&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;Long&lt;/span&gt; &lt;span class="n"&gt;accountId&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;BigDecimal&lt;/span&gt; &lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;   &lt;span class="c1"&gt;// no synchronized&lt;/span&gt;
        &lt;span class="nc"&gt;Account&lt;/span&gt; &lt;span class="n"&gt;account&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;accountRepository&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;findByIdForUpdate&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;accountId&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;orElseThrow&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="n"&gt;account&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;setBalance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;account&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;getBalance&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;subtract&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="n"&gt;amount&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The row lock is held until the transaction commits, which is exactly the guarantee &lt;code&gt;synchronized&lt;/code&gt; could not give. It works across pods, and the lock timeout means a waiter gives up instead of hanging.&lt;/p&gt;

&lt;h2&gt;
  
  
  What to audit in your own services this week
&lt;/h2&gt;

&lt;p&gt;None of the individual pieces here was exotic. A cache, a lock and an HTTP call is a design most services contain somewhere. The failure came from how they stacked, so audit the stack:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Every outbound HTTP, Feign, JDBC and message-broker call has an explicit timeout. Search your code for clients built with defaults.&lt;/li&gt;
&lt;li&gt;No lock is held across network I/O unless that I/O is strictly bounded.&lt;/li&gt;
&lt;li&gt;Every lock that can queue threads offers a way out: &lt;code&gt;tryLock(timeout)&lt;/code&gt;, a lock timeout in the database, or a lease on a distributed lock.&lt;/li&gt;
&lt;li&gt;Token and credential refresh happens ahead of expiry, and a stale-but-valid token is an acceptable fallback.&lt;/li&gt;
&lt;li&gt;No &lt;code&gt;synchronized&lt;/code&gt; method carries &lt;code&gt;@Transactional&lt;/code&gt;. Use &lt;code&gt;@Version&lt;/code&gt; or a pessimistic lock with a timeout instead.&lt;/li&gt;
&lt;li&gt;You graph busy threads against pool size and the latency of each dependency, and you alert on saturation.&lt;/li&gt;
&lt;li&gt;Tracing is on for the highest-traffic paths, so the next stuck call shows up as a span instead of silence.&lt;/li&gt;
&lt;li&gt;You know the thread-dump command for your runtime and have practised it in a pod: &lt;code&gt;jcmd &amp;lt;pid&amp;gt; Thread.print&lt;/code&gt; or &lt;code&gt;kill -3 &amp;lt;pid&amp;gt;&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;One last point: virtual threads will not rescue you from this. Millions of cheap threads can all queue behind one lock held across an unbounded call. Timeouts are what end the wait, and the fix works the same on any kind of thread.&lt;/p&gt;

&lt;p&gt;We found this one by luck and a thread dump. The goal is to find the next one by a dashboard.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Have you been bitten by a missing timeout or a lock held across a remote call? Tell me what it looked like in the comments.&lt;/strong&gt;&lt;/p&gt;

</description>
      <category>devops</category>
      <category>java</category>
      <category>kubernetes</category>
      <category>systemdesign</category>
    </item>
    <item>
      <title>Why Our Java Memory Crept Up on Flat Traffic: A Modern Stack Post-Mortem</title>
      <dc:creator>Satyaki Saha</dc:creator>
      <pubDate>Sat, 14 Nov 2026 10:48:04 +0000</pubDate>
      <link>https://dev.to/satyaki_saha_367d015583da/why-our-java-memory-crept-up-on-flat-traffic-a-modern-stack-post-mortem-4lpa</link>
      <guid>https://dev.to/satyaki_saha_367d015583da/why-our-java-memory-crept-up-on-flat-traffic-a-modern-stack-post-mortem-4lpa</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0a4a7cmh1zptyynj4yhw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F0a4a7cmh1zptyynj4yhw.png" alt=" " width="800" height="437"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;strong&gt;TL;DR:&lt;/strong&gt; After upgrading our stack, our Java service's memory usage kept climbing steadily despite flat request volumes. It looked like a single memory leak on our APM dashboard, but digging deeper revealed &lt;strong&gt;three separate issues working together&lt;/strong&gt;: virtual thread payload retention, an unbounded ANTLR 4 static DFA cache in Hibernate 7, and elevated baseline class loading. Here is how we diagnosed and fixed each one.&lt;/p&gt;
&lt;/blockquote&gt;




&lt;h2&gt;
  
  
  🔍 The Symptoms
&lt;/h2&gt;

&lt;p&gt;Right after migrating our core service to &lt;strong&gt;JDK 25&lt;/strong&gt; and &lt;strong&gt;Spring Boot 4.1&lt;/strong&gt; (which brings in Hibernate 7.4), we noticed our memory graph taking an upward slope:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Memory (MB)
  ^
  |          /---- Spikes (Virtual Threads)
  |         /
  |  /\    /|    /---- Steady Growth (ANTLR 4 DFA Cache)
  | /  \  / |   /
  |/____\/__|__/______ Baseline Shift (38.8k Classes Loaded)
  +-------------------------------------&amp;gt; Time
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Request volume was completely flat. Our high-level metrics suggested a classic memory leak, but a single fix didn't resolve it. We were actually fighting &lt;strong&gt;three distinct memory behaviors&lt;/strong&gt; disguised as one issue on our graphs.&lt;/p&gt;




&lt;h2&gt;
  
  
  🚨 Issue 1: Unbounded Virtual Threads &amp;amp; Memory Spikes
&lt;/h2&gt;

&lt;p&gt;Virtual threads are lightweight, but the &lt;strong&gt;payload data&lt;/strong&gt; they process on the heap is not. &lt;/p&gt;

&lt;p&gt;Once we enabled virtual threads without capping concurrency on high-throughput or heavy outbound operations, sudden traffic micro-bursts executed fully in parallel. Every in-flight request retained its object graph on the heap simultaneously.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Double Hit
&lt;/h3&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Downstream Overwhelm:&lt;/strong&gt; Downstream services got slammed without backpressure.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Heap Pressure:&lt;/strong&gt; Heap allocation spiked rapidly, causing aggressive GC pauses during traffic bursts.&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;While this wasn't responsible for the long-term steady memory growth, it magnified transient spikes.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Fix: Target Concurrency at the Outbound Layer
&lt;/h3&gt;

&lt;p&gt;Rather than throttling threads globally, cap concurrency where work gets expensive—such as downstream client calls. A bounded-wait &lt;code&gt;Semaphore&lt;/code&gt; fails fast so queued requests don't hang around filling up the heap.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="k"&gt;package&lt;/span&gt; &lt;span class="n"&gt;com&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;example&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;org&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;springframework&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;stereotype&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Component&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;org&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;springframework&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;web&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;client&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;RestClient&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;java&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;util&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;concurrent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Semaphore&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;span class="k"&gt;import&lt;/span&gt; &lt;span class="n"&gt;java&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;util&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;concurrent&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;TimeUnit&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

&lt;span class="nd"&gt;@Component&lt;/span&gt;
&lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="k"&gt;class&lt;/span&gt; &lt;span class="nc"&gt;DownstreamClient&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;

    &lt;span class="c1"&gt;// Size this to downstream capacity&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;Semaphore&lt;/span&gt; &lt;span class="n"&gt;permits&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;Semaphore&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;50&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="k"&gt;private&lt;/span&gt; &lt;span class="kd"&gt;final&lt;/span&gt; &lt;span class="nc"&gt;RestClient&lt;/span&gt; &lt;span class="n"&gt;restClient&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="nc"&gt;DownstreamClient&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nc"&gt;RestClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nc"&gt;Builder&lt;/span&gt; &lt;span class="n"&gt;builder&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;this&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="n"&gt;restClient&lt;/span&gt; &lt;span class="o"&gt;=&lt;/span&gt; &lt;span class="n"&gt;builder&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;baseUrl&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"https://downstream.example"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;build&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;

    &lt;span class="k"&gt;public&lt;/span&gt; &lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="nf"&gt;fetch&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="k"&gt;throws&lt;/span&gt; &lt;span class="nc"&gt;InterruptedException&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
        &lt;span class="k"&gt;if&lt;/span&gt; &lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="o"&gt;!&lt;/span&gt;&lt;span class="n"&gt;permits&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;tryAcquire&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="mi"&gt;2&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="nc"&gt;TimeUnit&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="no"&gt;SECONDS&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;throw&lt;/span&gt; &lt;span class="k"&gt;new&lt;/span&gt; &lt;span class="nc"&gt;IllegalStateException&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"Downstream is saturated, try again later"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
        &lt;span class="k"&gt;try&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="k"&gt;return&lt;/span&gt; &lt;span class="n"&gt;restClient&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;get&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;uri&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"/items/{id}"&lt;/span&gt;&lt;span class="p"&gt;,&lt;/span&gt; &lt;span class="n"&gt;id&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;retrieve&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
                    &lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;body&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="kt"&gt;String&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="k"&gt;class&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt; &lt;span class="k"&gt;finally&lt;/span&gt; &lt;span class="p"&gt;{&lt;/span&gt;
            &lt;span class="n"&gt;permits&lt;/span&gt;&lt;span class="p"&gt;.&lt;/span&gt;&lt;span class="nf"&gt;release&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
        &lt;span class="p"&gt;}&lt;/span&gt;
    &lt;span class="p"&gt;}&lt;/span&gt;
&lt;span class="p"&gt;}&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  💡 Additional Concurrency Controls across Layers
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Inbound Traffic:&lt;/strong&gt; Tune &lt;code&gt;server.tomcat.max-connections&lt;/code&gt; and &lt;code&gt;server.tomcat.accept-count&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Queue Consumers:&lt;/strong&gt; Bound max concurrent messages on SQS/Kafka listeners.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Database Connection Pools:&lt;/strong&gt; Limit Hikari pool size (remember: waiting threads still hold request objects in memory!).&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Spring Framework 7:&lt;/strong&gt; Check out &lt;code&gt;@ConcurrencyLimit&lt;/code&gt; for declarative control.&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  🕳️ Issue 2: Hibernate 7's ANTLR 4 Static DFA Cache Growth
&lt;/h2&gt;

&lt;p&gt;This was the actual culprit behind the &lt;strong&gt;steady long-term memory climb&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  How Hibernate Query Caching Works
&lt;/h3&gt;

&lt;p&gt;Hibernate parses HQL/JPQL strings into internal AST trees and caches them in the &lt;code&gt;QueryInterpretationCache&lt;/code&gt;. The default capacity is &lt;code&gt;2048&lt;/code&gt; entries (&lt;code&gt;hibernate.query.plan_cache_max_size&lt;/code&gt;).&lt;/p&gt;

&lt;p&gt;Several endpoints in our service executed SQL &lt;code&gt;IN&lt;/code&gt; queries with dynamically built, variable-length parameter lists:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight java"&gt;&lt;code&gt;&lt;span class="nd"&gt;@Query&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"select o from Order o where o.id in :ids"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;
&lt;span class="kt"&gt;List&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="nc"&gt;Order&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="nf"&gt;findByIds&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="nd"&gt;@Param&lt;/span&gt;&lt;span class="p"&gt;(&lt;/span&gt;&lt;span class="s2"&gt;"ids"&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt; &lt;span class="nc"&gt;Collection&lt;/span&gt;&lt;span class="o"&gt;&amp;lt;&lt;/span&gt;&lt;span class="kt"&gt;Long&lt;/span&gt;&lt;span class="o"&gt;&amp;gt;&lt;/span&gt; &lt;span class="n"&gt;ids&lt;/span&gt;&lt;span class="p"&gt;)&lt;/span&gt;&lt;span class="p"&gt;;&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Passing a collection of 3 elements produced a different query shape than a collection of 5 or 12 elements. This flooded the cache with thousands of unique query structures.&lt;/p&gt;

&lt;h3&gt;
  
  
  The Hidden ANTLR 4 Gotcha
&lt;/h3&gt;

&lt;p&gt;Under the hood, Hibernate 6 and 7 use &lt;strong&gt;ANTLR 4&lt;/strong&gt; for parsing HQL (replacing ANTLR 2 used in Hibernate 5). &lt;/p&gt;

&lt;p&gt;When we examined our heap dumps in Eclipse MAT, the memory wasn't tied up in Hibernate's query plan cache—it was dominated by:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;org.antlr.v4.runtime.atn.DFAState&lt;/code&gt;&lt;/li&gt;
&lt;li&gt;&lt;code&gt;org.antlr.v4.runtime.atn.*&lt;/code&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Key Takeaway:&lt;/strong&gt; ANTLR 4 maintains a &lt;strong&gt;static DFA (Deterministic Finite Automaton) cache&lt;/strong&gt; shared across the entire JVM. It has &lt;strong&gt;no maximum size setting&lt;/strong&gt;, &lt;strong&gt;never evicts entries&lt;/strong&gt;, and grows indefinitely as the parser encounters new query shapes. &lt;code&gt;hibernate.query.plan_cache_max_size&lt;/code&gt; will &lt;strong&gt;not&lt;/strong&gt; cap it!&lt;/p&gt;

&lt;h3&gt;
  
  
  The Fix
&lt;/h3&gt;

&lt;p&gt;To keep query shapes static regardless of array or collection sizes:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;
&lt;strong&gt;Enable IN-clause padding&lt;/strong&gt; in your application properties:
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight properties"&gt;&lt;code&gt;   &lt;span class="na"&gt;hibernate.query.in_clause_parameter_padding&lt;/span&gt;&lt;span class="o"&gt;=&lt;/span&gt;&lt;span class="kc"&gt;true&lt;/span&gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ol&gt;
&lt;li&gt;Always bind collections as parameters rather than building dynamic HQL strings.&lt;/li&gt;
&lt;/ol&gt;




&lt;h2&gt;
  
  
  🏗️ Issue 3: High Baseline Class Loading
&lt;/h2&gt;

&lt;p&gt;Following our migration, our service loaded roughly &lt;strong&gt;38.8k classes&lt;/strong&gt; at startup. Pulling in dependencies like AWS SQS (which brought in Netty), coupled with framework updates across JDK 25 and Spring Boot 4.1, pushed our baseline off-heap memory usage noticeably higher.&lt;/p&gt;

&lt;h3&gt;
  
  
  Mitigation vs. Root Cause Fix
&lt;/h3&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Mitigation:&lt;/strong&gt; Setting strict limits on Metaspace (&lt;code&gt;-XX:MaxMetaspaceSize&lt;/code&gt;) and sizing Max RAM percentage (&lt;code&gt;-XX:MaxRAMPercentage&lt;/code&gt;) prevents container OOM kills, but it only contains symptoms.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Root Cause Fix:&lt;/strong&gt; To actually lower off-heap baseline footprint, run dependency analysis tools to prune unused transitives and explicitly disable unneeded Spring auto-configurations (&lt;code&gt;@SpringBootApplication(exclude = ...)&lt;/code&gt;).&lt;/li&gt;
&lt;/ul&gt;




&lt;h2&gt;
  
  
  📊 Summary Diagnostic Playbook
&lt;/h2&gt;

&lt;p&gt;Different memory symptoms demand different diagnostic tools:&lt;/p&gt;

&lt;div class="table-wrapper-paragraph"&gt;&lt;table&gt;
&lt;thead&gt;
&lt;tr&gt;
&lt;th&gt;Symptom&lt;/th&gt;
&lt;th&gt;Primary Suspect&lt;/th&gt;
&lt;th&gt;Diagnostic Tool / Strategy&lt;/th&gt;
&lt;th&gt;Actionable Fix&lt;/th&gt;
&lt;/tr&gt;
&lt;/thead&gt;
&lt;tbody&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Sharp Spikes&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Unbounded Concurrency / Payload Retention&lt;/td&gt;
&lt;td&gt;Thread Dumps, APM Concurrency Metrics&lt;/td&gt;
&lt;td&gt;Apply &lt;code&gt;Semaphore&lt;/code&gt;, rate-limit consumers&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;Steady Upward Slope&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Dynamic Parser Caches (e.g. ANTLR DFA)&lt;/td&gt;
&lt;td&gt;Eclipse MAT / Heap Dump OQL&lt;/td&gt;
&lt;td&gt;Enable &lt;code&gt;in_clause_parameter_padding&lt;/code&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;tr&gt;
&lt;td&gt;&lt;strong&gt;High Elevated Baseline&lt;/strong&gt;&lt;/td&gt;
&lt;td&gt;Excess Class Load &amp;amp; Off-Heap Metaspace&lt;/td&gt;
&lt;td&gt;Native Memory Tracking (NMT), &lt;code&gt;-verbose:class&lt;/code&gt;
&lt;/td&gt;
&lt;td&gt;Exclude unused dependencies &amp;amp; auto-configs&lt;/td&gt;
&lt;/tr&gt;
&lt;/tbody&gt;
&lt;/table&gt;&lt;/div&gt;




&lt;h3&gt;
  
  
  💬 Discussion
&lt;/h3&gt;

&lt;p&gt;Have you encountered unexpected memory behavior after upgrading to Hibernate 7 or enabling Virtual Threads in production? Let me know down in the comments!&lt;/p&gt;

</description>
      <category>backend</category>
      <category>debugging</category>
      <category>java</category>
      <category>devops</category>
    </item>
    <item>
      <title>Just Add More Database Connections Is a System Design Trap</title>
      <dc:creator>Satyaki Saha</dc:creator>
      <pubDate>Sat, 03 Oct 2026 04:18:47 +0000</pubDate>
      <link>https://dev.to/satyaki_saha_367d015583da/just-add-more-database-connections-is-a-system-design-trap-5fnn</link>
      <guid>https://dev.to/satyaki_saha_367d015583da/just-add-more-database-connections-is-a-system-design-trap-5fnn</guid>
      <description>&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8ub71zkk9ck7if1rsmhh.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Farticles%2F8ub71zkk9ck7if1rsmhh.png" alt=" " width="799" height="436"&gt;&lt;/a&gt;&lt;br&gt;
During system design interviews or production firefighting sessions, a common piece of logic always resurfaces: &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;&lt;em&gt;"If our Hibernate threads are starving for database connections, why don't we just set the connection pool size to 1000? More connections means more parallel queries, which means better database CPU usage... right?"&lt;/em&gt;&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Wrong.&lt;/strong&gt; It sounds intuitive, but in production, this naive scaling approach will actively slow down your system—and under the right circumstances, trigger a total database outage. &lt;/p&gt;

&lt;p&gt;Here is what actually happens when you bloat your connection pool, and the production-grade solutions you should implement instead.&lt;/p&gt;


&lt;h2&gt;
  
  
  1. Latency Gets Worse, Not Better (The Myth of Infinite Parallelism)
&lt;/h2&gt;

&lt;p&gt;Imagine a database server running on a machine with &lt;strong&gt;8 CPU cores&lt;/strong&gt;. If you give your application instances hundreds of active connections, all trying to execute heavy queries simultaneously, the database doesn't magically work faster. It thrashes.&lt;/p&gt;

&lt;p&gt;Instead of doing actual processing work, the operating system spends its precious CPU execution cycles doing this:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Context Switching:&lt;/strong&gt; Rapidly swapping execution context between hundreds of competing database threads.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Lock Contention:&lt;/strong&gt; Waiting on row-level or table-level database locks.&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Cache Thrashing:&lt;/strong&gt; Ruining CPU L1/L2 cache locality as threads fight for resources.&lt;/li&gt;
&lt;/ul&gt;
&lt;h3&gt;
  
  
  The Downstream Effect
&lt;/h3&gt;

&lt;p&gt;When context switching takes over, &lt;strong&gt;each individual query takes longer to complete&lt;/strong&gt;. Because queries take longer, &lt;strong&gt;connections are held open longer&lt;/strong&gt;. As connections stay occupied, new incoming requests pile up in the application queue. You haven't increased throughput; you have simply turned a high-performance database into a severe traffic jam.&lt;/p&gt;


&lt;h2&gt;
  
  
  2. How Kubernetes HPA Turns a Slowdown Into an Outage
&lt;/h2&gt;

&lt;p&gt;Things get dangerous when you mix giant connection pools with cloud native auto-scaling infrastructure like a Kubernetes &lt;strong&gt;Horizontal Pod Autoscaler (HPA)&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;Imagine this textbook disaster scenario:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Your database starts slowing down due to CPU thrashing.&lt;/li&gt;
&lt;li&gt;Because queries take longer, application response times spike.&lt;/li&gt;
&lt;li&gt;The Kubernetes HPA sees the high latency (or CPU utilization) on your app pods and triggers a scale-out event to save the day—scaling your microservice from &lt;strong&gt;2 pods to 8 pods&lt;/strong&gt;.&lt;/li&gt;
&lt;li&gt;If each pod has a direct connection pool size of &lt;strong&gt;100&lt;/strong&gt;, your deployment suddenly attempts to open &lt;strong&gt;800 client connections&lt;/strong&gt; simultaneously (&lt;code&gt;8 pods × 100 connections&lt;/code&gt;).&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;If your Postgres &lt;code&gt;max_connections&lt;/code&gt; configuration limit is capped at &lt;strong&gt;200&lt;/strong&gt;, the autoscaler that was supposed to save your application just delivered the killing blow:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;FATAL: sorry, too many clients already
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Your system shifts instantly from a minor traffic slowdown into a hard production outage.&lt;/p&gt;




&lt;h2&gt;
  
  
  💡 Production-Grade Solutions
&lt;/h2&gt;

&lt;p&gt;How do you design a system that handles high traffic volumes without starving your microservices or crashing your core engine? &lt;/p&gt;

&lt;h3&gt;
  
  
  A. Introduce a Dedicated Connection Pooler
&lt;/h3&gt;

&lt;p&gt;For databases like PostgreSQL, you should almost &lt;strong&gt;never&lt;/strong&gt; connect highly scalable microservice replicas directly to the core database instance. Implement a proxy tool like &lt;strong&gt;PgBouncer&lt;/strong&gt; or &lt;strong&gt;AWS RDS Proxy&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;A connection pooler acts as a multiplexing buffer. Your 8 Kubernetes pods can safely open 100 client connections each to the proxy (800 total), while the proxy efficiently multiplexes those requests down into a tight, high-performance pool of just &lt;strong&gt;20 to 30 actual physical connections&lt;/strong&gt; directly routing onto the underlying Postgres engine.&lt;/p&gt;

&lt;h3&gt;
  
  
  B. Size the Pool to the DB Hardware, Not the Pod Count
&lt;/h3&gt;

&lt;p&gt;When calculating your absolute baseline connection pool limits, rely on hardware realities over arbitrary scaling numbers. The standard industry benchmark formula established by HikariCP is:&lt;/p&gt;

&lt;p&gt;$$\text{Connections} = (\text{Core Count} \times 2) + \text{Effective Spindles}$$&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Note: Effective spindles represent the underlying disk I/O capabilities (which varies based on mechanical hard disks vs. solid-state drives).&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;This formula tells you the sweet spot where the database server can process tasks simultaneously before disk I/O blocking transitions into destructive CPU context thrashing. Take this overall hardware budget and divide it safely across your &lt;em&gt;maximum expected&lt;/em&gt; replica pod count.&lt;/p&gt;

&lt;h3&gt;
  
  
  C. Implement CQRS (Read/Write Splitting)
&lt;/h3&gt;

&lt;p&gt;If your application genuinely demands 1,000 parallel connections to handle aggressive read traffic (e.g., massive reporting dashboards or heavy user profile fetches), &lt;strong&gt;do not route them to your primary transactional write instance&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;Separate your connection pools entirely. Route all heavy read operations to a distributed cluster of &lt;strong&gt;Read Replicas&lt;/strong&gt;, keeping your primary database connection pool lean, fast, and strictly dedicated to handling state mutations and writes.&lt;/p&gt;




&lt;h2&gt;
  
  
  The Ultimate Takeaway
&lt;/h2&gt;

&lt;p&gt;A bigger connection pool is &lt;strong&gt;not&lt;/strong&gt; a faster database. &lt;/p&gt;

&lt;p&gt;A tightly constrained pool, lightning-fast query execution, and a well-managed application-side queue will outperform a bloated, thrashing connection pool every single time. &lt;/p&gt;

&lt;p&gt;Keep your pools small, keep your queries indexed, and use proxy poolers to protect your data layer.&lt;/p&gt;

</description>
      <category>devops</category>
      <category>postgres</category>
      <category>systemdesign</category>
      <category>kubernetes</category>
    </item>
    <item>
      <title>We Broke Prod With Cache Misses So You Don't Have To</title>
      <dc:creator>Satyaki Saha</dc:creator>
      <pubDate>Sat, 26 Sep 2026 12:45:40 +0000</pubDate>
      <link>https://dev.to/satyaki_saha_367d015583da/we-broke-prod-with-cache-misses-so-you-dont-have-to-14le</link>
      <guid>https://dev.to/satyaki_saha_367d015583da/we-broke-prod-with-cache-misses-so-you-dont-have-to-14le</guid>
      <description>&lt;p&gt;Today's blog is mostly about the common ways &lt;strong&gt;cache misses&lt;/strong&gt; have happened in our system, and how we resolved them.&lt;/p&gt;

&lt;p&gt;Cache misses — and the system crashes they cause — are something you will face very often when you implement caching in a system. Until you face them, there's no way to know how the system can collapse without them.&lt;/p&gt;

&lt;h3&gt;
  
  
  1. Key simply doesn't exist yet (cold miss)
&lt;/h3&gt;

&lt;p&gt;First-ever request for that data — nothing wrong here, just an empty cache.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy:&lt;/strong&gt; Cache-aside (lazy loading) — read from the DB on a miss, populate the cache, then return. This is the default pattern for a reason: it only caches what's actually requested. The upside here is that the request is usually new and not yet a common one, so you can afford not to overthink it.&lt;/p&gt;

&lt;h3&gt;
  
  
  2. Key exists but fails to deserialize
&lt;/h3&gt;

&lt;p&gt;The bytes are there, but a schema change, version drift, or a bad write left the value unreadable. This one's sneaky — it looks like a miss, but it's actually a read failure being swallowed.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy:&lt;/strong&gt; Version your cache keys alongside your data schema (e.g., &lt;code&gt;user:v2:123&lt;/code&gt;) so old, incompatible values naturally stop being looked up instead of throwing on read. Also log deserialization failures separately from true misses — conflating them hides real bugs. &lt;em&gt;We faced this issue with a failing Jackson deserialization, which made the system go completely haywire.&lt;/em&gt;&lt;/p&gt;

&lt;h3&gt;
  
  
  3. TTL expiry — and the stampede risk on high-value keys
&lt;/h3&gt;

&lt;p&gt;A key ages out normally. That's fine for low-traffic keys. It's dangerous for hot keys: if thousands of concurrent requests hit the same expired key at once, they all miss simultaneously and hammer the DB together.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Mutex/lock on rebuild — the first request past the miss recomputes the value; others wait or get a stale value.&lt;/li&gt;
&lt;li&gt;Logical expiration — never let the TTL actually delete the key; instead, store an internal &lt;code&gt;expires_at&lt;/code&gt;. On read, if it's expired, serve the stale value immediately and refresh it asynchronously in the background. &lt;em&gt;[This is something we currently implement.]&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;Jittered TTLs so hot keys don't all expire in lockstep with each other.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  4. Request for a resource that doesn't exist (cache penetration)
&lt;/h3&gt;

&lt;p&gt;Someone queries an ID that isn't in the DB either — so nothing ever gets cached, and every repeat of that query bypasses the cache and hits the DB. This can be accidental, or an active exploit (bots probing random IDs).&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Cache the negative result too, with a short TTL, so repeated misses for the same nonexistent key stop reaching the DB. &lt;em&gt;This is negative caching, and we currently have this implemented.&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;Bloom filter in front of the cache/DB to cheaply reject obviously invalid keys before they ever reach the backend.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  5. Entire cache cluster (server + replicas) went down
&lt;/h3&gt;

&lt;p&gt;This one is severe. Thanks to the holiday-season timing, we were able to resolve it without much of a crisis — but every single request across the system ends up hitting the DB at once. This is a full avalanche, not a localized miss. In our system, we didn't have read sentinels set up properly.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Strategy:&lt;/strong&gt;&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;High availability for the cache layer itself (Sentinel/Cluster with automatic failover), so one node dying isn't a total outage.&lt;/li&gt;
&lt;li&gt;Circuit breaker / rate limiting in front of the DB as a last line of defense, so a cache outage degrades gracefully instead of taking the DB down too.&lt;/li&gt;
&lt;li&gt;A local in-process L1 cache in front of Redis can cushion the blow even if L2 is fully down.&lt;/li&gt;
&lt;/ul&gt;

&lt;h3&gt;
  
  
  6. Network timeout to the cache
&lt;/h3&gt;

&lt;p&gt;The cache is healthy and has the key, but the client times out or the connection drops before it gets the response. Depending on your fail-open/fail-closed policy, this often silently falls through to the DB, even though the data technically wasn't missing.&lt;/p&gt;

</description>
      <category>ai</category>
      <category>redis</category>
      <category>programming</category>
      <category>backenddevelopment</category>
    </item>
    <item>
      <title>Silent Saves: How JPA Persists Your Changes Without You Asking</title>
      <dc:creator>Satyaki Saha</dc:creator>
      <pubDate>Tue, 22 Sep 2026 18:28:19 +0000</pubDate>
      <link>https://dev.to/satyaki_saha_367d015583da/silent-saves-how-jpa-persists-your-changes-without-you-asking-4iii</link>
      <guid>https://dev.to/satyaki_saha_367d015583da/silent-saves-how-jpa-persists-your-changes-without-you-asking-4iii</guid>
      <description>&lt;p&gt;One of our junior devs wrote an API that was supposed to be &lt;em&gt;&lt;strong&gt;“read-only”&lt;/strong&gt;&lt;/em&gt; and act as an internal data funnel — pull some records, transform them, pass them on. nothing that should ever come close to the database. But it corrupted the production data badly.&lt;/p&gt;

&lt;p&gt;Then I started to dig into the code, and saw that he had @Transactional on the function. He was retrieving entities internally via EntityManager.find() (or a JPQL query, same thing) and &lt;em&gt;mutating some fields on them in the middle of processing&lt;/em&gt;, just as a way to store intermediate state while composing the response. No save, no merge, no repository.update() anywhere in sight, which is exactly what made him feel it was safe.&lt;/p&gt;

&lt;p&gt;But because the entities were managed and the method ran inside an active transaction, every one of those "intermediate state" field mutations got picked up by &lt;em&gt;Hibernate's dirty checking at commit time. What he thought was a harmless, read-only data funnel was silently issuing UPDATE statements against production data&lt;/em&gt; — overwriting real records with transient values that were only ever meant to exist in memory for the duration of the request.&lt;/p&gt;

&lt;p&gt;The fix was intuitive at that point: mark the transaction readOnly = true (@Transactional(readOnly = true)), which tells Hibernate to skip dirty checking and flushing entirely for that context. But 2 things I learnt were Hibernate engineering is a masterclass in abstraction, and learning hibernate is go deep or go home case.&lt;/p&gt;

</description>
      <category>jpa</category>
      <category>hibernate</category>
      <category>programming</category>
      <category>springboot</category>
    </item>
  </channel>
</rss>
