<?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 Raghav Jha on Medium]]></title>
        <description><![CDATA[Stories by Raghav Jha on Medium]]></description>
        <link>https://medium.com/@raghav-jha?source=rss-ce65f0e859b7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xyNKcu4imDIDoBuFPK3kqA.jpeg</url>
            <title>Stories by Raghav Jha on Medium</title>
            <link>https://medium.com/@raghav-jha?source=rss-ce65f0e859b7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:02:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raghav-jha/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[Resolving Redis Cluster Spikes at Glance]]></title>
            <link>https://engg.glance.com/resolving-redis-cluster-spikes-at-glance-c418899eb0c1?source=rss-ce65f0e859b7------2</link>
            <guid isPermaLink="false">https://medium.com/p/c418899eb0c1</guid>
            <category><![CDATA[spring-data-redis]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <dc:creator><![CDATA[Raghav Jha]]></dc:creator>
            <pubDate>Thu, 27 Feb 2025 05:09:10 GMT</pubDate>
            <atom:updated>2025-02-27T05:09:10.494Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background: Redis, Our Reliable Partner</h3><p>At Glance, we rely heavily on Redis as our distributed cache. It’s the backbone of our content management system (CMS) powering everything from enriching feeds to managing content lifecycle and serving detailed content views. Redis has been our trusted partner in delivering fast, efficient responses — until it wasn’t.</p><p>It was the last week of December — holiday cheer was in the air, but for our engineering team at Glance, the season was anything but merry!! Instead of receiving holiday greetings, we were getting Redis read timeouts and severe performance degradation. One of our systems, which relies on Redis for caching and data retrieval, began struggling, causing a massive spike in latency and API failures, and our users were starting to feel it.</p><p>Interestingly, this issue was isolated to this specific system. Other parts of the infrastructure were unaffected. The problem didn’t appear suddenly; it developed gradually over time. As we published more content and traffic increased, Redis initially managed the load without any issues. We figured it was just the usual holiday surge, nothing to be concerned about. But as the days went by, it became clear that something had gone seriously wrong!!</p><h3>The First Line of Defense: Quick Fixes, No Results</h3><p>Naturally, we started with the most obvious solution — blame the code. We reviewed the recent changes to see if some new feature or update could have triggered this avalanche. However, our search for the smoking gun led us to a disappointing conclusion: there were no major changes that could explain the degradation.</p><p>In the spirit of “try anything once,” we started throwing fixes at the problem, but none stuck. We progressively ramped up the Redis provisioned throughput limit by a factor of <strong><em>5</em></strong>, eventually reaching a <strong>60-fold</strong> increase, all in a desperate attempt to keep the system running. But it was like trying to fix a leaky bucket by adding more water. Each increase in capacity only bought us a bit of temporary relief — nothing sustainable.</p><h3>The Deep Dive: Redis Wasn’t the Problem — We Were</h3><p>After hours of debugging, we realized: Redis wasn’t the problem — it was how we were interacting with it.</p><p>Redis was reporting <strong><em>600K OPS</em></strong>, but our system was only sending <strong><em>10K OPS </em></strong>at peak. The disparity didn’t add up, so we started inspecting our code more carefully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XxVY3x7v_w_-U7Ton0pqUA.png" /><figcaption>Client-side insights from Grafana</figcaption></figure><p>Enter Spring Data Redis — the library we use to interact with Redis. We discovered that the Spring Data Redis library internally manages a Redis Set for each write operation performed through the <em>Repository</em> interface. When executing the <em>findAll</em>method, it sends a <em>SMEMBERS</em>command to retrieve all the members of the Redis set, followed by <em>N</em>calls to retrieve the details of each member. In total, this results in <em>N+1</em> Redis calls — one to fetch the set members and <em>N</em> more to get the details of each member.</p><pre>//excerpt taken from Spring Data Redis library<br><br>public &lt;T&gt; List&lt;T&gt; getAllOf(String keyspace, Class&lt;T&gt; type, long offset, int rows) {<br><br>  byte[] binKeyspace = toBytes(keyspace);<br><br>  // executes a SMEMBERS call<br>  Set&lt;byte[]&gt; ids = redisOps.execute((RedisCallback&lt;Set&lt;byte[]&gt;&gt;) <br>                      connection -&gt; connection.sMembers(binKeyspace));<br><br>  List&lt;T&gt; result = new ArrayList&lt;&gt;();<br>  List&lt;byte[]&gt; keys = new ArrayList&lt;&gt;(ids);<br><br>  if (keys.isEmpty() || keys.size() &lt; offset) {<br>   return Collections.emptyList();<br>  }<br><br>  offset = Math.max(0, offset);<br><br>  if (rows &gt; 0) {<br>   keys = keys.subList((int) offset, Math.min((int) offset + rows, keys.size()));<br>  }<br>  // for each member, makes a GET call to redis<br>  for (byte[] key : keys) {<br>   result.add(get(key, keyspace, type));<br>  }<br>  return result;<br> }</pre><h3>The Problem: A Set with More Ghosts Than Members</h3><p>Here’s the root of the issue: we had implemented the <em>@TimeToLive</em> annotation on our Redis cache to automatically expire items after a set period. While this worked for expiration — removing expired keys from Redis — the real problem arose with Spring Data Redis. It <em>didn’t automatically clean up the stale items from the internally managed Redis Set</em>. As a result, even though expired items were deleted from Redis, they remained in the set. This meant the library continued to process all the outdated data, even though it was technically expired.</p><p>To illustrate the scale of the problem: we had a Redis set with <em>40,000</em> members, but only <em>800</em> were active. The remaining <em>39,200</em> were obsolete entries from old processes. Yet, Spring Data Redis continued issuing <em>GET</em>commands for all <em>40,000</em> members — like walking through a database graveyard — and we had multiple such sets with a higher order of cardinality. The outcome? A massive surge in Redis operations overwhelmed our cluster.</p><p>We later found out that Spring provides a configuration setting to address this very issue, See this <a href="https://stackoverflow.com/questions/41693774/spring-redis-indexes-not-deleted-after-main-entry-expires/41695902">Stack Overflow Question</a> for details. But — surprise! — this setting isn’t enabled by default, and we didn’t know about it until it was too late. The documentation could have been more upfront about this.</p><h3>The Fix: Cleaning Up the Cache (Finally)</h3><p>Once we identified the root cause, the solution became clear: clean up the stale members in the Redis set.</p><p>We wrote a cleanup script that:</p><ol><li>Listed all members of the Redis set for each repository.</li><li>Divided the list into smaller batches of <em>500</em> items to avoid overburdening the cluster, which was already under heavy load.</li><li>Checked if each member was valid (i.e., still in use).</li><li>Deleted non-existent or expired members.</li></ol><pre>// KeySpace is a construct used by Spring Data Redis for each Redis Hash<br>private long cleanUpSMembersBasedOnKeyspace(String keyspace) {<br>        log.info(&quot;Cleaning up keyspace{}&quot;, keyspace);<br>        // we used stringRedisTemplate directly to deal with the set for simplicity<br>        Set&lt;String&gt; members = stringRedisTemplate.opsForSet().members(keyspace);<br>    <br>        if (CollectionUtils.isEmpty(members)) {<br>            return 0L;<br>        }<br><br>        List&lt;String&gt; toBeDeletedMembers = new ArrayList&lt;&gt;();<br><br>        for (String member : members) {<br>            String hashSetKeyName = keyspace + &quot;:&quot; + member;<br>            if (!redisTemplate.hasKey(hashSetKeyName)) {<br>                toBeDeletedMembers.add(member);<br>            }<br>        }<br>        // Used ListUtils.partition to split the list into batches<br>        List&lt;List&lt;String&gt;&gt; batches = ListUtils.partition(toBeDeletedMembers, 500);<br>        log.info(&quot;Keyspace: {}, Batches size: {}&quot;,keyspace, batches.size());<br>       <br>        long totalDeletedCount = batches.stream()<br>                .mapToLong(<br>                        eachBatch -&gt; stringRedisTemplate.opsForSet().remove(keyspace, eachBatch.toArray(new String[0]))<br>                ).sum();<br><br>        log.info(&quot;Total number of ghost members removed: {}&quot;, totalDeletedCount);<br>        return totalDeletedCount;<br>    }</pre><p>We deployed the script and waited with bated breath for the results.</p><h3>Results: From Chaos to Calm</h3><p>The cleanup was almost like flipping a switch. After deploying the script, we watched as Redis OPS plummeted by a factor of 60, returning to its normal rate. The API calls that were previously choking under the load now executed smoothly, latency was slashed, and the timeouts disappeared. User devices started receiving fresh, updated content, and our infrastructure costs took a nosedive, too. It was a performance optimization miracle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4MbK79xhuNscuSc5F2vrDg.png" /><figcaption>Server-side metrics from Redis dashboard</figcaption></figure><p>To keep things in tip-top shape, we automated the cleanup process with a daily CRON job. Now, every night, the script runs to make sure that only active members stay in the Redis set, preventing the same pile-up from happening again. What had once been a bottleneck was now running like a well-oiled machine.</p><h3>Key Takeaways:</h3><ol><li><strong><em>Look before you leap</em></strong>: Third-party libraries like Spring Data Redis abstract away a lot of the inner workings of Redis. While they make life easier, they can also hide performance issues — like a bad hair day you didn’t notice until you left the house. In this case, the double <em>SMEMBERS</em> + <em>GET</em>combo was a performance killer.</li><li><strong><em>Check the defaults:</em></strong> Configuration settings in libraries like Spring Data Redis can be easy to overlook. Always double-check that what you expect is enabled.</li><li><strong><em>Scale smart:</em></strong> More resources don’t always fix the problem — sometimes a little housekeeping can go a long way.</li><li><strong><em>Don’t let stale data build-up:</em></strong> Stale data in your Redis sets is like junk in your garage — it’s easy to ignore until it completely overwhelms you.</li><li><strong><em>Automate the mundane:</em></strong> Automating tasks like cleanup can save you a lot of headaches in the long run.</li></ol><p>So, while Redis had a bit of a holiday hiccup, it’s now back to its old, fast self — and we learned an important lesson along the way. <strong><em>A clean cache is a happy cache</em></strong>!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c418899eb0c1" width="1" height="1" alt=""><hr><p><a href="https://engg.glance.com/resolving-redis-cluster-spikes-at-glance-c418899eb0c1">Resolving Redis Cluster Spikes at Glance</a> was originally published in <a href="https://engg.glance.com/">Glance</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>