<?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 Guptaarman on Medium]]></title>
        <description><![CDATA[Stories by Guptaarman on Medium]]></description>
        <link>https://medium.com/@guptaarman910?source=rss-95a91a7861e3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6LJwZoJVk2imEAvQ</url>
            <title>Stories by Guptaarman on Medium</title>
            <link>https://medium.com/@guptaarman910?source=rss-95a91a7861e3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 02:24:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@guptaarman910/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 1 Million WebSocket Connections Is Harder Than It Looks]]></title>
            <link>https://medium.com/@guptaarman910/why-1-million-websocket-connections-is-harder-than-it-looks-1200c29ebe72?source=rss-95a91a7861e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1200c29ebe72</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[websocket]]></category>
            <dc:creator><![CDATA[Guptaarman]]></dc:creator>
            <pubDate>Sat, 30 May 2026 16:55:24 GMT</pubDate>
            <atom:updated>2026-05-30T16:55:24.162Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s a question nobody asks when they first build a chat app: before a single message is sent, before any user types anything — how much memory does the server spend just <em>keeping the door open</em>?</p><p>I got curious about this while working with FastAPI. Not curious in a theoretical sense. I actually wanted to measure it.</p><p>So I wrote the smallest possible WebSocket server. It accepts connections, stores them in a list, and waits. That’s it. When a client connects, I print the size of the WebSocket object two different ways — shallow and deep.</p><pre>from fastapi import FastAPI, WebSocket<br>from pympler import asizeof<br>import sys<br><br>app = FastAPI()<br>connections = []<br>@app.websocket(&quot;/ws&quot;)<br>async def websocket_endpoint(websocket: WebSocket):<br>    await websocket.accept()<br>    connections.append(websocket)<br>    print(<br>        f&quot;shallow={sys.getsizeof(websocket)} bytes | &quot;<br>        f&quot;deep={asizeof.asizeof(websocket)} bytes&quot;<br>    )<br>    while True:<br>        await websocket.receive_text()</pre><p>The output stopped me cold.</p><pre>shallow=56 bytes | deep=27960 bytes</pre><p>56 bytes and 27 kilobytes. Same object. A difference of 500x.</p><p>That gap isn’t a bug — it’s a lesson. sys.getsizeof() only measures the Python object sitting at the surface. But a WebSocket isn&#39;t just a number or a string. It drags along everything it needs to function: asyncio internals, transport wrappers, protocol state, internal queues, socket metadata. The outer shell is tiny. The whole creature is not.</p><p>So the real number — the one that actually matters — is roughly <strong>27 KB per idle connection</strong>. And that’s with nobody doing anything. No messages. No media. Just a socket breathing.</p><p>Now do the math. Let’s say, one million users are online simultaneously.</p><p>One million idle sockets at 27 KB each. That’s about <strong>27 GB of RAM</strong>, consumed before your application has processed a single message. Before TLS overhead. Before presence tracking. Before any user data whatsoever.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Izo60pDsUz-v9raBtExqZA.png" /></figure><p>That number quietly kills the idea of a single beefy server handling everything. It doesn’t matter how powerful the machine is — you can’t fit a city in one building.</p><p>This is where the architecture has to change shape.</p><p>Instead of one server drowning under a million connections, you spread users across many servers sitting behind a load balancer. Each server holds a slice of the total connections and handles only the users assigned to it. The memory problem becomes manageable. Each machine carries its own weight.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCpUnsUWuvi0eYW8uhwYFQ.png" /></figure><p>But the moment you do this, a new problem walks through the door.</p><p>Say Alice is on Server 1 and Bob is on Server 2. Alice sends Bob a message. It arrives at Server 1. Bob doesn’t live there. His socket is on Server 2. Server 1 has no idea what to do with this message.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRSSjQI9IBlbODIUxpiycA.png" /></figure><p>The machines aren’t talking to each other. They’re islands.</p><p>The fix is a message broker sitting between them — something like Kafka, Redis Pub/Sub, or NATS. Server 1 publishes the message to the broker. Server 2 subscribes, picks it up, and pushes it to Bob’s socket. Now the islands have a bridge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TeM1Nggwimk-Uw2oROgctQ.png" /></figure><p>Problem solved. Mostly.</p><p>Because there’s still a quieter question hiding underneath: how does Server 1 even <em>know</em> Bob is on Server 2?</p><p>This is the routing problem, and it needs its own solution. The common answer is a presence registry — a simple key-value store in Redis that maps each user to the server currently holding their connection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0sMsDnzuqBknsJQ3KZuJzw.png" /></figure><p>When Bob connects to Server 2, that server writes Bob → Server2 into Redis. When Alice&#39;s message arrives at Server 1, it looks Bob up, gets the answer, and routes accordingly. One small lookup. The whole distributed system snaps together.</p><p>But even this clean solution has edges that fray.</p><p>What if Server 2 crashes mid-conversation? Redis still says Bob is there. But Bob’s socket is gone. Nothing cleaned it up. Now any message sent to Bob disappears into a dead address.</p><p>What if Bob’s phone loses signal without closing the connection properly? The socket is technically alive on the server but completely unreachable. How long before the system figures that out?</p><p>These aren’t edge cases you’ll find in a tutorial. They’re the actual job.</p><p>What I find genuinely fascinating about all this is how one small measurement triggered a cascade. A single line of Python output — ~27 KB per connection — pulled an entire distributed systems problem into view.</p><p>Horizontal scaling. Pub/sub routing. Presence registries. Failure detection. Reconnect handling. Each answer revealed a new question.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1200c29ebe72" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Redis Reads Don’t Always Hit Redis: Local Caching and Consistency Trade-offs in Spring Boot]]></title>
            <link>https://medium.com/@guptaarman910/why-redis-reads-dont-always-hit-redis-local-caching-and-consistency-trade-offs-in-spring-boot-bb0b1bc76d82?source=rss-95a91a7861e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb0b1bc76d82</guid>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Guptaarman]]></dc:creator>
            <pubDate>Tue, 24 Mar 2026 20:58:11 GMT</pubDate>
            <atom:updated>2026-03-24T20:58:11.026Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>A common assumption when working with Redis is that every read operation results in a network call to the Redis node.</strong> While this is true in basic setups, it does not hold when local (near) caching is introduced through clients such as Redisson in Spring Boot.</p><p>This article explains how local caching works, how <strong>eventual consistency</strong> is maintained using Redis Pub/Sub, and the trade-offs that arise in distributed systems.</p><h3>Local Cache with RLocalCachedMap</h3><p>Redisson provides a data structure called <strong>RLocalCachedMap</strong> that maintains a local in-memory cache alongside Redis in Spring Boot. This creates a two-layer architecture:</p><ol><li><strong>Local JVM cache (Local Cache)</strong></li><li><strong>Remote Redis cache (Remote Cache)</strong></li></ol><p>A typical initialization looks like this:</p><pre>LocalCachedMapOptions&lt;String, String&gt; options =<br>    LocalCachedMapOptions.&lt;String, String&gt;defaults()<br>        .timeToLive(10, TimeUnit.MINUTES)<br>        .syncStrategy(LocalCachedMapOptions.SyncStrategy.INVALIDATE);<br><br>RLocalCachedMap&lt;String, String&gt; map =<br>    redissonClient.getLocalCachedMap(&quot;users&quot;, options);</pre><h4>Read Path</h4><p>On a cache read:</p><pre>String value = map.get(&quot;user:1&quot;);</pre><p>The execution flow is:</p><ul><li><strong>The client first checks the local JVM cache.</strong></li><li><strong>If the value is present, it is returned immediately.</strong></li><li><strong>If not, a network call is made to Redis.</strong></li><li><strong>The fetched value is returned and stored in the local cache with TTL.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*FWy7BA9A5E3ueIZ8Hl-gCA.png" /></figure><p>This reduces latency and avoids repeated network calls for frequently accessed data. <strong>Also, the TTL makes sure that the JVM heap never overflows.</strong></p><h4>Write Path and Cache Synchronization</h4><p>The complexity arises during writes:</p><pre>map.put(&quot;user:1&quot;, &quot;Arman&quot;);</pre><p><strong>When a value is updated, other application instances, which are utilising the same cache and have the cache entry stored in the JVM heap, may still hold stale data in their local caches. </strong>To address this, Redisson relies on Redis Pub/Sub.</p><p>On every update:</p><ul><li><strong>Redis publishes an invalidation or update event on Redis pub/sub.</strong></li><li><strong>All subscribed services </strong>(who are also using the same somwhere in the service)<strong> receive this event.</strong></li><li><strong>Each service updates or invalidates (</strong>deletes<strong>) its JVM heap entry for that key. This behaviour can be pre-decided, programatically </strong>(weather you want to invalidate or update)<strong>.</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*tynVrzq0wudGEs-g4Er5nA.png" /></figure><h3>Consistency in Distributed Systems</h3><p>Consider a system with multiple service instances using the same cache. When one instance updates a value:</p><ul><li><strong>Redis publishes a Pub/Sub event.</strong></li><li><strong>Other instances receive the event with some latency </strong>(may be very small, typically in milliseconds).</li></ul><p>During this interval, different instances may observe old values and may also serve old values to the requests, even when the value was updated on the Redis Node already. <strong>This creates a window of temporary inconsistency.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*tfbg4kTuryXOLul6EnQy9g.png" /></figure><p>This model provides<strong> eventual consistency, not strong consistency.</strong></p><h3>Failure Scenarios</h3><p>The consistency model relies on Redis Pub/Sub, which has important limitations. <strong>If a service is temporarily disconnected, it may miss invalidation events. If network delays occur, stale data may be served longer than expected.</strong></p><p>In such cases, inconsistency may persist until TTL-based eviction or a subsequent update (as a part of the retry mechanism) corrects it.</p><h3>Conclusion</h3><p>Local caching in Redis clients is not just a performance optimization. It introduces a distributed consistency model that must be understood and accepted.</p><p>What appears to be a simple cache layer is, in practice, a trade-off between performance and correctness. Designing with this awareness is essential when building scalable systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb0b1bc76d82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Matching Server for an Omegle-Like App]]></title>
            <link>https://medium.com/@guptaarman910/building-a-matching-server-for-an-omegle-like-app-ce2f6d08e0a6?source=rss-95a91a7861e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce2f6d08e0a6</guid>
            <category><![CDATA[omegle]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[real-time-communication]]></category>
            <category><![CDATA[webrtc]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <dc:creator><![CDATA[Guptaarman]]></dc:creator>
            <pubDate>Mon, 29 Dec 2025 06:10:43 GMT</pubDate>
            <atom:updated>2025-12-29T06:10:43.970Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jOp3E__SUq7T4DiXPkuVWg.png" /></figure><p>When I set out to build an Omegle-like random video-chat application, I thought I could handle everything with a single backend server. I was wrong. Here’s the story of how I discovered what was really needed, the problems I encountered, and how I solved them one by one.</p><h4>The First Realization: Two Servers, Not One</h4><p>My initial architecture was too simple: one server to do everything. But as I dug deeper into WebRTC and real-time matching, I realized I needed two distinct microservices:</p><ol><li><strong>Matching Server</strong> — pairs users together</li><li><strong>Signaling Server</strong> — helps matched users establish their WebRTC connection</li></ol><p><strong><em>This article focuses on the Matching Server, which turned out to be more nuanced than I expected.</em></strong></p><h3>Problem #1: How Do Users Actually Get Matched?</h3><p>Let me start with the basic user flow I was trying to enable:</p><ol><li>User opens the app and enters their name</li><li>System finds them a random partner</li><li>Both users start video-chatting</li></ol><p>Simple concept, but how do you implement step 2?</p><p>My first attempt was straightforward: make an API call that doesn’t return until we find a match.</p><pre>POST /api/match<br>{ &quot;name&quot;: &quot;Alice&quot; }<br><br>// Wait here until matched...<br>// Could be 1 second, could be 5 minutes<br><br>Response: { &quot;room_code&quot;: &quot;abc123&quot;, &quot;peer&quot;: &quot;Bob&quot; }</pre><h4>Why This Failed</h4><p>This synchronous approach had serious problems:</p><ul><li><strong>The request could hang indefinitely</strong> if no one else was online</li><li><strong>Impossible to scale</strong> — each waiting user holds a server connection</li></ul><p>I needed a better approach.</p><h3>Problem #2: Asynchronous Matching — But Then What?</h3><p>The solution seemed obvious: make matching asynchronous.</p><p><strong>New approach:</strong></p><ul><li>User registers for matching (request returns immediately)</li><li>A background worker handles the actual matching</li><li>Somehow notify the user when matched</li></ul><p>This separated concerns beautifully:</p><pre>Registration API: Fast, just queues the user<br>Background Worker: Continuously matches people</pre><p>But this created a new problem: <strong>How do users get notified when they’re matched?</strong></p><h3>Problem #3: The Notification Challenge</h3><p>With asynchronous matching, I had to figure out how to tell users “Hey, you’ve been matched!”</p><h4>Option 1: Polling (The Naive Approach)</h4><pre>// Client keeps asking<br>setInterval(async () =&gt; {<br>  const match = await fetch(&#39;/api/check-match&#39;);<br>  if (match) { /* start chat */ }<br>}, 1000);</pre><p><strong>Why this is terrible:</strong></p><ul><li>Wastes bandwidth</li><li>Delays are inevitable (what if match happens right after a poll?)</li></ul><h4>Option 2: WebSocket (The Right Choice)</h4><p>Instead, I used WebSockets for real-time push notifications:</p><pre>// Client opens WebSocket<br>const ws = new WebSocket(&#39;ws://server.com/match&#39;);<br><br>// Then registers<br>await fetch(&#39;/api/register&#39;, { name: &#39;Alice&#39; });<br><br>// Server pushes notification when ready<br>ws.onmessage = (event) =&gt; {<br>  const { room_code, peer } = JSON.parse(event.data);<br>  // Start chatting!<br>};</pre><p>This solved everything:</p><ul><li>Instant notification</li><li>Clean separation of concerns</li></ul><p><strong>But it introduced a critical timing issue…</strong></p><h3>Problem #4: The Race Condition</h3><p>Think about this sequence:</p><pre>1. Client calls /api/register<br>2. Server adds user to queue<br>3. Worker immediately finds a match<br>4. Worker tries to send notification via WebSocket<br>5. But... WebSocket isn&#39;t connected yet!</pre><p>The match notification could arrive before the client was ready to receive it.</p><h4>The Solution: Connect Before Registering</h4><p>I flipped the order:</p><pre>// Step 1: Open WebSocket FIRST<br>const ws = new WebSocket(`ws://server.com/match?name=Alice`);<br><br>ws.onopen = async () =&gt; {<br>  // Step 2: Register AFTER connection is ready<br>  await fetch(&#39;/api/register&#39;, { name: &#39;Alice&#39; });<br>};<br><br>// Step 3: Wait for match notification<br>ws.onmessage = (event) =&gt; {<br>  const { room_code, peer } = JSON.parse(event.data);<br>};</pre><p>This guaranteed the notification channel was always ready.</p><p><strong>Trade-off accepted:</strong> WebSockets consume server memory, but for a real-time app, this is worth it.</p><h3>Problem #5: Where Do I Store Waiting Users?</h3><p>Now that I had the flow working, I needed to store users waiting for matches. Redis was the obvious choice, but <em>which data structure?</em></p><h4>Option 1: Sorted Set (ZSET) with Timestamps</h4><p>My first instinct was to use timestamps to match the <em>oldest</em> waiting users first:</p><pre>ZADD waiting_users 1640000000 &quot;alice&quot;<br>ZADD waiting_users 1640000001 &quot;bob&quot;</pre><p>This would let me:</p><ul><li>Match people fairly (oldest first)</li><li>See exactly when someone started waiting</li></ul><p><strong>But then I realized:</strong></p><ul><li>Do timestamps actually matter? Users just want <em>any</em> match fast</li><li>Operations are O(log N) instead of O(1)</li></ul><h4>Option 2: Simple List (What I Actually Used)</h4><p>I chose a Redis LIST instead:</p><pre>RPUSH waiting_queue &quot;alice&quot;   # Add to back<br>RPUSH waiting_queue &quot;bob&quot;     # Add to back<br>LPOP waiting_queue            # Remove from front → &quot;alice&quot;<br>LPOP waiting_queue            # Remove from front → &quot;bob&quot;</pre><p><strong>Why this won:</strong></p><ul><li>FIFO behavior is automatic</li><li>O(1) operations (blazing fast)</li></ul><p><strong>Trade-off accepted:</strong> No fancy prioritization, but for a simple random chat app, I don’t need it.</p><h3>Problem #6: The Matching Worker Logic</h3><p>With users in a queue, I needed a worker to continuously match them:</p><pre>while True:<br>    queue_size = redis.llen(&#39;waiting_queue&#39;)<br>    <br>    if queue_size &gt;= 2:<br>        user1 = redis.lpop(&#39;waiting_queue&#39;)<br>        user2 = redis.lpop(&#39;waiting_queue&#39;)<br>        <br>        room_code = generate_room_code()<br>        notify_both_users(user1, user2, room_code)<br>    else:<br>        # What do we do here?<br>        pass</pre><h4>The Edge Case: Only One User Waiting</h4><p>What happens when there’s only one person in the queue?</p><p><strong>Bad approach:</strong></p><pre>while True:<br>    if queue_size &lt; 2:<br>        continue  # Check again immediately</pre><p>This would create a <strong>tight loop</strong> that:</p><ul><li>Burns CPU cycles</li><li>Hammers Redis with constant LLEN calls</li></ul><h4>The Solution: Incremental Backoff</h4><pre>sleep_duration = 0.1  # Start with 100ms<br><br>while True:<br>    queue_size = redis.llen(&#39;waiting_queue&#39;)<br>    <br>    if queue_size &gt;= 2:<br>        # Match users<br>        match_users()<br>        sleep_duration = 0.1  # Reset sleep<br>    else:<br>        # No matches possible, back off<br>        time.sleep(sleep_duration)<br>        sleep_duration = min(sleep_duration * 1.5, 5)  # Max 5 seconds</pre><p>This makes the system adaptive to changing conditions:</p><ul><li>Responsive when traffic is high (short sleep)</li><li>Efficient when traffic is low (longer sleep)</li></ul><h3>Problem #7: The WebRTC Initiator Problem</h3><p>After matching two users and sending them the same room_code, I hit a subtle but critical issue with WebRTC.</p><p>WebRTC connections require:</p><ol><li>One peer to create and send an “offer”</li><li>The other peer to respond with an “answer”</li></ol><p><strong>But what if both users try to initiate?</strong></p><pre>// Both Alice and Bob do this:<br>const offer = await peerConnection.createOffer();<br>// Chaos ensues!</pre><p>This causes:</p><ul><li>Duplicate offers</li><li>Connection failures</li><li>Impossible-to-debug race conditions</li></ul><h4>The Solution: Assign Roles at Match Time</h4><p>When the matching worker pairs two users, it assigns roles:</p><pre>user1 = redis.lpop(&#39;waiting_queue&#39;)<br>user2 = redis.lpop(&#39;waiting_queue&#39;)<br><br>room_code = generate_room_code()<br><br># Assign roles<br>notify_user(user1, {<br>    &#39;room_code&#39;: room_code,<br>    &#39;peer&#39;: user2[&#39;name&#39;],<br>    &#39;role&#39;: &#39;initiator&#39;  # You send the offer<br>})<br><br>notify_user(user2, {<br>    &#39;room_code&#39;: room_code,<br>    &#39;peer&#39;: user1[&#39;name&#39;],<br>    &#39;role&#39;: &#39;responder&#39;  # You wait for the offer<br>})</pre><p>Now:</p><ul><li>Exactly one user creates the offer</li><li>Predictable WebRTC flow</li><li>The signaling server knows what to expect</li></ul><h3>The Complete Flow (Finally!)</h3><p>Here’s what happens from start to finish:</p><pre>1. User opens app, enters name &quot;Alice&quot;<br>   <br>2. Client opens WebSocket:<br>   ws://server.com/match?name=Alice<br>   <br>3. Client registers for matching:<br>   POST /api/register { &quot;name&quot;: &quot;Alice&quot; }<br>   ↓<br>   Server: RPUSH waiting_queue &quot;alice&quot;<br>   Response: { &quot;status&quot;: &quot;queued&quot; }<br>   <br>4. [Background worker continuously runs]<br>   - Checks queue length<br>   - If &gt;= 2 users, matches them<br>   <br>5. Bob joins, gets matched with Alice:<br>   Worker:<br>     - LPOP waiting_queue → &quot;alice&quot;<br>     - LPOP waiting_queue → &quot;bob&quot;<br>     - Creates room_code: &quot;abc123&quot;<br>     - Stores room data in Redis<br>   <br>6. Server pushes to both WebSockets:<br>   → Alice: {<br>       &quot;room_code&quot;: &quot;abc123&quot;,<br>       &quot;peer&quot;: &quot;Bob&quot;,<br>       &quot;role&quot;: &quot;initiator&quot;<br>     }<br>   → Bob: {<br>       &quot;room_code&quot;: &quot;abc123&quot;,<br>       &quot;peer&quot;: &quot;Alice&quot;,<br>       &quot;role&quot;: &quot;responder&quot;<br>     }<br>   <br>7. Both clients receive notification<br>   Now they can connect via WebRTC!</pre><h3>What the Matching Server Provides</h3><p>By the end of this process, each matched user has:</p><ul><li>A unique room_code to join</li><li>Their peer’s name</li><li>A clearly defined role (initiator/responder)</li></ul><p>This is everything the Signaling Server needs to:</p><ul><li>Verify room legitimacy</li><li>Enforce initiator rules</li><li>Forward WebRTC messages safely</li><li>Clean up rooms on disconnect</li></ul><h3>Key Takeaways</h3><p>Looking back at this journey, here are the design principles that emerged:</p><ol><li><strong>Separate concerns early</strong> — Matching and signaling are fundamentally different problems</li><li><strong>Async operations need real-time communication</strong> — WebSockets aren’t optional for this use case</li><li><strong>Solve timing issues with ordering</strong> — Connect before you register</li><li><strong>Choose simple data structures</strong> — Redis LIST beat ZSET because simpler is often better</li><li><strong>Background workers need backoff</strong> — Don’t burn CPU when there’s nothing to do</li><li><strong>Assign roles to prevent race conditions</strong> — WebRTC needs clear coordination</li></ol><p>None of these decisions were obvious from the start. Each one emerged from hitting a wall and finding a way through.</p><h3>What’s Next?</h3><p>The matching server’s job is done: it paired two users and gave them everything they need to connect. But they still need to actually establish that WebRTC connection.</p><p>In the next article, I’ll cover the <strong>Signaling Server</strong> — how it uses these guarantees to safely coordinate WebRTC handshakes, handle disconnections, and keep the conversation flowing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce2f6d08e0a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Was Eating Our CPUs — Until I Built a Smarter Consumer — Part 2]]></title>
            <link>https://medium.com/@guptaarman910/kafka-was-eating-our-cpus-until-i-built-a-smarter-consumer-part-2-3976ab8209a1?source=rss-95a91a7861e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/3976ab8209a1</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[offset]]></category>
            <dc:creator><![CDATA[Guptaarman]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 10:47:14 GMT</pubDate>
            <atom:updated>2025-07-24T10:47:14.214Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kafka Was Eating Our CPUs — Until I Built a Smarter Consumer — Part 2</h3><p>In Part 1 of this series, we discovered that the real culprit wasn’t inefficient message handling — it was Kafka’s design to <strong>trigger rebalancing for the entire consumer group whenever any member joins or leaves</strong>, even if all consumers subscribe to completely different topics.</p><p>When all consumers are placed in one group, a single restart or change forces every consumer — across all topics — to pause, coordinate, and redistribute their partition assignments. This leads to needless spikes in CPU usage and longer startup times, even though the consumers have no overlapping work. The core issue:</p><blockquote><strong><em>Kafka rebalancing always operates at the group level, never at the topic level. Fixing this inefficiency is crucial for scaling Kafka environments smoothly.</em></strong></blockquote><h3>Kafka’s Polling Loops — The Silent CPU Killer</h3><p>After optimizing consumer group behavior and startup rebalancing, I shifted my focus from <strong>startup behavior</strong> to <strong>runtime efficiency</strong>.</p><p>I wanted to understand how Kafka behaved during normal operation — while actively running and waiting for records.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1002/0*EF1PM89tq6fNXLBv.png" /></figure><h4>Understanding Kafka’s Pull Model</h4><p>Kafka operates on a <strong>pull-based model</strong> — consumers pull records from brokers, not the other way around. This means:</p><ul><li>Consumers actively call .poll() to fetch data.</li><li>The broker waits passively, keeping track of offsets and ready messages.</li><li>If there are no new records, the consumer still polls — often returning empty results.</li></ul><p>At first, this looked harmless. But when I profiled CPU usage during these empty polling cycles, I realized they weren’t as cheap as I had assumed.</p><h4>The Insight: Polling When There’s Nothing To Poll</h4><p>In our setup, <strong>most of the poll cycles were returning empty</strong> — no new records were available yet. But polling was happening continuously, every few milliseconds. The consumers were just looping, polling, waiting, looping again… burning CPU in the process.</p><p>This felt wasteful. If we knew that nothing new was expected for a while, why keep polling so aggressively?</p><h4>The Discovery: idleBetweenPolls Property</h4><p>That’s when I stumbled upon a setting from Spring Kafka’s ConcurrentKafkaListenerContainerFactory — the <strong>idleBetweenPolls</strong> property.</p><p>This property allows you to <strong>introduce a fixed delay between each poll</strong>, effectively telling the consumer:</p><blockquote><strong>Take a short break after each poll.</strong></blockquote><p>Here’s a quick code snippet for reference:</p><pre>factory.setIdleBetweenPolls(Duration.ofMillis(500));</pre><h4>The Trade-Off</h4><p>Applying this setting led to a noticeable drop in CPU usage during idle periods. The consumers were no longer hammering the broker with unnecessary polls when there were no records to consume.</p><p>However, this optimization came with a trade-off:</p><ul><li><strong>Pro</strong>: Significant CPU savings during low activity periods.</li><li><strong>Con</strong>: Potential lag if there’s a sudden <strong>burst of messages</strong> during the sleep window. Since the consumer waits between polls, it might fall behind during high-throughput scenarios.</li></ul><p>So, while idleBetweenPolls wasn’t a silver bullet, it was a <strong>useful lever</strong> for <strong>low-volume</strong> or <strong>bursty workloads</strong> where CPU conservation mattered more than millisecond-level latency.</p><p>In our case, we applied it selectively — only to consumers dealing with low-frequency topics, where throughput was not critical.</p><h4>From Static Delays to Smart Polling — The Custom Strategy</h4><p>As useful as the idleBetweenPolls property was, it still felt… <strong>too static</strong>.</p><p>The real world isn’t static. Kafka traffic in production is often <strong>bursty and unpredictable</strong> — long periods of silence followed by sudden spikes. A fixed delay after each poll didn’t quite fit that pattern.</p><p>That’s when I had the idea:</p><blockquote><strong><em>What if the delay between polls could be dynamic?</em></strong></blockquote><h4>The Idea: Adaptive Polling Based on Load</h4><p>Here’s the strategy I envisioned:</p><ol><li><strong>Start with a small delay</strong> — say, 100ms.</li><li>After every <strong>empty poll</strong>, slightly <strong>increase the delay</strong> — e.g., double it, up to a <strong>maximum cap</strong>.</li><li>If records <strong>do arrive</strong> in a poll, reset the delay back to <strong>zero</strong>, so the consumer runs at full speed.</li><li>Repeat this cycle — adaptively.</li></ol><p>This way, during periods of inactivity, the consumer becomes more “relaxed,” saving CPU. But when a burst of events arrives, it <strong>snaps back to full throttle</strong> almost instantly.</p><p>It was like teaching the consumer to <strong>breathe</strong> — work harder when needed, rest when idle.</p><h4>The Problem: No Built-In Support</h4><p>I went back to Kafka docs, community forums, GitHub issues, Stack Overflow threads — hoping to find a flag or config to implement this dynamic behavior.</p><p>But… nothing.</p><p>Kafka’s idleBetweenPolls was a <strong>fixed value</strong> — not something that could be adjusted at runtime based on poll results. And since this was baked into the consumer container’s lifecycle, overriding it wasn&#39;t straightforward either.</p><p>I realized that if we wanted this kind of flexibility…</p><blockquote><strong><em>We had to build it ourselves.</em></strong></blockquote><h4>Building @KafkaOptimizer — A Smarter Kafka Consumer</h4><p>With the idea of adaptive polling in place, it was time to turn it into something <strong>usable and scalable</strong> — not just a one-off experiment.</p><p>That’s how the <strong>Kafka Optimizer</strong> library was born.</p><h4>The Goal</h4><p>Build a Kafka library that:</p><ul><li>Could be used just like @KafkaListener with minimal friction.</li><li>Dynamically controlled polling behavior based on message activity.</li><li>Gave services deep control over how and when consumers operated.</li><li>Was resilient to failures and production-grade edge cases.</li></ul><p>I created a custom annotation, <strong>@KafkaOptimizerListener</strong>, that developers could use exactly like @KafkaListener. Under the hood, though, this annotation:</p><ul><li>Bootstrapped a custom Kafka consumer manually.</li><li>Controlled the polling loop.</li><li>Handled offsets and commits explicitly.</li><li>Allowed dynamic sleep intervals between polls based on activity.</li></ul><h4>Manually Managing the Kafka Loop</h4><p>By bypassing the default Spring Kafka container and managing the consumer loop myself, I could fine-tune everything:</p><pre>while (running) {<br>    ConsumerRecords&lt;String, String&gt; records = consumer.poll(Duration.ofMillis(pollTimeout));<br>    <br>    if (records.isEmpty()) {<br>        emptyPollCount++;<br>        sleepTime = Math.min(maxSleepTime, sleepTime * 2); // Exponential backoff<br>    } else {<br>        emptyPollCount = 0;<br>        sleepTime = initialSleepTime; // Reset on record receipt<br>        process(records); // User-defined callback<br>    }<br>    <br>    Thread.sleep(sleepTime);<br>}</pre><p>This gave me answers to previously unanswered questions:</p><ul><li>What if a consumer fails to poll a record?<br> → Catch and retry logic with backoff.</li><li>What if the consumer thread dies silently?<br> → A watchdog service that monitors liveness and restarts if needed.</li><li>What if polling causes high CPU under low traffic?<br> → Adaptive delays, now fully in place.</li><li>What if the consumer crashes midway through processing a batch?<br> → Manual offset control to avoid message loss or duplication.</li></ul><h4>Offset Handling — Keeping It Simple, With One Caveat</h4><p>While building the Kafka Optimizer, I had to decide how to manage <strong>offsets</strong> — whether to commit them manually or let Kafka do its job.</p><p>After evaluating the options, I chose to keep it simple:</p><blockquote><strong><em>Let Kafka handle auto-commits</em></strong><em>.</em></blockquote><p>This worked well in most scenarios, as long as record processing succeeded. But what about when processing failed?</p><p>For that, I introduced a <strong>simple but effective mechanism</strong>:</p><p>When a record fails to process (due to an exception, timeout, etc.), I <strong>seeked the consumer back to the offset of that failed record</strong>, using:</p><pre>consumer.seek(topicPartition, failedOffset);</pre><p>This ensured that the failed record would be retried in the next poll.</p><h4>The Trade-Off</h4><p>This approach works well <strong>when failures are rare</strong> — which, according to our monitoring and logs, they were. But it comes with a known downside:</p><blockquote><strong><em>If you poll 1,000 records and the first record fails, all 1,000 records are re-polled next time — even though 999 were successfully polled the first time but not processed.</em></strong></blockquote><h4>Case 1: Order Doesn’t Matter — Use a DLT</h4><p>If <strong>processing order is not critical</strong> (e.g., independent events like logs, user activity, telemetry), a smarter approach is to:</p><ul><li>Send the <strong>failed record</strong> to a <strong>Dead Letter Topic (DLT)</strong>.</li><li>Continue processing the remaining 999 records.</li><li>Later, use a <strong>scheduled batch job (CRON or stream processor)</strong> to retry processing those DLT records separately.</li></ul><p>This ensures high throughput, minimal lag, and avoids blocking other valid records due to one bad apple.</p><h4>Case 2: Order Matters — Retry Before Skipping</h4><p>However, for many systems — such as order pipelines, payment events, or transaction logs — <strong>order of record processing matters</strong>. In such cases:</p><ul><li>You <strong>cannot skip or reorder records</strong>, even if they fail.</li><li>So the failed record <strong>must be handled before progressing</strong>.</li></ul><p>To support this, I implemented a <strong>retry mechanism</strong>:</p><ul><li>Each record is given up to <strong>X retry attempts</strong>.</li><li>Between retries, the consumer <strong>sleeps for a short backoff duration</strong> to prevent tight loops.</li><li>If the record <strong>still fails after X retries</strong>, it is marked as skipped and the consumer moves to the next offset.</li></ul><p>This ensures that <strong>important records are given every chance to succeed</strong>, but the system also <strong>doesn’t get stuck forever</strong> on a single bad message.</p><p>This might sound wasteful (and it is, in theory), but in practice:</p><ul><li>Our failure rate was extremely low.</li><li>Most polls returned far fewer than 1,000 records.</li><li>The simplicity and reliability of the model outweighed the small inefficiency.</li></ul><p>Still, I realize this might not work for every system, especially those with:</p><ul><li>High-throughput topics</li><li>Long record processing times</li><li>Higher failure rates</li></ul><h3>Part 3 : Bonus: Remote Control for Kafka Consumers</h3><p>Here’s where it got even more exciting.</p><p>Because I was manually starting and managing each consumer thread, I now had <strong>programmatic control</strong> over each Kafka consumer instance. So, I built a lightweight REST controller on top of it — allowing developers to:</p><ul><li><strong>Start or stop consumers</strong> at runtime via API.</li><li><strong>Use consumer IDs</strong> to identify and manage individual consumers.</li><li>Dynamically tune consumer behavior based on environment or deployment strategy.</li></ul><h4>Example Use Case: Blue-Green Deployment Optimization</h4><p>Let’s say we have three deployments:</p><ul><li>blue</li><li>green</li><li>beta</li></ul><p>If beta isn&#39;t currently receiving any user traffic (e.g., staging or dormant env), why keep Kafka consumers running there?</p><p>Now, with a simple HTTP call like:</p><pre>POST /kafka/stop?consumerId=beta-consumer-01</pre><p>The Kafka consumer shuts down gracefully — <strong>saving CPU instantly</strong>.</p><p>Need it again? Just hit:</p><pre>POST /kafka/start?consumerId=beta-consumer-01</pre><p>And the consumer boots up, resumes polling, and rejoins the stream.</p><h3>Final Results: The Impact in Numbers</h3><p>After all the investigation, experimentation, and engineering — it was time to measure the real-world results.</p><p>Here’s what we achieved:</p><ul><li><strong>Startup Time Reduced</strong><br> From <strong>29 seconds</strong> ⟶ <strong>18 seconds</strong><br> (~38% faster service boot time)</li><li><strong>Average CPU Usage Dropped</strong><br> From <strong>4.2%</strong> ⟶ <strong>3.0%</strong><br> (~29% reduction in overall CPU load)</li></ul><p>These optimizations not only saved infrastructure cost but also improved service responsiveness, deployment agility, and observability.</p><p>And the best part? These changes required <strong>no major architectural shifts</strong> — just a deeper understanding of how Kafka works under the hood, and a willingness to challenge defaults.</p><h4>Final Thoughts: What This Taught Me</h4><p>This journey taught me more than just Kafka internals. It taught me how deep performance issues often lie hidden in design assumptions. And how sometimes, small changes — like splitting consumer groups or adding intelligent sleep — can save real CPU, time, and money.</p><p>It also reminded me that <strong>“default” doesn’t always mean “optimal”</strong>, especially in large-scale systems.</p><p>From debugging rebalances to building a production-grade Kafka abstraction layer, this project challenged me, taught me, and made a real impact — both for my learning and my company.</p><h4>Your Turn: How Would You Handle It?</h4><p>I’d love to hear from other engineers and Kafka practitioners:</p><ul><li>How do you handle <strong>per-record failure recovery</strong> without reprocessing everything?</li><li>Have you implemented <strong>per-record offset commits</strong>, and how has that worked for you?</li><li>Would a batching + checkpoint approach be better in your use case?</li></ul><p>Feel free to share thoughts, feedback, or improvements — this is still evolving, and I’d love to make the library better with community input.</p><p>In upcoming articles, I’ll dive deeper into <strong>manual offset management in Kafka</strong> — when to use it and how to implement it safely. I’ll also share strategies for <strong>deploying changes to consumer groups</strong> without triggering data loss or unnecessary reprocessing. Stay tuned!</p><p>Much of what I learned came from exploring official docs and deep technical articles. Here are some of the most useful ones:</p><ul><li><a href="https://www.linkedin.com/pulse/kafka-consumer-group-rebalance-1-2-rob-golder/">Kafka Consumer Group Rebalance (Part 1)</a> — Rob Golder</li><li><a href="https://www.redpanda.com/guides/kafka-performance-kafka-rebalancing">Understanding Kafka Rebalancing</a> — Redpanda Guide</li><li><a href="https://kafka.apache.org/documentation/">Apache Kafka Official Documentation</a></li><li><a href="https://docs.confluent.io/kafka/introduction.html">Confluent Kafka Introduction</a></li><li><a href="https://docs.spring.io/spring-kafka/reference/index.html">Spring Kafka Reference Documentation</a></li><li><a href="https://javadoc.io/doc/org.apache.kafka/kafka-clients/latest/index.html">Kafka Clients Javadoc</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3976ab8209a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kafka Was Eating Our CPUs — Until I Built a Smarter Consumer]]></title>
            <link>https://medium.com/@guptaarman910/kafka-was-eating-our-cpus-until-i-built-a-smarter-consumer-27101e5b8d8e?source=rss-95a91a7861e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/27101e5b8d8e</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[kafka-streams]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Guptaarman]]></dc:creator>
            <pubDate>Sat, 12 Jul 2025 02:57:20 GMT</pubDate>
            <atom:updated>2025-07-24T10:48:46.349Z</atom:updated>
            <content:encoded><![CDATA[<h3>Kafka Consumer Group Rebalancing: The Hidden Cause of High CPU and Latency Spikes</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ydav9bJKqS_pK-euqgSMg.png" /></figure><p>During my internship , I was assigned a critical task — investigate and optimize Kafka’s unexpectedly high CPU usage. The infra team had flagged Kafka as one of the top contributors to CPU costs, and my job was to figure out why.</p><p>At first, it seemed like just another devops task. But what followed was a deep dive into Kafka’s internals, a trail of unexpected discoveries, and some very satisfying performance gains.</p><p>This article shares the journey — what I learned, how I approached the problem, and the optimization that ultimately cut CPU usage and reduced service startup time by over 40%.</p><h4>Enter Kafka — Understanding the Beast</h4><p>Like any good investigation, I started at the beginning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*e5N791ospxb2OEKR99mtPg.png" /><figcaption>Credit :- <a href="https://reeshabh-choudhary.medium.com/message-system-apache-kafka-basics-and-comparison-24226bc54415">Reesabh Choudhary</a></figcaption></figure><p>Kafka is a distributed event streaming platform made up of producers, consumers, brokers, topics, and partitions. While I had worked with it before, this time I had to truly understand how it ticks.</p><p>I focused on:</p><ul><li><strong>Producers and Consumers</strong>: who sends and who receives.</li><li><strong>Topics and Partitions</strong>: how data is grouped and distributed.</li><li><strong>Consumer Groups</strong>: how Kafka coordinates multiple consumers.</li><li><strong>Offset Management</strong>: how Kafka remembers what was consumed.</li></ul><p>As I unraveled each of these, I realized something strange in our setup: <strong>all consumers were placed in the same consumer group</strong>, even though they were consuming from different topics.</p><p>At first, this didn’t feel problematic. Intuitively, if each consumer is reading from a different topic, they shouldn’t interfere with each other — right?</p><p>Turns out, I was wrong.</p><h3>Part 1 : The Unexpected Rebalancing Mystery</h3><p>I started observing how Kafka behaved when services started, shut down, or restarted. One behavior stood out: whenever <strong>any</strong> one of the consumers restarted — even if it was consuming from a completely unrelated topic — <strong>all the other consumers in the same group were rebalancing</strong>.</p><p>This felt… wasteful.</p><p>Rebalancing is Kafka’s way of ensuring partitions are evenly assigned among consumers in a group. But in our case, the consumers weren’t sharing partitions at all — they were subscribed to <strong>different topics entirely</strong>. There was no overlap.</p><p>Still, every time a consumer left or joined the group (say, due to a restart), <strong>Kafka triggered a full rebalancing event</strong> for the entire group. This meant:</p><ul><li>All the consumers paused their work.</li><li>Resources were spent coordinating partition assignments.</li><li>CPU usage spiked during this coordination.</li><li>And most importantly — <strong>startup times for services increased</strong> because they had to wait for rebalancing to complete.</li></ul><p>I began searching for answers, reading Kafka documentation, mailing list threads, and GitHub discussions. Eventually, I found confirmation of what I was seeing: <strong>Kafka triggers rebalancing at the group level, not at the topic level</strong>.</p><p>Even if consumers are subscribed to separate topics, being in the same group binds them into a single unit for Kafka’s coordination logic.</p><h3>Kafka Group-Level Rebalancing: Simple Example</h3><h4>Scenario: One Group, Many Topics</h4><p>Imagine you have a single consumer group (let’s call it group-X). There are 10 consumers (C1 to C10). Each consumer is exclusively subscribed to a different Kafka topic. For example:</p><ul><li>C1 → topic-1</li><li>C2 → topic-2</li></ul><p>…</p><ul><li>C10 → topic-10</li></ul><h4>What Happens When a New Consumer Joins?</h4><p>A new consumer (C11) joins group-X. Even though each consumer handles a separate topic, Kafka considers the group as a whole.</p><p>As soon as C11 joins:</p><ul><li>All partition assignments for every topic within the group are recalculated.</li><li>This means <em>all ten existing consumers</em> undergo rebalancing, despite their subscriptions not overlapping.</li></ul><h3>The Fix — Split the Groups, Cut the Load</h3><p>Now that I understood the root cause — unnecessary rebalancing caused by all consumers being in the same group — the solution seemed obvious in hindsight:</p><blockquote><strong><em>Separate the consumers into different consumer groups, based on the topic they subscribe to.</em></strong></blockquote><p>So I did exactly that.</p><p>Instead of having all our consumers under a single group ID like consumer-group-service, I assigned each consumer a new group ID reflecting the topic or concern they were tied to. For example:</p><ul><li>user-events-consumer</li><li>order-events-consumer</li><li>billing-updates-consumer</li></ul><p>This way, each consumer effectively lived in its own isolated universe. No more collective rebalancing chaos.</p><h4>The Impact</h4><p>The results were immediate and significant:</p><ul><li><strong>CPU usage dropped</strong> — no more unnecessary partition negotiation for unrelated consumers.</li><li><strong>Startup time dropped from ~29 seconds to ~18 seconds</strong> — a <strong>~38% improvement</strong>.</li><li><strong>Operational stability increased</strong> — restarting one consumer no longer affected the others.</li></ul><p>One of the most unexpected but rewarding outcomes of this optimization was the <strong>dramatic reduction in service startup time</strong> — from 29 seconds to 18 seconds.</p><p>Here’s what was happening:</p><ul><li>Kafka treats a consumer group as a <strong>single coordination unit</strong>, so when a <strong>new consumer joins during service startup</strong>, Kafka <strong>triggers a rebalance</strong> for the entire group.</li><li>During rebalancing, <strong>all consumers in the group pause</strong> their work — they stop consuming, reassess partition assignments, and wait until Kafka finishes redistributing partitions.</li><li>Since multiple consumers were initializing <strong>at the same time</strong>, these rebalances weren’t isolated — they <strong>chained into each other</strong>, leading to what I call a <strong>“cascading rebalance storm”</strong>.</li></ul><p>It was a classic case of: <strong>one small change, big ripple effect.</strong></p><p>Much of what I learned came from exploring official docs and deep technical articles. Here are some of the most useful ones:</p><ul><li><a href="https://www.linkedin.com/pulse/kafka-consumer-group-rebalance-1-2-rob-golder/">Kafka Consumer Group Rebalance (Part 1)</a> — Rob Golder</li><li><a href="https://www.redpanda.com/guides/kafka-performance-kafka-rebalancing">Understanding Kafka Rebalancing</a> — Redpanda Guide</li><li><a href="https://kafka.apache.org/documentation/">Apache Kafka Official Documentation</a></li><li><a href="https://docs.confluent.io/kafka/introduction.html">Confluent Kafka Introduction</a></li><li><a href="https://docs.spring.io/spring-kafka/reference/index.html">Spring Kafka Reference Documentation</a></li><li><a href="https://javadoc.io/doc/org.apache.kafka/kafka-clients/latest/index.html">Kafka Clients Javadoc</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27101e5b8d8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Redisson Stole My Morning: Debugging a 4.5-Minute Startup Mystery]]></title>
            <link>https://medium.com/@guptaarman910/when-redisson-stole-my-morning-debugging-a-4-5-minute-startup-mystery-aed18acd5aef?source=rss-95a91a7861e3------2</link>
            <guid isPermaLink="false">https://medium.com/p/aed18acd5aef</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[hashcode]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Guptaarman]]></dc:creator>
            <pubDate>Sun, 29 Jun 2025 06:05:56 GMT</pubDate>
            <atom:updated>2025-06-29T07:18:00.155Z</atom:updated>
            <content:encoded><![CDATA[<p>I was recently handed a challenging task: investigate why one of our services was <strong>taking a staggering 4.5 minutes to start up</strong>. In today’s fast-paced deployment environments, such a delay is more than just an inconvenience — it’s a serious bottleneck. My mission was clear: dig deep, uncover the root cause, and bring that startup time down to something far more reasonable. Here’s how I tackled the mystery.</p><h3><strong>The Scene: A Service with Too Many Friends</strong></h3><p>This particular service was a heavyweight, relying on a constellation of dependencies:</p><ul><li>ElasticSearch</li><li>Redisson (Redis client)</li><li>Kafka</li><li>PostgreSQL</li><li>AWS S3</li></ul><blockquote>With so many moving parts, my first instinct was to suspect one of the big players — maybe ElasticSearch, notorious for handling vast datasets, was taking its sweet time.</blockquote><h3><strong>ElasticSearch: The Red Herring</strong></h3><p>I dove into the ElasticSearch integration, expecting to find it slogging through mountains of data at startup. <strong>But after reading through the internals of the ElasticSearch client, I realized it wasn’t loading any data at all during initialization — just setting up a connection.</strong> To be sure, I peppered the codebase with time logs around every ElasticSearch-related bean creation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*alP5ykd_DXAkgHTbYyQIww.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOd6bZ2ieJ-btwaiiZp1Rg.png" /><figcaption>This was the Elastic Search connection initializer, taking almost negeligible time execute.</figcaption></figure><p>While investigating the startup delay, I closely examined the Elasticsearch <strong>RestHighLevelClient</strong> initialization. One line in particular caught my attention:</p><pre>this.registry = new NamedXContentRegistry((List)Stream.of(<br>getDefaultNamedXContents().stream(), getProvidedNamedXContents().stream(), <br>namedXContentEntries.stream()).flatMap(Function.identity()).collect(<br>Collectors.toList()));</pre><p>This snippet initializes three key components:</p><ul><li><strong>getDefaultNamedXContents()</strong>: Provides the default classes defined by the Elasticsearch client for serialization and deserialization.</li><li><strong>getProvidedNamedXContents()</strong>: Includes any custom classes we supply for handling specific object types.</li><li><strong>namedXContentEntries</strong>: This one stood out—it scans the entire project and all dependencies to discover custom classes created for serializing and deserializing particular data objects.</li></ul><blockquote>Given the scale of our service, I suspected that initializing <strong>namedXContentEntries</strong> could be a bottleneck, potentially consuming significant time as it scanned through all project classes and dependencies.</blockquote><p>To test this theory, I wrote a small piece of code to <strong>measure how long this initialization actually took</strong> during startup. To my surprise, the process <strong>completed in just a few milliseconds</strong>. My suspicion was unfounded — <strong>this part of the Elasticsearch client was not responsible for the slow startup.</strong></p><h3><strong>Spotting the Pattern: The Logging Blackout</strong></h3><p>After confirming that bean initialization wasn’t the source of our 4.5-minute startup lag, I decided to monitor the entire startup process more closely. <strong>What I found was both intriguing and frustrating: there were two distinct periods — first for 3 minutes, then for 1 minute — where the logs went completely silent. <em>No output, no errors, just a total blackout.</em></strong></p><blockquote>This complete absence of logs strongly suggested that something specific (and blocking) was happening during those intervals. It wasn’t just slow — it was as if the application was frozen, waiting for a single operation to finish before moving on.</blockquote><h3><strong>Thread Dump to the Rescue</strong></h3><p>To dig deeper, <strong>I took thread dumps right in the middle of each blackout.</strong> The evidence was clear: <strong>the main thread was in a <em>blocked</em> state, and the culprit looks to be </strong><strong>redisson</strong>. This was a crucial clue—Redisson, our Redis client, was involved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oGdErPbBGRgryz8tdbcQiw.png" /></figure><blockquote>Reading further into the thread dump, I noticed that the main thread was stuck executing a function called hashCode. This was unexpected, as hashCode is typically a lightweight operation.</blockquote><h3><strong>The Realization: Redisson’s Heavy hashCode</strong></h3><p>Curious, I dove into the Redisson client library’s source code. There, <strong>I discovered that this particular </strong><strong>hashCode function wasn’t your typical hash calculation—it was traversing all the key-value pairs and generating a hash, a process that can be extremely time-consuming if the dataset is large or if network latency is involved.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*EqMWz9i50d71v44e6FKafA.png" /></figure><p>After discovering that Redisson was blocking the main thread during startup, <strong>I needed to understand why this heavy operation was even running at that time.</strong> Digging deeper into the thread dump, <strong>I realized the culprit was Spring’s bean creation process.</strong></p><h3><strong>How Spring Bean Creation Triggered the Problem</strong></h3><blockquote>During bean creation, Spring records destruction information for each bean — essentially, instructions on how to clean up the bean when the application shuts down. To manage this, Spring uses a concurrent hashmap, where the key is generated by calling the <strong>hashCode</strong> method on the bean name. Normally, Java’s default <strong>hashCode</strong> implementation is extremely fast. However, Redisson overrides this method in its map implementations. Instead of a simple calculation, Redisson’s <strong>hashCode</strong> traverses all entries in the map to compute the hash.</blockquote><h3>Why It Was So Slow</h3><p>I investigated which caches were causing the slowdown and found two major offenders: one cache with <strong>4.5 million </strong>entries and another with <strong>2.1 million</strong>.</p><blockquote>Every time Spring tried to store destruction info for a Redisson map bean, it triggered this overridden <strong>hashCode</strong> method, which then scanned through millions of entries.</blockquote><p>This explained the long periods of inactivity in the logs—the application was essentially frozen while Redisson’s <strong>hashCode</strong> churned through massive caches.</p><h3>Root Cause: Cache Configuration</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-ztgbLyV-q7P8SZ-j1S8OQ.png" /></figure><p>The caches were configured with <strong>LocalCachedMapOptions.defaults()</strong>, which sets the cache <strong>TTL (Time-To-Live)</strong> to infinite. As a result, data was never evicted, and the caches kept growing unchecked.</p><h3>The Solution</h3><blockquote>I immediately cleared the oversized caches.</blockquote><blockquote>I reconfigured the beans to use a sensible TTL, ensuring that cache entries would be evicted over time.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HTP13Anqp8ni9IzuL74Pbg.png" /></figure><h3>The Problem Was Titanic, The Solution Was… a Mop?</h3><p>After hours of playing detective, analyzing thread dumps, and suspecting every service in the stack, I finally uncovered the villain behind our 4.5-minute startup: millions of dusty old cache entries clogging up Redisson. The drama! The suspense! The hours spent squinting at logs and stack traces!</p><blockquote>And the solution?<br>Not a new algorithm.<br>Not a fancy optimization.<br>Not even a heroic code refactor.</blockquote><p>Nope.<br><strong>Just… clear the caches.</strong></p><p>That’s right — after all that, the fix was basically the IT equivalent of “have you tried turning it off and on again?” I swept out those monstrous caches, and — BOOM! — startup time dropped from a glacial 4.5 minutes to a breezy 0.5 minutes.</p><p><strong>Sometimes, the mountain you’re climbing is just a pile of junk you forgot to sweep. Lesson learned: when in doubt, bring a broom! 🧹</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aed18acd5aef" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>