<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Prathameshjadhav on Medium]]></title>
        <description><![CDATA[Stories by Prathameshjadhav on Medium]]></description>
        <link>https://medium.com/@prathameshjadhav0198?source=rss-6d36b495ecd0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*zOoZgqJQ8xGzwk5w</url>
            <title>Stories by Prathameshjadhav on Medium</title>
            <link>https://medium.com/@prathameshjadhav0198?source=rss-6d36b495ecd0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 14:26:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@prathameshjadhav0198/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Why Our Spring Boot API Spiked to 800ms: Tracing a Silent N+1 Bottleneck with SigNoz and…]]></title>
            <link>https://medium.com/@prathameshjadhav0198/why-our-spring-boot-api-spiked-to-800ms-tracing-a-silent-n-1-bottleneck-with-signoz-and-8b04c462fa9c?source=rss-6d36b495ecd0------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b04c462fa9c</guid>
            <dc:creator><![CDATA[Prathameshjadhav]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 08:42:06 GMT</pubDate>
            <atom:updated>2026-07-15T08:46:56.510Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Our Spring Boot API Spiked to 800ms: Tracing a Silent N+1 Bottleneck with SigNoz and OpenTelemetry</h3><p>At 11:30 PM, right before a scheduled release, our event-tracking API started hemorrhaging performance. The `GET /api/v1/contests/active` endpoint — which was supposed to be a trivial cache hit — was averaging 850ms under moderate load. Standard application logs told us nothing was broken, no exceptions were throwing, and server CPU utilization sat comfortably at 15%.</p><p>We assumed Redis was choking under connection pool exhaustion. We were completely wrong. Here is how distributed tracing with OpenTelemetry and SigNoz exposed an architectural flaw that standard logging completely missed, and how we took our p99 latency down from 850ms to 18ms.</p><p>— -</p><p>## The Setup: The 4ms Cache Illusion</p><p>The architecture behind this specific service is straightforward: a Spring Boot 3 backend handling high-frequency schedule requests, backed by MySQL for persistent storage and Redis for caching active event lists.</p><p>To keep database load low, the endpoint followed a classic cache-aside pattern:</p><p>1. Check Redis for the list of active contest IDs.<br>2. If present, map those IDs to our response Data Transfer Objects (DTOs) and return them.<br>3. If missing, query MySQL, populate Redis, and return the response.</p><p>When we tested the Redis connection in isolation using `redis-cli`, response times were sitting at a clean 2ms to 4ms. Yet, whenever the frontend polled the endpoint during peak usage, network tab response times spiked past 800ms. Without visibility into what the application thread was doing between receiving the HTTP request and sending the payload, we were just guessing.</p><p>— -</p><p>## Instrumenting the Stack</p><p>To see inside the black box without rewriting our business logic, we dropped in the OpenTelemetry (OTel) Java Agent for auto-instrumentation and spun up a local SigNoz instance to collect and visualize the traces.</p><p>If you are running a Spring Boot application, you don’t need to modify your `pom.xml` or `build.gradle` to get baseline tracing. You simply attach the OTel Java agent at runtime. Here is the exact command structure we used to bind the application to our collector:</p><pre><br>java -javaagent:path/to/opentelemetry-javaagent.jar \<br> -Dotel.resource.attributes=service.name=event-tracker-api,deployment.environment=staging \<br> -Dotel.traces.exporter=otlp \<br> -Dotel.metrics.exporter=none \<br> -Dotel.exporter.otlp.endpoint=http://localhost:4317 \<br> -jar target/event-tracker-0.0.1-SNAPSHOT.jar</pre><p>To ingest these traces, we ran SigNoz via Docker Compose. The critical piece here is ensuring your OpenTelemetry Collector (`otel-collector-config.yaml`) is configured to receive OTLP traffic on port `4317` (gRPC) or `4318` (HTTP) and pass it along to ClickHouse for storage:</p><pre>receivers:<br> otlp:<br> protocols:<br> grpc:<br> endpoint: 0.0.0.0:4317<br> http:<br> endpoint: 0.0.0.0:4318<br>processors:<br> batch:<br> send_batch_size: 10000<br> timeout: 10s<br>exporters:<br> clickhousetraces:<br> datasource: tcp://clickhouse:9000/?database=signoz_traces<br>service:<br> pipelines:<br> traces:<br> receivers: [otlp]<br> processors: [batch]<br> exporters: [clickhousetraces]</pre><p>Once the service restarted, we fired a load testing script using `hey` to send 500 concurrent requests to the slow endpoint:</p><pre>hey -n 500 -c 20 http://localhost:8080/api/v1/contests/active</pre><p>— -</p><p>## The Investigation: The Flamegraph Staircase</p><p>We opened the SigNoz UI, navigated to the Traces tab, and filtered by `service.name = “event-tracker-api”` and `http.status_code = 200`. We sorted by latency descending and clicked into one of the 850ms traces.</p><p>Instead of seeing a single long red bar pointing to a stalled Redis query, the SigNoz flamegraph showed a bizarre pattern: a tiny 4ms span at the very top for the Redis `GET`, followed by a cascading “staircase” of 50 individual, sequential database spans stretching across the screen.</p><p>`[INSERT SCREENSHOT 1: SigNoz Trace Detail / Flamegraph showing an 800ms+ total duration. The top span shows a quick Redis GET, followed immediately by dozens of short, cascading MySQL SELECT spans forming a staircase pattern.]`</p><p>Auto-instrumentation had caught something our standard console logs ignored. The application was hitting Redis, and Redis was returning the payload quickly. But what we had stored in Redis wasn’t the fully hydrated response object — it was just a list of raw entity IDs.</p><p>Here is what was happening inside our `<a href="http://twitter.com/Service">@Service</a>` class:</p><pre>@Transactional(readOnly = true)<br>public List&lt;ContestResponseDTO&gt; getActiveContests() {<br> // 1. Fast Redis Hit (4ms)<br> List&lt;Long&gt; activeIds = redisTemplate.opsForList().range(&quot;contests:active&quot;, 0, -1);<br> <br> List&lt;ContestResponseDTO&gt; responses = new ArrayList&lt;&gt;();<br> for (Long id : activeIds) {<br> // 2. The Trap: Loading entities inside a loop<br> Contest contest = contestRepository.findById(id).orElseThrow();<br> <br> // 3. The Silent N+1: Getter triggers lazy-loading of a child collection<br> int participantCount = contest.getParticipants().size(); <br> <br> responses.add(new ContestResponseDTO(contest.getName(), participantCount));<br> }<br> return responses;<br>}</pre><p>Because the method was annotated with `<a href="http://twitter.com/Transactional">@Transactional</a>`, an open Hibernate session persisted throughout the execution. When our DTO mapper called `contest.getParticipants().size()`, Hibernate silently executed a separate SQL `SELECT` query for *every single ID in the list* to fetch the lazy-loaded relationship.</p><p>If there were 50 active contests, our “cached” endpoint was executing 1 Redis hit and 50 sequential MySQL queries over the network. In a local environment with 2 test records, this took 10ms and went unnoticed. Under staging load with real data, network round-trip times compounded, ballooning the endpoint latency to 850ms.</p><p>— -</p><p>## The Fix: Flattening the Cache Payload</p><p>To fix this without abandoning our caching strategy, we needed to sever the dependency on the Hibernate session entirely during a cache hit. Instead of storing a list of raw IDs and hydrating them in memory, we shifted to caching the flattened, pre-computed JSON representation of the `ContestResponseDTO`.</p><p>First, we updated the Redis serialization config to handle generic DTO structures using Jackson:</p><pre>@Bean<br>public RedisTemplate&lt;String, Object&gt; redisTemplate(RedisConnectionFactory connectionFactory) {<br> RedisTemplate&lt;String, Object&gt; template = new RedisTemplate&lt;&gt;();<br> template.setConnectionFactory(connectionFactory);<br> template.setKeySerializer(new StringRedisSerializer());<br> template.setValueSerializer(new GenericJackson2JsonRedisSerializer());<br> return template;<br>}</pre><p>Next, we rewrote the service layer to pull the complete payload directly from cache, only falling back to a single, optimized `JOIN FETCH` database query if the cache was entirely cold:</p><pre>public List&lt;ContestResponseDTO&gt; getActiveContests() {<br> // 1. Attempt to fetch fully mapped DTOs directly from Redis<br> List&lt;Object&gt; cached = redisTemplate.opsForList().range(&quot;contests:active:dtos&quot;, 0, -1);<br> if (cached != null &amp;&amp; !cached.isEmpty()) {<br> return cached.stream()<br> .map(obj -&gt; (ContestResponseDTO) obj)<br> .collect(Collectors.toList());<br> }<br>// 2. Cold fallback: Fetch everything in ONE query using JOIN FETCH<br> List&lt;Contest&gt; contests = contestRepository.findAllActiveWithParticipants();<br> <br> List&lt;ContestResponseDTO&gt; dtos = contests.stream()<br> .map(c -&gt; new ContestResponseDTO(c.getName(), c.getParticipants().size()))<br> .collect(Collectors.toList());<br>// 3. Populate cache with flattened DTOs (TTL: 5 mins)<br> redisTemplate.opsForList().rightPushAll(&quot;contests:active:dtos&quot;, dtos.toArray());<br> redisTemplate.expire(&quot;contests:active:dtos&quot;, Duration.ofMinutes(5));<br>return dtos;<br>}</pre><p>We deployed the updated build, flushed the old Redis keys, and ran the exact same `hey` load test against the endpoint.</p><p>`[INSERT SCREENSHOT 2: SigNoz Flamegraph after the fix. The total trace duration should read under 20ms, displaying a single clean HTTP GET span and a single Redis range span, with zero MySQL queries attached.]`</p><p>The flamegraph shrank dramatically. The 50 cascading MySQL spans vanished completely. The p99 latency dropped from 850ms to 18ms, and database CPU utilization fell to near zero during polling spikes.</p><p>— -</p><p>## Three Things the Docs Don’t Tell You</p><p>1. Auto-instrumentation will save you from your own ORM.Standard logging frameworks won’t warn you when Hibernate issues valid, syntactically correct queries. A visual trace timeline is the fastest way to catch ORM lazy-loading bugs because N+1 queries physically manifest as unmistakable, visual “staircases” on the screen.<br>2. Watch your sampling rates in high-throughput loops.If you are running OTel in production, tracing every single 18ms polling request will quickly consume storage in ClickHouse. Use tail-based sampling in your OpenTelemetry Collector configuration to keep 100% of error traces (HTTP 5xx) and slow traces (&gt; 200ms), while only sampling 5% of your successful, fast requests.<br>3. Trace context doesn’t automatically cross async thread boundaries.** If your Spring Boot app uses `<a href="http://twitter.com/Async">@Async</a>` or `CompletableFuture` to process data after returning an HTTP response, auto-instrumentation will drop the trace ID at the thread boundary. You must manually propagate the `Context` using OTel’s `Context.current().wrap(runnable)` if you want to see background processing linked to the originating HTTP request in SigNoz.</p><p>Building robust backends requires more than writing clean syntax; it requires knowing how your application behaves when memory, networks, and databases interact under load. Moving from traditional text logging to visual distributed tracing with OpenTelemetry and SigNoz fundamentally changed how we debug our systems. You stop arguing about theoretical bottlenecks in code reviews, open the flamegraph, and let the execution timeline show you exactly where the time went. You can find the complete Docker Compose setup for SigNoz and OpenTelemetry in their [official documentation repository](<a href="https://signoz.io/docs/"><strong>https://signoz.io/docs/</strong></a>) to test this against your own local stack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b04c462fa9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>