<?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 Jasdeep Singh Kapoor on Medium]]></title>
        <description><![CDATA[Stories by Jasdeep Singh Kapoor on Medium]]></description>
        <link>https://medium.com/@kapoorjasdeep?source=rss-b0dc10b7d34f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HAR-FfgdgmBHkiOc</url>
            <title>Stories by Jasdeep Singh Kapoor on Medium</title>
            <link>https://medium.com/@kapoorjasdeep?source=rss-b0dc10b7d34f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 15:01:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kapoorjasdeep/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[Measuring Kafka Consumer TPS: Raw Throughput vs Realistic Processing]]></title>
            <link>https://medium.com/@kapoorjasdeep/measuring-kafka-consumer-tps-raw-throughput-vs-realistic-processing-a2fbda84e3f6?source=rss-b0dc10b7d34f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2fbda84e3f6</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Jasdeep Singh Kapoor]]></dc:creator>
            <pubDate>Fri, 27 Feb 2026 07:29:32 GMT</pubDate>
            <atom:updated>2026-02-27T07:31:40.739Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9NGJ055Ln_vTeYHumW8Ppg.png" /><figcaption>Kafka TPS Testing with multiple consumers for real world benchmarks</figcaption></figure><p>Kafka throughput numbers are often quoted without context. Producer TPS looks impressive, but <strong>consumer TPS is what actually determines whether your system keeps up or falls behind</strong>.</p><p>In this article, I benchmark Kafka <strong>locally</strong> and focus specifically on <strong>consumer throughput under three realistic scenarios</strong>, using <strong>real measurements</strong>, not theoretical numbers.</p><h3>Test Environment</h3><p>All benchmarks were run on:</p><ul><li><strong>Machine:</strong> MacBook Air <strong>M4</strong>, 16 GB RAM</li><li><strong>OS:</strong> macOS</li><li><strong>Kafka:</strong> Single broker (Docker)</li><li><strong>Topic:</strong> 3 partitions, replication factor 1</li><li><strong>Language:</strong> Java</li><li><strong>Consumers:</strong> Kafka Java client</li><li><strong>Producers:</strong> Kafka Java client</li></ul><p>Kafka was run locally using Docker Compose to isolate <strong>client-side behavior</strong>.</p><h3>Producer TPS (Baseline)</h3><p>The producer benchmark was run <strong>once</strong>, since producer behavior remains consistent across consumer tests.</p><pre>Messages sent: 1,000,000<br>Time taken: 1,158 ms<br>Producer TPS: ~863,558 messages/sec</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*psw7yD-W0OMpPZEvWnw0sg.png" /><figcaption>Kafka Producer TPS for 100000 messages and three partitions</figcaption></figure><h4>What this represents</h4><ul><li>Asynchronous sends</li><li>Aggressive batching</li><li>No application logic</li><li>Writes primarily hitting OS page cache</li></ul><p>This number represents <strong>raw ingestion capacity</strong>, not end-to-end system throughput.</p><h3>Why Consumer TPS Matters More</h3><p>Kafka producers are rarely the bottleneck.<br> Consumers determine:</p><ul><li>Backlog growth</li><li>Lag</li><li>System stability</li><li>Scalability limits</li></ul><p>So the rest of this article focuses <strong>entirely on consumers</strong>.</p><h4>Consumer Test Setup (Common)</h4><p>For all consumer experiments:</p><ul><li>Producer was run <strong>once and stopped</strong></li><li>Consumers read pre-produced data</li><li>Offsets committed synchronously</li><li>Same topic and partitions</li><li>Same consumer group where applicable</li></ul><h3>Consumer Test 1 — Single Consumer, No Processing</h3><h4>What this test measures</h4><p>This test measures the <strong>maximum speed at which Kafka can deliver messages to a consumer</strong> when the consumer does nothing except:</p><ul><li>Poll records</li><li>Deserialize</li><li>Commit offsets</li></ul><p>There is <strong>no application logic</strong>.</p><pre>Messages consumed: 1,000,000<br>Time taken: 3,922 ms<br>Consumer TPS: ~254,972 messages/sec</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*LSjVMtamEa_iTlo_Iu4tGw.png" /><figcaption>Kafka Single Consumer TPS for 100000 messages and three partitions with no processing time for each event</figcaption></figure><h4>Interpretation</h4><p>Even with no processing:</p><ul><li>Polling is synchronous</li><li>Deserialization costs exist</li><li>Offset commits hit __consumer_offsets</li><li>A single consumer processes partitions sequentially</li></ul><p>This is the <strong>upper bound</strong> for a single consumer thread.</p><h3>Consumer Test 2 — Single Consumer with Processing Delay</h3><h4>What this test measures</h4><p>This simulates <strong>real-world consumer work</strong>, such as:</p><ul><li>API calls</li><li>Database writes</li><li>Logging</li><li>Downstream service calls</li></ul><p>Each message incurs a <strong>2 ms processing delay</strong>.</p><h4>Result</h4><pre>Messages consumed: 1,000,000<br>Time taken (ms): 18,921<br>Consumer TPS: ~52,851 messages/sec</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*ICVaUFKpVfmUXtS1HzoSHA.png" /><figcaption>Kafka Single Consumer TPS for 100000 messages and three partitions with 10ms processing time for each event</figcaption></figure><h4>Why TPS drops</h4><p>Once per-batch processing is introduced:</p><ul><li>Kafka is no longer the bottleneck</li><li>Application logic dominates throughput</li><li>Consumer speed is bounded by processing latency</li></ul><p>This demonstrates a key reality:</p><blockquote><strong><em>Kafka throughput is usually higher than application throughput.</em></strong></blockquote><h3>Consumer Test 3 — Processing Delay with 3 Consumers (Parallel)</h3><h4>Why this test matters</h4><p>Kafka is designed to scale consumers <strong>horizontally</strong>, not vertically.</p><p>Since the topic has <strong>3 partitions</strong>, Kafka can assign:</p><ul><li>1 partition per consumer</li><li>True parallelism</li></ul><h4>Setup</h4><ul><li>3 consumer JVMs</li><li>Same consumer group</li><li>Same 2 ms processing delay</li><li>Kafka automatically rebalanced partitions</li></ul><p>Each consumer processed ~300k messages.</p><h4>Results (Per Consumer)</h4><pre>Consumer A:<br>Messages consumed: ~300,964<br>Time taken (ms): 9,399<br>TPS: ~32,020<br><br>Consumer B:<br>Messages consumed: ~300,469<br>Time taken (ms): 17,665<br>TPS: ~17,009<br><br>Consumer C:<br>Messages consumed: ~300,948<br>Time taken (ms): 26,171<br>TPS: ~11,499</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*VJdDqmDTKaf_WG316H-KfQ.png" /><figcaption>Consumer A: Kafka Parallel Consumer TPS for 100000 messages and three partitions with 2ms processing time for each batch event of 1000</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/752/1*z12mromm478fipZCf3qgYw.png" /><figcaption>Consumer B: Kafka Parallel Consumer TPS for 100000 messages and three partitions with 2ms processing time for each batch event of 1000</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/778/1*yFNHbuW_v55GhNCU3NW3LQ.png" /><figcaption>Consumer C: Kafka Parallel Consumer TPS for 100000 messages and three partitions with 2ms processing time for each batch event of 1000</figcaption></figure><h4>Aggregate Throughput</h4><p>When running in parallel, the <strong>effective consumer throughput</strong> is the <strong>sum of all consumers</strong>:</p><pre>Aggregate Consumer TPS ≈ ~60,000 messages/sec</pre><p>This is <strong>higher than the single-consumer case</strong>.</p><h4>Why Parallel Consumers Scale Throughput</h4><ul><li>Kafka assigns <strong>one consumer per partition</strong></li><li>Consumers run independently</li><li>Processing latency is overlapped</li><li>Offset commits are isolated per partition</li></ul><p>This is Kafka’s <strong>intended scaling model</strong>.</p><h3>Why Parallel Consumers Win Here (Key Insight)</h3><p>This experiment highlights a critical Kafka design principle:</p><blockquote><strong><em>Parallel consumers only provide benefits when processing dominates Kafka overhead.</em></strong></blockquote><p>Here’s why scaling worked this time:</p><h4>1️⃣ Processing Time Is Now the Bottleneck</h4><p>With heavier per-message processing:</p><ul><li>Kafka fetch cost becomes relatively small</li><li>Processing latency dominates</li><li>Parallelism allows overlapping work</li></ul><h4>2️⃣ CPU Utilization Improves</h4><p>Instead of:</p><ul><li>One consumer blocking on processing</li></ul><p>We now have:</p><ul><li>Multiple consumers utilizing different CPU cores</li><li>Better overall CPU utilization</li></ul><h3>Final Thought</h3><p>Local benchmarks can be misleading if taken at face value.<br> The real value comes from understanding <strong>why numbers change</strong>, not just what the numbers are.</p><p>This experiment clearly shows:</p><ul><li>Kafka is rarely the bottleneck</li><li>Application design determines throughput</li><li>Consumer parallelism must be evaluated <strong>in the context of processing cost</strong></li></ul><p>That understanding is what leads to correct Kafka architecture decisions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2fbda84e3f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two Ways to Stop Chaos in Databases — But Only One Works for You]]></title>
            <link>https://medium.com/@kapoorjasdeep/optimistic-vs-pessimistic-locking-which-is-the-way-to-go-70503a52e054?source=rss-b0dc10b7d34f------2</link>
            <guid isPermaLink="false">https://medium.com/p/70503a52e054</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Jasdeep Singh Kapoor]]></dc:creator>
            <pubDate>Fri, 12 Sep 2025 13:42:57 GMT</pubDate>
            <atom:updated>2025-09-15T09:01:48.251Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wffnk3tqn5dO5BLvBJxPnw.png" /><figcaption>Optimistic vs Pessimistic Locking Techniques</figcaption></figure><h4>What is Locking and why is it needed?</h4><p>When two requests come at the exact same time and requires to update the same row. In such a scenario, how do you decide which request to proceed with? What will happen to the other request? how to handle conflicts? That is where Locking comes in to ensure handling such situations without causing any data discrepancy and gracefully handling errors.</p><p>There are many types of locking mechanisms, today we will discuss two of those: <strong>Optimistic Locking</strong> and <strong>Pessimistic Locking</strong></p><h4>Optimistic Locking</h4><p>Situation: In my company we have our own <strong>feature flag delivery system</strong> where users can come create, update and access the feature flags. Now suppose two users want to update the same feature flag at the exact same time with two different configs:</p><p><strong>Current feature flag in DB:</strong></p><pre>{<br>  &quot;id&quot;: &quot;dark-mode&quot;,<br>  &quot;enabled&quot;: false,<br>  &quot;description&quot;: &quot;Disable dark mode for UI&quot;,<br>  &quot;version&quot;: 3, <br>  &quot;updatedAt&quot;: &quot;2025-09-12T12:00:00Z&quot;<br>}</pre><p><strong>Client A config:</strong></p><pre>{<br>  &quot;id&quot;: &quot;dark-mode&quot;,<br>  &quot;enabled&quot;: true,<br>  &quot;description&quot;: &quot;Enable dark mode for UI&quot;,<br>  &quot;version&quot;: 3, <br>  &quot;updatedAt&quot;: &quot;2025-09-12T12:00:00Z&quot;<br>}</pre><p><strong>Client B config:</strong></p><pre>{<br>  &quot;id&quot;: &quot;dark-mode&quot;,<br>  &quot;enabled&quot;: false,<br>  &quot;description&quot;: &quot;This feature is temporary disabled&quot;,<br>  &quot;version&quot;: 3, <br>  &quot;updatedAt&quot;: &quot;2025-09-12T12:00:00Z&quot;<br>}</pre><h4>Conflict Case</h4><p>As you can both the users are trying to update the same flag with different config values and will have different impacts on the feature flag evaluation. How do we tackle this ? <strong>The obvious choice is to just overwrite the latest request.</strong></p><p><strong>The “just overwrite the latest request”:</strong></p><ul><li><strong>Request A</strong> (from Client A) → wants enabled: true, version=3</li><li><strong>Request B</strong> (from Client B) → wants description: ‘This feature is temporary disabled’, version=3</li></ul><p>With the current implementation we first take the request A and write it into DB and immediately overwrite it with request B</p><ul><li><strong>If A commits first</strong> → state becomes { enabled: true, version: 4 }</li><li><strong>Then B overwrites it</strong> → { description: ‘This feature is temporary disabled’ version: 5 }</li></ul><h4>Issues with this Approach</h4><p>Some issues that might arise with the current approach:</p><ul><li><strong>Lost updates</strong>: Client A might think that their change was saved but it was overwritten by Client B.</li><li><strong>No intent awareness</strong>: The server has no idea which change is more important. Sometimes “latest” is not necessarily “correct.”</li><li><strong>User confusion</strong>: Client A sees the flag enabled in their UI, but the database says disabled because Client B overwrote it milliseconds later.</li></ul><h4>Correct Approach</h4><p>In this approach we don’t overwrite but let one of the requests succeed and the other one fails making sure the client knows about the failed update request.</p><p><strong>For Client A:</strong></p><pre>UPDATE feature_flags <br>SET enabled = true, version = version + 1<br>WHERE id = &#39;dark-mode&#39; AND version = 3;</pre><p>✅ This succeeds → row updated to version=4.</p><p><strong>For Client B:</strong></p><pre>UPDATE feature_flags <br>SET description = &#39;This feature is temporary disabled&#39;, version = version + 1<br>WHERE id = &#39;dark-mode&#39; AND version = 3;</pre><p>❌ No rows match (because version is now 4).</p><p>👉 <strong>Result</strong>:</p><ul><li>Client A’s change is applied.</li><li>Client B is informed about the conflict: <em>“Hey, your copy of the data is stale, fetch the latest and retry.”</em></li><li>No silent overwrites.</li></ul><h3>Pessimistic Locking</h3><p>Now the above approach of using <strong>optimistic locking </strong>works for systems where the <strong>conflicts occur relatively less</strong>. For systems with high amount of <strong>concurrent writes</strong>, failing write requests often due to conflicts will hamper the overall user experience.</p><h4>Ideal Approach For Highly Concurrent Systems</h4><p>Instead of failing the requests we pick the requests sequentially maintaining a strict order. Each request holds a lock on the particular row which needs to be updated. All the other requests wait in line for their turn are only picked up once the previous update is successful and lock is release.</p><ul><li><strong>Request A</strong> (from Client A) → wants enabled: true, version=3</li><li><strong>Request B</strong> (from Client B) → wants description: ‘This feature is temporary disabled’, version=3</li></ul><p><strong>For Client A:</strong></p><pre>BEGIN;<br>SELECT * <br>FROM feature_flags <br>WHERE id = &#39;dark-mode&#39;<br>FOR UPDATE;</pre><p>🔒 This <strong>locks the row</strong> in the DB. Now no other transaction can modify this row until this transaction is commited/rolled back.</p><p><strong>Client B transaction blocked</strong></p><pre>BEGIN;<br>SELECT * <br>FROM feature_flags <br>WHERE id = &#39;dark-mode&#39;<br>FOR UPDATE;</pre><p>Client B also tries the acquire the lock for the same row but its transaction is blocked and kept in waiting waiting for the lock to be released.</p><p><strong>Client A Updates:</strong></p><pre>UPDATE feature_flags<br>SET enabled = true, version = version + 1<br>WHERE id = &#39;dark-mode&#39;;<br>COMMIT;</pre><p>Client A’s transaction is completed and lock is now released.</p><p><strong>Client B’s transaction resumes</strong></p><pre>UPDATE feature_flags<br>SET description = &#39;This feature is temporary disabled&#39;, version = version + 1<br>WHERE id = &#39;dark-mode&#39;;<br>COMMIT;</pre><p>Client B’s transaction is resumed and then applies its own update.</p><p>👉 <strong>Result</strong>:</p><ul><li><strong>No conflicts to detect</strong> → clients don’t get 409 errors, they just wait their turn.</li><li><strong>Guaranteed serial execution</strong> → no lost updates, because DB ensures strict order.</li></ul><h4>Closing Note</h4><p><strong>Assume no conflicts</strong> : Optimistic Locking</p><p><strong>Assume Conflicts</strong>: Pessimistic Locking</p><p>So there is no right or wrong when choosing a locking mechanism, different types of systems require different locking mechanism.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70503a52e054" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Tech Behind Flash Sales: How E-Commerce Handles Race Conditions]]></title>
            <link>https://medium.com/@kapoorjasdeep/its-the-big-billion-day-sale-on-flipkart-and-the-latest-smartphone-you-ve-been-eyeing-has-just-a9ad5cb30d08?source=rss-b0dc10b7d34f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9ad5cb30d08</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[race-condition]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <dc:creator><![CDATA[Jasdeep Singh Kapoor]]></dc:creator>
            <pubDate>Sat, 30 Aug 2025 11:45:33 GMT</pubDate>
            <atom:updated>2025-08-30T11:54:03.538Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nwHeREYvN3TIpxD98o6bhw.png" /><figcaption>Real life example of a race condition</figcaption></figure><p>It’s the Big Billion Day sale on <strong>Flipkart</strong>, and the latest smartphone you’ve been eyeing has just gone live limited to only <strong>10 units</strong>.</p><p>Thousands of shoppers rush to click <strong>“Buy Now”</strong> at the exact same moment. The website shows <strong>“10 units left,”</strong> but within milliseconds, multiple users try to grab the same product.</p><p>Without proper handling, this scenario leads to a <strong>race condition</strong>: multiple shoppers may end up “successfully” buying the same unit, payments go through, and your inventory shows negative stock. For an online store, this is <strong>nightmare material</strong>: angry customers, refund chaos, and potential financial losses.</p><p>This is what is called the <strong>Race condition</strong> in software engineering.</p><h4>What Is Happening Under the Hood?</h4><p>A race condition occurs when two or more operations try to <strong>read and modify the same data simultaneously</strong>, and the final result depends on the timing of these operations.</p><p>In our sale example:</p><ol><li>Shopper A reads stock = 1 for the smartphone.</li><li>Shopper B also reads stock = 1 at almost the same time.</li><li>Both try to reduce stock by 1.</li><li>If unchecked, the system allows <strong>both orders</strong>, even though there was only 1 unit left.</li></ol><h3>How E-Commerce Platforms Handle It</h3><h4>1. Database Locks (Prevent Simultaneous Updates)</h4><p><strong>PostgreSQL Example:</strong></p><pre>BEGIN;<br><br>-- Lock the product row until the transaction finishes<br>SELECT stock FROM products WHERE id = 101 FOR UPDATE;<br><br>-- Reduce stock<br>UPDATE products SET stock = stock - 1 WHERE id = 101;<br><br>COMMIT;</pre><p>This ensures only <strong>one transaction at a time</strong> can decrement stock.</p><p><strong>Real-World Analogy:</strong></p><ul><li><strong>Bank Teller Line:</strong> Imagine only one customer can interact with the teller at a time. If two people try to withdraw from the same account simultaneously, the teller processes one first, then the next. No one can skip the line or create negative balance because the system forces sequential access.</li></ul><h4>2. Atomic Updates</h4><p>In MongoDB, atomic operations prevent conflicts automatically:</p><pre>db.products.updateOne(<br>  { _id: 101, stock: { $gt: 0 } },<br>  { $inc: { stock: -1 } }<br>);</pre><p>Even if thousands of requests hit the database simultaneously, MongoDB ensures stock cannot go below 0.</p><p><strong>Real-World Analogy:</strong></p><ul><li><strong>Vending Machine:</strong> You select a soda, insert money, and the machine dispenses your drink. You <strong>cannot get your drink and have your money returned simultaneously</strong> or lose both. The operation happens atomically.</li></ul><h4>3. Optimistic Concurrency Control</h4><p>This approach is like saying, “I hope no one else changes this data while I’m working, but I’ll check before saving.”</p><pre>-- Read stock and version<br>SELECT stock, version FROM products WHERE id = 101;<br><br>-- Try updating only if version hasn&#39;t changed<br>UPDATE products<br>SET stock = stock - 1, version = version + 1<br>WHERE id = 101 AND version = 3;</pre><p>If another process updated the version first, your update fails, and you can <strong>retry safely</strong>.</p><p><strong>Real-World Analogy:</strong></p><ul><li><strong>Shared Document Editing:</strong> You and a colleague edit the same Google Doc paragraph. You assume no one else will change it while you type, but Google Docs checks before saving. If a conflict occurs, it alerts you to merge changes.</li></ul><h4>4. Queue-Based Serialization</h4><p>E-commerce platforms often use <strong>queues to serialize orders</strong> for high-demand products.</p><pre>const Queue = require(&#39;bull&#39;);<br>const orderQueue = new Queue(&#39;orders&#39;);<br><br>orderQueue.process(async (job) =&gt; {<br>  const product = await Product.findById(job.data.productId);<br>  if (product.stock &gt; 0) {<br>    product.stock -= 1;<br>    await product.save();<br>    return &#39;Order successful&#39;;<br>  }<br>  throw new Error(&#39;Out of stock&#39;);<br>});</pre><p>Here, even if 1,000 people click “Buy Now” at the same time, the queue ensures <strong>orders are processed one by one</strong>, preventing overselling.</p><p><strong>Real-World Analogy:</strong></p><ul><li><strong>Amusement Park Ride:</strong> Everyone waits in line for a roller coaster. Each person boards one at a time. Even if hundreds of people show up simultaneously, the ride can only take one group at a time, ensuring no one “skips” the ride.</li></ul><h3>Takeaway</h3><p>Race conditions are everywhere in high-traffic scenarios like the Big Billion Day sale. Without safeguards:</p><ul><li>Multiple shoppers could “buy” the same unit.</li><li>Inventory could go negative.</li><li>Refunds and complaints skyrocket.</li></ul><p>By using <strong>locks, atomic operations, optimistic concurrency, or queues</strong>, engineers ensure stock consistency, even under <strong>millions of concurrent requests</strong>.</p><p>Next time you snag a limited smartphone during a sale, thank the engineers who tamed the race condition behind the scenes!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9ad5cb30d08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fan-Out and Fan-In: The Unsung Heroes of System Design]]></title>
            <link>https://medium.com/@kapoorjasdeep/fan-out-and-fan-in-the-unsung-heroes-of-system-design-2f8a46933518?source=rss-b0dc10b7d34f------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f8a46933518</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Jasdeep Singh Kapoor]]></dc:creator>
            <pubDate>Tue, 26 Aug 2025 15:27:50 GMT</pubDate>
            <atom:updated>2025-08-26T15:27:50.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rDApeusxie9QAwimCeRJ-w.png" /><figcaption>Fan Out vs Fan In Architecture</figcaption></figure><p>When building scalable and reliable systems, two patterns often come up: <strong>Fan-out and Fan-in</strong>. These are not just buzzwords in distributed systems or microservices architecture — they represent fundamental ways to scale work, distribute tasks, and consolidate results.</p><p>Lets explore these concepts, compare them, and explore <strong>real-life scenarios</strong> for each of them.</p><h4>What is Fan-out?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y0NlZF3132V6I3hv1Bzfeg.png" /><figcaption>Fan out architecture</figcaption></figure><p><strong>Fan-out</strong> means <strong>one task produces many sub-tasks that run in parallel</strong>. The original request (or event) is distributed across multiple workers, processes, or services to handle the workload faster.</p><p>👉 Think of it like a <strong>manager delegating tasks</strong> to their entire team. Instead of doing everything alone, they divide and conquer.</p><h4>📌 Example 1: Image Processing System</h4><p>Suppose you’re building a system where users upload images and you need to:</p><ul><li>Generate thumbnails</li><li>Extract metadata</li><li>Apply filters</li><li>Run face detection</li></ul><p>Instead of one service doing all tasks sequentially, you <strong>fan-out</strong> the uploaded image into multiple jobs → each microservice handles a specific task in parallel.</p><p>This reduces processing time drastically.</p><h4>📌 Example 2: E-commerce Order Processing</h4><p>When a new order is placed:</p><ul><li>One service handles <strong>payment validation</strong></li><li>Another updates the <strong>inventory</strong></li><li>Another triggers <strong>shipment service</strong></li><li>Another sends a <strong>confirmation email</strong></li></ul><p>The <strong>order event fans out</strong> to multiple downstream services simultaneously.</p><h4>What is Fan-in?</h4><p><strong>Fan-in</strong> is the opposite: <strong>many inputs converge into a single result or workflow</strong>. It’s about collecting outputs from multiple sources and merging them into a final result.</p><p>👉 Think of it like a <strong>reporting manager collecting weekly reports</strong> from their team before making a summary report for upper management.</p><h4>📌 Example 1: Data Aggregation in Analytics</h4><p>Imagine you have:</p><ul><li>A service collecting <strong>web clickstream data</strong></li><li>A service tracking <strong>mobile app usage</strong></li><li>A service tracking <strong>in-store sales</strong></li></ul><p>All these streams <strong>fan-in</strong> into a central <strong>data lake or analytics system</strong> that produces a unified dashboard.</p><h4>📌 Example 2: Payment Aggregation</h4><p>A fintech app might integrate with multiple payment providers (Stripe, PayPal, Razorpay, etc.). Each provider sends back responses about payments, but your system needs to <strong>fan-in</strong> those responses to give a single consolidated transaction status to the user.</p><h3>Combined Pattern in Real Systems</h3><p>Most real-world systems use <strong>both</strong>.</p><h4>Example: Video Streaming Platform (like YouTube)</h4><p><strong>Fan-out</strong> → When a user uploads a video, the platform:</p><ul><li>Extracts audio</li><li>Generates thumbnails</li><li>Creates multiple quality encodings (1080p, 720p, 480p)</li><li>Runs content moderation</li></ul><p>All these happen in parallel.</p><p><strong>Fan-in</strong> → Once processing finishes, all results <strong>fan-in</strong> to mark the video as “Ready to Watch.”</p><p><strong>👉 Next time you design a system, ask yourself:</strong></p><ul><li><em>Do I need to break this task into smaller parts (fan-out)?</em></li><li><em>Or do I need to merge multiple results into one (fan-in)?</em></li></ul><p>Chances are, you’ll need a mix of both.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f8a46933518" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Large Datasets for Pagination in NoSQL Databases]]></title>
            <link>https://medium.com/@kapoorjasdeep/handling-large-datasets-for-pagination-in-nosql-databases-9046e0ba502e?source=rss-b0dc10b7d34f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9046e0ba502e</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[design-systems]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jasdeep Singh Kapoor]]></dc:creator>
            <pubDate>Sat, 23 Aug 2025 09:36:29 GMT</pubDate>
            <atom:updated>2025-08-23T09:36:29.168Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JylOyjxJw7MT_Gy4V-qlig.png" /><figcaption>Handling Large Datasets in NoSQL Databases</figcaption></figure><p>One of those issues that appears to be straightforward until your dataset grows into the millions. You’ll soon discover that traditional pagination techniques don’t scale well in NoSQL databases like <strong>MongoDB, Cassandra, or DynamoDB</strong> if you’re creating applications like chat history viewers, log dashboards, or e-commerce product catalogues.</p><p>We will first discuss the naïve approach, why it fails at scale, and how to properly paginate large datasets.</p><h3>A Real-World Example</h3><p>Imagine you’re building an <strong>e-commerce store</strong>.</p><ul><li>On the homepage, you want to show a paginated list of products.</li><li>It should be easy for users to browse through thousands of products.</li></ul><p>At first, you might reach for the simplest solution: <strong>offset + limit pagination</strong>.</p><h3>The Traditional Way: Offset + Limit</h3><pre>db.products.find().sort({ created_at: -1 }).skip(10000).limit(20);</pre><p>Sounds fine, right? Unfortunately, this is <strong>not scalable</strong>:</p><ul><li>skip(10000) makes the database scan through 10,000 documents, throw them away, and then fetch the next 20.</li><li>On datasets with millions of documents, the query becomes slower and slower.</li><li>If new products are inserted while the user is browsing, pagination results can become inconsistent (items might shift between pages).</li></ul><p>This approach works for small datasets or admin dashboards, but <strong>it fails for user-facing applications at scale</strong>.</p><h3>The Right Way: Cursor-Based Pagination</h3><p>Instead of skipping records, we can remember <strong>where the last page ended</strong> and fetch the next set from there.</p><h4>How it Works</h4><ul><li>Each page query keeps track of the <strong>last item’s unique value</strong> (usually _id, timestamp, or some indexed field).</li><li>Instead of saying <em>“skip the first 10,000 items”</em>, we say <em>“start after this specific ID/timestamp”.</em></li></ul><pre>// First page<br>db.products.find()<br>  .sort({ created_at: -1 })<br>  .limit(20);<br><br>// Next page (using last seen created_at)<br>db.products.find({ created_at: { $lt: lastSeenTimestamp } })<br>  .sort({ created_at: -1 })<br>  .limit(20);</pre><h4>Where do we get the “cursor”?</h4><p>Usually, the cursor is taken from a <strong>unique, ordered field</strong> in your dataset.</p><p>So basically,</p><ul><li>When the client asks for the first page → no cursor is provided.</li><li>When returning results → the server includes the <strong>last seen item’s key</strong> (cursor).</li><li>When requesting the next page → the client sends that cursor back to the server, and the server queries <em>items greater than that cursor</em>.</li></ul><p>Let’s see the same thing in action:</p><h4>Example (MongoDB)</h4><p><strong>Imagine you have a collection of blog posts:</strong></p><pre>{<br>  &quot;_id&quot;: ObjectId(&quot;66b2345...&quot;),<br>  &quot;title&quot;: &quot;Intro to NoSQL&quot;,<br>  &quot;createdAt&quot;: &quot;2025-08-01T10:00:00Z&quot;<br>}</pre><p><strong>First request (no cursor yet)</strong></p><pre>db.posts.find({})<br>  .sort({ createdAt: 1 })<br>  .limit(10)</pre><p>Server returns 10 posts <strong>plus</strong> a cursor (the last post’s createdAt or _id).</p><p><strong>Response:</strong></p><pre>{<br>  &quot;data&quot;: [ ... 10 posts ... ],<br>  &quot;nextCursor&quot;: &quot;2025-08-01T12:30:00Z&quot;<br>}</pre><p><strong>Next request (client sends cursor)</strong></p><pre>db.posts.find({ createdAt: { $gt: &quot;2025-08-01T12:30:00Z&quot; } })<br>  .sort({ createdAt: 1 })<br>  .limit(10)</pre><p>and so on…</p><h3>Why This is Better</h3><p>✅ Uses indexes efficiently — the DB doesn’t scan or discard rows.<br>✅ Consistent results — no “shifting items” if new data is added.<br>✅ Works great for <strong>infinite scroll</strong> or “next page” navigation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9046e0ba502e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>