<?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 Saksham Sahgal on Medium]]></title>
        <description><![CDATA[Stories by Saksham Sahgal on Medium]]></description>
        <link>https://medium.com/@sakshamsahgal5?source=rss-fedbe07f6613------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*K5XgDWYMyMbW_DYlj8nhsg.jpeg</url>
            <title>Stories by Saksham Sahgal on Medium</title>
            <link>https://medium.com/@sakshamsahgal5?source=rss-fedbe07f6613------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:30:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sakshamsahgal5/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[Counting at Scale: Sharded Counters with Redis Caching]]></title>
            <link>https://medium.com/@sakshamsahgal5/counting-at-scale-sharded-counters-with-redis-caching-d0a4c5e81236?source=rss-fedbe07f6613------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0a4c5e81236</guid>
            <category><![CDATA[counting]]></category>
            <category><![CDATA[sharding]]></category>
            <category><![CDATA[contention]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[cache]]></category>
            <dc:creator><![CDATA[Saksham Sahgal]]></dc:creator>
            <pubDate>Thu, 24 Jul 2025 18:15:59 GMT</pubDate>
            <atom:updated>2025-07-24T18:15:59.109Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In 2012, Facebook’s engineers hit a surprising bottleneck. The “Like” button was generating millions of tiny database writes every second. What should have been a trivial +1 turned into a performance nightmare, with lock contention overwhelming the database.</blockquote><blockquote>And Facebook wasn’t alone. Platforms like YouTube, Reddit, and Twitter, all of which handle viral content and real-time interactions, ran into the same core problem: <strong>how do you scale counting without overloading your data infrastructure</strong></blockquote><h4>Core Idea</h4><p>To simplify the problem lets say our database has a table with this schema :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRyFqXHGuToeZicJi3sOpg.png" /></figure><p>Everytime someone hits the like button on a post, this query would run</p><pre>UPDATE posts<br>SET likes_count = likes_count + 1<br>WHERE post_id = &#39;123&#39;;</pre><h4>Why is this a Bottleneck ?</h4><p>This query would run for each user’s like on this post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HxAhJTQMdE8rixuqcvP83w.png" /><figcaption><strong>Multiple users Updating the same Row in the Database</strong></figcaption></figure><p>So the database applies a <strong>lock</strong> on that row to prevent corruption, so it queues the updates:</p><ul><li>A → lock granted → update → release.</li><li>B → wait → lock granted → update → release.</li><li>C → wait…</li></ul><p>This resulted all the requests getting queued at this row.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s10XUgfJRy-20PxH_ZlOeg.png" /></figure><h3>What would happen at scale ?</h3><p>Now imagine 10,000 people liking a celebrity’s post <strong>in one second</strong>.</p><h4>The system chokes on lock contention.</h4><p>Every like triggers an UPDATE on the same row. The database tries to serialize these concurrent writes, leading to row-level locks and write queuing. Performance degrades rapidly.</p><h4>Some likes are dropped or delayed.</h4><p>As contention increases, some requests time out or fail silently. Others are retried, introducing latency. In worst cases, some user actions are lost entirely.</p><h4>The page will look outdated</h4><p>Since likes are written slower than they’re coming in, reads (like SELECT likes_count) show stale values. The user sees 1,500 likes when 9,000 have already happened. It breaks real-time expectations and trust.</p><h4>Countering Contention with Sharded Counter Design</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gMCK6d8mWVKkWtyA28cyEg.png" /><figcaption>Each update request Goes in a seperate Row</figcaption></figure><p>To fix this, we use <strong>sharded counters</strong>. Instead of storing one likes_count per post, we create multiple <strong>shards</strong>—say 100 rows for the same post, each with a unique shard_id. When someone clicks “like,” the system <strong>randomly picks one shard</strong> (e.g., shard #2) and increments its counter. This distributes the 10,000 concurrent updates across 100 rows, reducing lock contention by ~99%. All writes happen in parallel, with minimal blocking.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLfnSPVwmhQmwTkTsDV2CQ.png" /><figcaption>Distributed Queues</figcaption></figure><p>Each shard is stored as a separate row (or record) in the database, so the Traffic Queue is distributed across Rows.</p><h4>The Hidden Cost of Sharding</h4><p>While sharded counters solve the write bottleneck beautifully, they introduce a new challenge: reading becomes more complex and slightly slower.</p><p>It quietly shifts complexity to the <strong>read path</strong>. Previously, getting the total likes was as simple as reading a single row with a query like —</p><pre>SELECT likes_count<br>FROM posts<br>WHERE post_id = &#39;123&#39;;</pre><p>Now for each read it would have to calculate the sum of each shard by a query like :</p><pre>SELECT SUM(likes_count) <br>FROM posts<br>WHERE post_id = &#39;123&#39;;</pre><p>This query hits <strong>multiple rows instead of one</strong>, increasing disk I/O and adding latency. At small scale, this overhead is negligible. But at large scale, especially for viral posts, this becomes a bottleneck on the <strong>read side</strong>.</p><h4>Countering Read Latency</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*im7lmV7VZABNkhXHyyVRug.png" /></figure><p>To avoid hitting the database on every read, we introduce <strong>Redis caching</strong>. Instead of summing up all shard values every time someone views a post, we <strong>precompute and store the total like count in Redis</strong>. When a user loads the page, the system can instantly return the cached count:</p><p>This makes reads <strong>blazing fast</strong> — often in under a millisecond — and takes pressure off the database entirely. The cache is <strong>refreshed periodically</strong> (e.g., every few seconds).</p><p>So in summary everytime someone Reads the likes Count it hits Redis cache instead of hitting the Database directly and a periodic functions updates the Cache every few seconds by querying the Database, this inludes a slight Latency but it’s totaly acceptable.</p><p>At scale, small inefficiencies become monsters. But with the right algorithm, monsters become math problems — and math problems, we solve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0a4c5e81236" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>