<?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 Rishita Kotiyal on Medium]]></title>
        <description><![CDATA[Stories by Rishita Kotiyal on Medium]]></description>
        <link>https://medium.com/@rishitakotiyal?source=rss-e35687308fd7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*LXRPwdDosg1y91wk_cH1Gg.gif</url>
            <title>Stories by Rishita Kotiyal on Medium</title>
            <link>https://medium.com/@rishitakotiyal?source=rss-e35687308fd7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 20:09:29 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rishitakotiyal/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[What Actually Happens After You Click “Place Order” on an E-commerce Website?]]></title>
            <link>https://medium.com/@rishitakotiyal/what-actually-happens-after-you-click-place-order-on-an-e-commerce-website-47fa2af551c0?source=rss-e35687308fd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/47fa2af551c0</guid>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[event-driven-architecture]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[Rishita Kotiyal]]></dc:creator>
            <pubDate>Sun, 12 Apr 2026 15:46:43 GMT</pubDate>
            <atom:updated>2026-04-12T15:46:43.304Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zRdvq4e-7XOLD5vIqZE4IA.png" /><figcaption>One Click. Dozens of Backend Systems. Millions of Events.</figcaption></figure><p>You open an online store, find the product you want, and click <strong>“Place Order.”</strong></p><p>Within seconds:</p><ul><li>You receive an <strong>order confirmation email</strong></li><li>Your payment is processed</li><li>The product is reserved in inventory</li><li>A shipping request is generated</li></ul><p>To the customer, this feels instant and simple.</p><p>But behind that single click, <strong>multiple backend systems are coordinating together</strong> to process your order safely and reliably.</p><p>Modern e-commerce platforms such as <strong>Amazon</strong> or <strong>Shopify</strong> handle <strong>millions of orders every day</strong>, and they rely heavily on <strong>event-driven architecture</strong> powered by streaming systems like <strong>Apache Kafka</strong>.</p><p>In this article, we’ll explore what really happens behind the scenes when you place an order online.</p><h3>The Naive Way to Design an E-commerce Backend</h3><p>Imagine you are designing an order processing system.</p><p>A simple architecture might look like this:</p><p>Order Service → Payment Service → Inventory Service → Shipping Service → Notification Service</p><p>In this design:</p><ol><li>The Order Service creates the order</li><li>It calls the Payment Service</li><li>Then it calls the Inventory Service</li><li>Then the Shipping Service</li><li>Finally the Notification Service sends an email</li></ol><p>This approach is straightforward, but it has several problems.</p><h3>Tight Coupling</h3><p>Every service depends on another service being available.</p><p>If the <strong>inventory system is down</strong>, the order cannot be processed.</p><h3>Poor Scalability</h3><p>As the number of orders grows, each service becomes a bottleneck.</p><h3>Fragile Systems</h3><p>If one service fails, the entire pipeline breaks.</p><p>For small systems this works.<br>For large e-commerce platforms handling <strong>thousands of orders per minute</strong>, it quickly becomes unreliable.</p><h3>Enter Event-Driven Architecture</h3><p>Instead of services calling each other directly, modern systems use <strong>events</strong>.</p><p>An <strong>event</strong> is simply a message describing something that happened.</p><p>For example:</p><ul><li>OrderCreated</li><li>PaymentCompleted</li><li>InventoryUpdated</li><li>ShipmentCreated</li></ul><p>These events are published to a <strong>streaming platform</strong> like <strong>Apache Kafka</strong>, which acts as a central event pipeline.</p><p>Services then <strong>subscribe to the events they care about</strong>. This means services are no longer tightly connected. They simply react to events.</p><h3>What Happens When You Place an Order</h3><p>Let’s walk through a typical e-commerce order flow.</p><pre>                +--------------------+<br>                |      Frontend      |<br>                |   Web / Mobile     |<br>                +---------+----------+<br>                          |<br>                          v<br>                +--------------------+<br>                |     API Gateway    |<br>                +---------+----------+<br>                          |<br>                          v<br>                +--------------------+<br>                |    Order Service   |<br>                |   Create Order     |<br>                +---------+----------+<br>                          |<br>                          |  order-created<br>                          v<br>                +--------------------+<br>                |    Apache Kafka    |<br>                |    Event Stream    |<br>                +----+----+----+-----+<br>                     |    |    |<br>        -------------     |     -------------<br>       |                  |                  |<br>       v                  v                  v<br><br>+-------------+   +-------------+   +-------------+<br>|   Payment   |   |  Inventory  |   | Notification|<br>|   Service   |   |   Service   |   |   Service   |<br>+-------------+   +-------------+   +-------------+<br>       |<br>       v<br>+-------------+<br>|  Shipping   |<br>|   Service   |<br>+-------------+</pre><h3>Step 1 — Customer Places an Order</h3><p>A user clicks <strong>Place Order</strong>. The Order Service creates the order and publishes an event order-created.This event is sent to Kafka. Now other services can react to it independently.</p><h3>Step 2 — Payment Processing</h3><p>The Payment Service listens for order-created events. When it receives the event, it attempts to charge the customer’s payment method. If the payment succeeds, it publishes another event:payment-success</p><p>If payment fails, it publishes:payment-failed.This allows other services to react accordingly.</p><h3>Step 3 — Inventory Reservation</h3><p>The Inventory Service listens for payment-success.</p><p>When it receives this event:</p><ul><li>It reduces the product stock</li><li>It reserves the item for that order</li></ul><p>It then publishes another event:inventory-updated</p><h3>Step 4 — Shipping Preparation</h3><p>The Shipping Service listens for inventory-updated.</p><p>Once it receives the event:</p><ul><li>A shipping request is created</li><li>A warehouse picks the product</li><li>Packaging and labeling begins</li></ul><p>The system then publishes:shipment-created</p><h3>Step 5 — Customer Notification</h3><p>Finally, the Notification Service listens for events such as:</p><ul><li>order-created</li><li>shipment-created</li><li>order-delivered</li></ul><p>Whenever one of these events occurs, the service sends the customer updates via:</p><ul><li>email</li><li>SMS</li><li>push notification</li></ul><p>From the user’s perspective, everything appears seamless. But behind the scenes, multiple services are reacting to events asynchronously.</p><h3>How Kafka Fits Into This System</h3><p>A streaming platform like <strong>Apache Kafka</strong> acts as the <strong>central event hub</strong>.</p><p>Instead of services calling each other, they publish and consume events through Kafka.</p><p>Typical topics in an e-commerce system might look like this:</p><ul><li>order-created</li><li>payment-processed</li><li>inventory-updated</li><li>shipment-created</li><li>order-delivered</li></ul><p>Each service subscribes only to the events it needs.</p><p>For example:</p><ul><li>Payment Service listens to order-created</li><li>Inventory Service listens to payment-success</li><li>Shipping Service listens to inventory-updated</li><li>Notification Service listens to multiple events</li></ul><p>This creates a loosely coupled architecture.</p><pre>User clicks &quot;Place Order&quot;<br>        |<br>        v<br>+-------------------+<br>|   Order Service   |<br>+-------------------+<br>        |<br>        | order-created<br>        v<br>+-------------------+<br>|   Kafka Topic     |<br>|   order-created   |<br>+-------------------+<br>        |<br>        +---------------------+<br>        |                     |<br>        v                     v<br>+---------------+     +---------------+<br>| Payment       |     | Notification  |<br>| Service       |     | Service       |<br>+---------------+     +---------------+<br>        |<br>        | payment-success<br>        v<br>+---------------+<br>| Inventory     |<br>| Service       |<br>+---------------+<br>        |<br>        | inventory-updated<br>        v<br>+---------------+<br>| Shipping      |<br>| Service       |<br>+---------------+</pre><h3>Why This Architecture Scales</h3><p>Large e-commerce systems must process <strong>massive volumes of events</strong>. Event-driven architecture provides several advantages.</p><h3>Scalability</h3><p>-&gt; Kafka topics can be split into <strong>partitions</strong>, allowing multiple consumers to process events in parallel.</p><p>-&gt; This enables systems to scale horizontally as traffic grows.</p><h3>Reliability</h3><p>-&gt; Kafka stores events durably until they are consumed.</p><p>-&gt; If a service crashes, it can restart and continue processing events from where it left off.</p><h3>Loose Coupling</h3><p>-&gt; Services don’t need to know about each other.</p><p>-&gt; They simply react to events.</p><p>-&gt; This makes the system easier to maintain and evolve.</p><h3>Flexibility</h3><p>-&gt; New services can be added without modifying existing ones.</p><p>-&gt; For example, an <strong>Analytics Service</strong> can subscribe to order events to generate business insights.</p><h3>A Simplified Architecture Diagram</h3><p>A typical architecture might look like this:</p><pre>                 +----------------------+<br>                 |      Frontend        |<br>                 |   (Web / Mobile)     |<br>                 +----------+-----------+<br>                            |<br>                            v<br>                 +----------------------+<br>                 |     API Gateway      |<br>                 +----------+-----------+<br>                            |<br>                            v<br>                 +----------------------+<br>                 |     Order Service    |<br>                 +----------+-----------+<br>                            |<br>                            v<br>                 +----------------------+<br>                 |   Kafka Event Stream |<br>                 +----------+-----------+<br>                            |<br>        -------------------------------------------------<br>        |         |           |           |             |<br>        v         v           v           v             v<br><br>+-------------+ +-------------+ +-------------+ +-------------+ +-------------+<br>|  Payment    | | Inventory   | |  Shipping   | | Notification| |  Analytics  |<br>|  Service    | |  Service    | |  Service    | |  Service    | |  Service    |<br>+-------------+ +-------------+ +-------------+ +-------------+ +-------------+</pre><p>Each service works independently but communicates through events.</p><h3>Final Thoughts</h3><p>That single <strong>“Place Order”</strong> click triggers a complex chain of events across multiple systems.</p><p>Modern e-commerce platforms rely on <strong>event-driven architecture</strong> and streaming platforms like <strong>Apache Kafka</strong> to make this possible.</p><p>By decoupling services and processing events asynchronously, companies can build systems that are:</p><ul><li>scalable</li><li>resilient</li><li>flexible</li></ul><p>The next time you place an order online, remember that behind the scenes, dozens of services may be working together to process it — all coordinated through events.</p><p>And that’s the real magic powering modern e-commerce platforms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47fa2af551c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding DNS, Load Balancers, and Anycast — From Scratch with a Real-World Scenario]]></title>
            <link>https://medium.com/@rishitakotiyal/understanding-dns-load-balancers-and-anycast-from-scratch-with-a-real-world-scenario-39835f342e26?source=rss-e35687308fd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/39835f342e26</guid>
            <dc:creator><![CDATA[Rishita Kotiyal]]></dc:creator>
            <pubDate>Sun, 29 Mar 2026 23:31:20 GMT</pubDate>
            <atom:updated>2026-04-13T23:34:48.999Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9SfPtGwDrgei9XuknpA6pg.png" /><figcaption>DNS, load balancers and Anycast explained</figcaption></figure><p>When you open a website like myapp.com, a lot more happens behind the scenes than you might imagine. This article breaks down three fundamental building blocks of modern internet architecture:</p><ul><li>DNS (Domain Name System)</li><li>Load Balancers</li><li>Anycast</li></ul><p>We’ll go step by step and then tie everything together with a real-world scenario so even a beginner can clearly understand how these pieces fit.</p><h3>🌍 1. DNS — The Internet’s Phonebook</h3><h3>What is DNS?</h3><p>DNS (Domain Name System) translates human-friendly domain names into machine-friendly IP addresses.</p><p>Example:</p><pre>myapp.com → 100.10.10.10</pre><h3>Why do we need it?</h3><ul><li>Humans remember names (myapp.com)</li><li>Computers communicate using IP addresses</li></ul><h3>What happens when you open a website?</h3><ol><li>You type myapp.com in your browser</li><li>Your system asks a DNS server:</li></ol><ul><li>“What is the IP address of this domain?”</li></ul><p>3. DNS responds with an IP:</p><pre>100.10.10.10</pre><p>Now your request is ready to go to that IP.</p><h3>Limitation of DNS</h3><p>DNS only gives you an address. It does NOT:</p><ul><li>Decide the closest server</li><li>Handle failures instantly</li><li>Distribute traffic intelligently</li></ul><p>That’s where the next components come in.</p><h3>⚖️ 2. Load Balancer — The Traffic Manager</h3><h3>What is a Load Balancer?</h3><p>A Load Balancer distributes incoming traffic across multiple servers.</p><h3>Why is it needed?</h3><p>Imagine:</p><ul><li>10,000 users hitting your server at once</li></ul><p>Without a load balancer:</p><ul><li>One server gets overloaded → crashes</li></ul><p>With a load balancer:</p><ul><li>Traffic is distributed → system stays stable</li></ul><h3>Basic flow</h3><pre>Client → Load Balancer → Multiple Servers</pre><p>Example:</p><ul><li>Request 1 → Server A</li><li>Request 2 → Server B</li><li>Request 3 → Server C</li></ul><h3>Problem: Single Point of Failure</h3><p>If you only have ONE load balancer:</p><pre>Client → Load Balancer (down) → ❌ System down</pre><p>Even if your servers are healthy, users cannot reach them.</p><h3>🌐 3. Anycast — The Global Routing Layer</h3><p>Now we solve a bigger problem:</p><blockquote><em>How do we make the entry point itself reliable and fast globally?</em></blockquote><h3>What is Anycast?</h3><p>Anycast is a networking technique where:</p><ul><li>Multiple servers share the SAME IP address</li><li>The internet automatically routes users to the <strong>nearest or best server</strong></li></ul><h3>Key idea</h3><p>Instead of:</p><pre>One IP → One server</pre><p>We have:</p><pre>One IP → Multiple servers (globally distributed)</pre><h3>🧠 Putting It All Together — A Real Scenario</h3><p>Let’s walk through a complete example.</p><h3>Scenario: You open myapp.com from Canada</h3><h3>Step 1: DNS Resolution</h3><p>You type:</p><pre>myapp.com</pre><p>DNS responds:</p><pre>100.10.10.10</pre><h3>Step 2: Anycast Routing</h3><p>Now here’s the important part:</p><p>That IP (100.10.10.10) exists in multiple locations:</p><ul><li>Toronto</li><li>New York</li><li>London</li></ul><p>Your request goes into the internet, and routers decide:</p><blockquote><em>“Which location is closest to this user?”</em></blockquote><p>Since you are in Canada:</p><pre>→ Routed to Toronto</pre><h3>Step 3: Regional Load Balancer</h3><p>Now you hit the Toronto Load Balancer.</p><p>Inside Toronto:</p><pre>Load Balancer<br>   ↓<br>API Server 1<br>API Server 2<br>API Server 3</pre><p>The load balancer distributes traffic:</p><ul><li>Your request → API Server 2</li></ul><h3>Step 4: Backend Processing</h3><p>The server processes your request:</p><ul><li>Fetches data</li><li>Sends response back</li></ul><h3>Step 5: Response</h3><p>Response flows back:</p><pre>Server → Load Balancer → You</pre><h3>💥 Failure Scenario (Most Important Part)</h3><p>Now let’s break something.</p><h3>Toronto Load Balancer goes DOWN</h3><p>What happens when you open myapp.com again?</p><h4>Step 1: DNS (unchanged)</h4><p>Still returns:</p><pre>100.10.10.10</pre><h4>Step 2: Anycast reacts</h4><p>Toronto is no longer available.</p><p>Routers automatically choose the next best path:</p><pre>→ New York Load Balancer</pre><h4>Step 3: System continues working</h4><pre>New York LB → Servers → Response</pre><h3>What you experience</h3><ul><li>Maybe slightly slower</li><li>But system still works</li></ul><p>No manual failover. No downtime.</p><h3>🔍 Key Insight — How Anycast Handles Failure</h3><p>Anycast does NOT “switch” traffic actively.</p><p>Instead:</p><ul><li>Each location advertises the same IP</li><li>If one location fails, it stops advertising</li><li>Internet routing automatically avoids it</li></ul><h3>🧩 Final Architecture (Simplified)</h3><pre>User<br>  ↓<br>DNS (returns IP)<br>  ↓<br>Anycast (routes to nearest region)<br>  ↓<br>Load Balancer (distributes locally)<br>  ↓<br>Servers / API / Services</pre><h3>🧠 Simple Analogy</h3><p>Think of ordering food:</p><ul><li>DNS → Finds restaurant phone number</li><li>Anycast → Connects you to nearest branch</li><li>Load Balancer → Manager assigns your order to a chef</li></ul><h3>🎯 Final Takeaways</h3><ul><li><strong>DNS</strong> gives you the entry point (IP address)</li><li><strong>Anycast</strong> ensures you reach the nearest and healthiest location</li><li><strong>Load Balancer</strong> distributes traffic within that location</li></ul><p>Together, they provide:</p><ul><li>High availability</li><li>Low latency</li><li>Fault tolerance</li></ul><h3>🚀 Why This Matters</h3><p>This combination is used in almost every large-scale system today:</p><ul><li>Global apps</li><li>Streaming platforms</li><li>E-commerce systems</li></ul><p>Understanding this flow gives you a strong foundation in system design.</p><p>If you understand this, you’ve already crossed the biggest mental hurdle in backend architecture.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=39835f342e26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Killing the N+1 Query Monster in Spring Data JPA: How a Single Fetch Join Saved 298 Queries]]></title>
            <link>https://medium.com/@rishitakotiyal/killing-the-n-1-query-monster-in-spring-data-jpa-how-a-single-fetch-join-saved-250-queries-1e83b75df320?source=rss-e35687308fd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1e83b75df320</guid>
            <dc:creator><![CDATA[Rishita Kotiyal]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 16:42:19 GMT</pubDate>
            <atom:updated>2025-08-17T23:38:11.448Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3jIsia9IsUBW4HeU-piKA.png" /><figcaption>Hibernate N+1</figcaption></figure><p><em>“5:25 AM. Load test running.</em><br><em>CPU is fine. Memory is fine.</em><br><em>Database? Crying in SQL.</em><br><em>298 queries… for one API call.”</em></p><p>That was the scene one early morning when our performance test dashboard lit up. The culprit?<br>An <strong>N+1 query problem</strong> hiding in plain sight — inside a <strong>Spring Data JPA Specification</strong>.</p><h3>1. The Scene: N+1 in the Wild</h3><p>During a high-volume load test, one endpoint — let’s call it:</p><pre>GET /orders/notifications?status=CREATED</pre><p>was suddenly making <strong>298 database queries</strong> for a single request.</p><p>In our profiler trace (Dynatrace), it looked something like this:</p><pre>SELECT * FROM order_notification WHERE status = &#39;CREATED&#39;;  -- 1 query <br>SELECT * FROM order_item WHERE notification_id = 1;         -- +1 <br>SELECT * FROM order_item WHERE notification_id = 2;         -- +1<br>...<br>SELECT * FROM order_item WHERE notification_id = 298;       -- +1</pre><p>Total: <strong>1 (parent) + 297 (children) = 298 queries</strong>.<br>💀 Classic N+1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SLBh-NJbFbaVKCGgGTfjEA.png" /><figcaption>Trace for n+1</figcaption></figure><h3>2. What is the N+1 Query Problem?</h3><p>The N+1 problem happens when:</p><ul><li>You query a list of entities (N rows)</li><li>For each entity, Hibernate lazily loads its children in separate queries</li></ul><p>Instead of this:</p><pre>sqlCopyEditSELECT * FROM order_notification;<br>SELECT * FROM order_item WHERE notification_id = 1;<br>SELECT * FROM order_item WHERE notification_id = 2;<br>...</pre><p>We want <strong>this</strong>:</p><pre>SELECT n.*, i.* <br>FROM order_notification n<br>LEFT JOIN order_item i ON n.id = i.notification_id;</pre><p>That’s <strong>1 query total</strong>, not N+1.</p><h3>3. The Hidden Culprit: Specifications Without Fetch Joins</h3><p>Our repository used a dynamic Specification:</p><pre>Specification&lt;OrderNotification&gt; spec = Specification<br>    .where(mapSpec(params.getStatus(), OrderNotificationSpecs::byStatus))<br>    .and(mapSpec(params.getCreatedAfter(), OrderNotificationSpecs::createdAfter));</pre><p>This was clean and reusable.<br>But <strong>Specifications do not automatically join-fetch</strong> related entities — so every lazy-loaded association was triggering its own SQL query.</p><h3>4. The Fix: Populate Fetch Joins in the Specification</h3><p>Here’s how we solved it:</p><pre>public static Specification&lt;OrderNotification&gt; populateJoinFetches() {<br>    return (root, query, cb) -&gt; {<br>        // Avoid fetch joins in count queriesif (query.getResultType() != Long.class) {<br>            root.fetch(&quot;orderItems&quot;, JoinType.LEFT);<br>            root.fetch(&quot;customer&quot;, JoinType.LEFT);<br>        }<br>        return null;<br>    };<br>}</pre><p>And in our builder:</p><pre>Specification&lt;OrderNotification&gt; spec = OrderNotificationSpecs.populateJoinFetches()<br>    .and(mapSpec(params.getStatus(), OrderNotificationSpecs::byStatus))<br>    .and(mapSpec(params.getCreatedAfter(), OrderNotificationSpecs::createdAfter));</pre><h3>Why query.getResultType() != Long.class is Crucial</h3><p>When Spring Data JPA paginates, it runs <strong>two queries</strong>:</p><ul><li>The main fetch query</li><li>A SELECT COUNT(...) query for total results</li></ul><p>If you fetch join in a count query, you risk:</p><ul><li>org.hibernate.QueryException: query specified join fetching, but the owner of the fetched association was not present in the select list</li><li>Wrong counts due to Cartesian product inflation</li></ul><p>So we <strong>skip fetch joins</strong> for count queries.</p><h3>5. Before vs After: Proof in the Logs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x-p051c_owrwzy31UkJcRQ.png" /><figcaption>Fetch Join Performance</figcaption></figure><p><strong>Before (N+1 problem):</strong></p><pre>[SQL] SELECT * FROM order_notification WHERE status=&#39;CREATED&#39;;  -- 1 query<br>[SQL] SELECT * FROM order_item WHERE notification_id=?;         -- 297 queries<br>Total queries: 298<br>Execution time: 1.28s</pre><p><strong>After (fetch join):</strong></p><pre>[SQL] SELECT n.*, i.*, c.* <br>FROM order_notification n<br>LEFT JOIN order_item i ON n.id = i.notification_id<br>LEFT JOIN customer c ON n.customer_id = c.id<br>WHERE n.status=&#39;CREATED&#39;;<br>Total queries: 1<br>Execution time: 0.12s</pre><p><strong>Result:</strong> 🚀 <strong>From 298 queries → 1 query.</strong><br>Load test latency dropped by <strong>90%</strong> for this endpoint.</p><h3>6. Why Fetch Joins? And What Are the Alternatives</h3><p>When tackling N+1 queries in Spring Data JPA, we had several options:</p><blockquote><strong><em>Option 1: Fetch Joins (What We Chose)</em></strong></blockquote><ul><li><strong>Why we chose it:</strong><br>Fetch joins load the parent entity <strong>and its associations in a single query</strong>, drastically reducing database round-trips.<br>They integrate cleanly with <strong>Specifications</strong>, which was essential because we already had dynamic filtering logic in place.</li><li><strong>Pros:<br></strong>Minimal changes to existing repository code<br>Dramatic reduction in queries (1 instead of N+1)<br>Works well for eager loading of multiple associations</li><li><strong>Cons:<br></strong>Can fetch more data than needed if not carefully scoped<br>Needs special handling for count queries in paginated requests</li></ul><blockquote><strong>Option 2: </strong><strong>@EntityGraph</strong></blockquote><ul><li><strong>How it works:</strong><br>Annotate repository methods with @EntityGraph to define which associations should be eagerly loaded.</li><li><strong>Pros:<br></strong>Declarative and reusable across queries<br>Avoids manual join fetch in Specifications</li><li><strong>Cons:<br></strong>Harder to dynamically apply filters<br>Less flexible for highly dynamic query scenarios</li></ul><blockquote><strong>Option 3: Batch Fetching / Hibernate </strong><strong>@BatchSize</strong></blockquote><ul><li><strong>How it works:</strong><br>Load lazy associations in <strong>batches</strong> rather than one-by-one. Hibernate combines multiple selects into one batch query.</li><li><strong>Pros:<br></strong>Reduces N+1 without changing queries drastically<br>Works automatically for multiple associations</li><li><strong>Cons:<br></strong>Still more queries than a single fetch join<br>Harder to reason about exact query execution</li></ul><blockquote><strong>Why Fetch Joins Won Out</strong></blockquote><p>We went with fetch joins because:</p><ul><li>We needed <strong>full control</strong> over which associations to load dynamically.</li><li>We wanted <strong>maximum query reduction</strong> during high-volume load tests.</li><li>It fit neatly into our <strong>Specification-based filtering</strong>, without adding extra repository methods.</li></ul><h3>7. Lessons Learned</h3><ul><li><strong>Specifications won’t optimize your fetch strategy</strong><br>They combine predicates, but fetching is your job.</li><li><strong>Always skip fetch joins in count queries</strong><br>Use query.getResultType() to guard against it.</li><li><strong>N+1 is a silent killer</strong><br>You might never notice it in dev with small data.<br>In production load? It can destroy performance.</li><li><strong>Profile before you optimize</strong><br>A single fetch join can make a massive difference — but fetching too much can also backfire.</li></ul><h3>8. Final Takeaway</h3><p>The N+1 problem isn’t just a “junior dev mistake.”<br>It can hide in <strong>beautiful, reusable Specification code</strong> until the day you throw production-level traffic at it.</p><p><strong>One strategic fetch join saved us from 290+ redundant queries.</strong><br>Your codebase might have similar ticking time bombs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1e83b75df320" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching in Microservices: The Hidden Superpower Behind Fast, Scalable APIs]]></title>
            <link>https://medium.com/@rishitakotiyal/caching-in-microservices-the-hidden-superpower-behind-fast-scalable-apis-9b81fe9fc9ab?source=rss-e35687308fd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b81fe9fc9ab</guid>
            <dc:creator><![CDATA[Rishita Kotiyal]]></dc:creator>
            <pubDate>Thu, 31 Jul 2025 15:05:00 GMT</pubDate>
            <atom:updated>2025-08-01T10:58:15.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kweAChrF5o0hO83KK2fQHQ.png" /></figure><h3>🔥 Introduction</h3><p>If you’ve ever marveled at how Amazon loads product pages almost instantly — even during Black Friday — or how Netflix personalizes your feed without a hitch, chances are you’re witnessing a silent hero at work: <strong>caching</strong>.</p><p>Caching is often overlooked in system design interviews and backend discussions, yet it’s one of the <strong>most powerful techniques</strong> for reducing latency, cutting costs, and scaling APIs to handle millions of users.</p><p>In this article, we’ll break down <strong>what caching really is</strong>, why <strong>every microservice should use it</strong>, and how <strong>top tech companies leverage it</strong> to deliver blazing-fast performance.</p><h3>🚀 What Is Caching, Really?</h3><p>Caching is the act of <strong>temporarily storing data</strong> so future requests for that data can be served <strong>faster</strong>.</p><p>Instead of hitting a database or a remote API every time, a system <strong>remembers</strong> the response for a certain period. This improves performance and reduces unnecessary load.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d4Lcd-Klev2bIr-Fci1lAQ.jpeg" /></figure><h3>🏗️ Where Caching Happens in Microservices</h3><p>In microservice architectures, caching can be implemented at <strong>multiple layers</strong>:</p><pre>| Layer               | Purpose                 | Example Tool         |<br>| ------------------- | ----------------------- | -------------------- |<br>| In-memory (per app) | Fastest local access    | Caffeine, Guava      |<br>| Distributed cache   | Shared across instances | Redis, Memcached     |<br>| CDN/Edge caching    | Closest to the end-user | Cloudflare, Akamai   |<br>| Browser cache       | Client-side storage     | Cache API, IndexedDB |</pre><p>Each microservice typically has <strong>its own cache</strong>, because services are <strong>autonomous</strong>, and coupling cache introduces tight dependencies and invalidation nightmares.</p><h3>💡 Why Every Microservice Needs Its Own Cache</h3><h4>1. Reduced Latency</h4><p>Caching moves data closer to the service or user, reducing fetch time from milliseconds to microseconds.</p><h4>2. Lower Infrastructure Cost</h4><p>Less load on databases and APIs means fewer read replicas, smaller clusters, and better use of resources.</p><h4>3. Resilience</h4><p>In case the database is slow or down, the system can still serve from cache.</p><h4>4. Scalability</h4><p>Cache enables horizontal scaling without proportional increase in DB queries.</p><h3>⚙️ How It Works: A Real-World Analogy</h3><p>Think of a bookstore:</p><ul><li>The <strong>warehouse</strong> is your database</li><li>The <strong>shelf</strong> is your cache</li><li>A popular book gets pulled from the warehouse once and placed on the shelf</li><li>The next 100 people get it instantly from the shelf</li></ul><p>This is how product data, user preferences, and search results behave in high-traffic systems.</p><h3>🧪 Common Caching Strategies</h3><pre>| Strategy               | Description                                 |<br>| ---------------------- | ------------------------------------------- |<br>| **Read-through**       | First fetch from DB, then cache result      |<br>| **Write-through**      | Writes go to cache and DB simultaneously    |<br>| **Cache-aside (Lazy)** | App controls when data is loaded into cache |<br>| **TTL-based Expiry**   | Data auto-expires after set time            |<br>| **Eviction Policies**  | LRU (Least Recently Used), LFU, FIFO        |</pre><p>In most microservices, <strong>cache-aside with TTL</strong> is the go-to model — fetch from DB only if the cache doesn’t have the data.</p><h3>🤯 Common Misunderstandings</h3><blockquote><strong><em>“Caching only helps if I request the same product again.”</em></strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q3WfMuAF40Xzg8QFJXeRrA.jpeg" /></figure><p>Not true. <strong>Popular data patterns</strong> across users — like trending products, top categories, or homepage items — benefit massively from caching.</p><p>Even if every user makes a different request, there’s a high chance of <strong>data reuse across user sessions</strong>, which makes caching worthwhile.</p><h3>🔄 Dealing with Stale Data</h3><p>Caching always walks the line between <strong>performance and freshness</strong>.</p><p>Techniques used to keep data relevant:</p><ul><li><strong>Short TTLs</strong> (e.g., 2–10 minutes for inventory)</li><li><strong>Manual eviction</strong> on update</li><li><strong>Message-driven invalidation</strong> via Kafka/RabbitMQ</li><li><strong>Soft expiry with background refresh</strong></li></ul><p>Systems like Amazon or Flipkart often combine multiple strategies to <strong>ensure fast, fresh, and consistent data</strong>.</p><h3>🔍 Real-World Use Cases</h3><pre>| Company      | Use of Caching                              |<br>| ------------ | ------------------------------------------- |<br>| **Amazon**   | Product metadata, pricing, recommendations  |<br>| **Netflix**  | User preferences, watch history, UI layouts |<br>| **Facebook** | Profile data, news feed, comment threads    |<br>| **Uber**     | ETA calculations, route suggestions         |</pre><p>These companies rely on <strong>multi-layered caching</strong> for global speed and reliability — often combining Redis, Memcached, CDN, and browser cache.</p><h3>🛠️ Tools of the Trade</h3><pre>| Tool                | Best For                                 |<br>| ------------------- | ---------------------------------------- |<br>| **Redis**           | Fast, scalable distributed caching       |<br>| **Caffeine**        | Java in-memory caching with LRU          |<br>| **Spring Cache**    | Annotation-based caching for Spring Boot |<br>| **CDNs**            | Edge caching for assets and APIs         |<br>| **Service Workers** | Caching on the browser/client side       |</pre><h3>📊 Cache Effectiveness: What to Monitor</h3><ul><li><strong>Hit ratio</strong>: Percentage of requests served from cache</li><li><strong>Evictions</strong>: Items removed due to space or TTL</li><li><strong>Latency</strong>: Cache vs DB response times</li><li><strong>Staleness</strong>: How outdated the cache data is</li></ul><h3>🧠 Key Takeaways</h3><ol><li><strong>Caching is not optional</strong> for scalable systems.</li><li><strong>Each microservice should manage its own cache</strong>, tailored to its domain.</li><li>Avoid caching null results — they can cause stale misses.</li><li>A good caching strategy balances <strong>speed and freshness</strong>.</li><li>Monitoring and tuning are just as important as implementation.</li></ol><h3>📌 Final Thoughts</h3><p>Caching is invisible to users, yet critical to their experience. It’s the difference between a sluggish app and a world-class product.</p><p>In microservices, caching isn’t just about performance — it’s about <strong>resilience, cost-efficiency, and intelligent architecture</strong>. Whether you’re building product pages, APIs, or personalized dashboards, mastering caching gives you a <strong>superpower</strong> in backend design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b81fe9fc9ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Remote Procedure Calls (RPC): A Step-by-Step Guide]]></title>
            <link>https://medium.com/@rishitakotiyal/understanding-remote-procedure-calls-rpc-a-step-by-step-guide-d274e814ce87?source=rss-e35687308fd7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d274e814ce87</guid>
            <dc:creator><![CDATA[Rishita Kotiyal]]></dc:creator>
            <pubDate>Tue, 01 Apr 2025 23:27:06 GMT</pubDate>
            <atom:updated>2025-04-02T00:06:31.185Z</atom:updated>
            <content:encoded><![CDATA[<h3>What is RPC?</h3><p>Remote Procedure Call (<strong>RPC</strong>) is a communication protocol that allows one service (or application) to <strong>call a function on another service</strong> running on a different machine, as if it were a local function.</p><p>In simple words, <strong>RPC allows different parts of a distributed system to communicate seamlessly</strong>.</p><h3>Why Do We Need RPC?</h3><p>Imagine you are building an <strong>e-commerce platform</strong> with multiple microservices:</p><ul><li><strong>Order Service</strong> 🛒 (Handles orders)</li><li><strong>Payment Service</strong> 💳 (Processes payments)</li><li><strong>User Service</strong> 👤 (Manages users)</li><li><strong>Inventory Service</strong> 📦 (Tracks product stock)</li></ul><blockquote>Each of these services is <strong>independent</strong> and may run on different servers. But they still need to communicate with each other.</blockquote><p>For example, when a user places an order:</p><ol><li><strong>Order Service</strong> needs to call <strong>Payment Service</strong> to charge the customer.</li><li><strong>Payment Service</strong> needs to call <strong>User Service</strong> to verify the user’s balance.</li><li><strong>Order Service</strong> needs to call <strong>Inventory Service</strong> to check product availability.</li></ol><p>Since these services are running <strong>in different locations</strong>, they <strong>cannot call functions directly</strong> like in a normal program. Instead, they use <strong>RPC</strong> to communicate over a network.</p><h3>How Does RPC Work? (Step-by-Step)</h3><p>Let’s break it down with an example where an <strong>Order Service</strong> calls a <strong>Payment Service</strong> using RPC.</p><h4>Step 1: The Order Service Makes a Request</h4><ul><li>The <strong>Order Service</strong> wants to charge a customer.</li><li>It calls a function: processPayment(userId, amount), but this function exists on a <strong>different service</strong> (Payment Service).</li></ul><h4>Step 2: RPC Encodes &amp; Sends the Request</h4><p>The <strong>RPC framework</strong> (like gRPC, Thrift, or JSON-RPC) converts the function call into a <strong>network request</strong>, which contains:</p><ul><li>The function name (processPayment)</li><li>The parameters (userId, amount)</li><li>Metadata (authentication, request ID, etc.)</li></ul><p>This request is sent over the network.</p><h4>Step 3: Payment Service Receives &amp; Processes the Request</h4><ul><li>The <strong>Payment Service</strong> <strong>decodes</strong> the request.</li><li>It runs the function processPayment(userId, amount) on its own server.</li><li>It verifies the user’s balance and processes the payment</li></ul><h4>Step 4: Payment Service Sends Back a Response</h4><ul><li>Once payment is processed, the <strong>Payment Service</strong> sends a response:</li></ul><pre>{ &quot;status&quot;: &quot;success&quot;, &quot;transactionId&quot;: &quot;TXN12345&quot; }</pre><ul><li>The response is <strong>encoded</strong> and sent over the network.</li></ul><h4>Step 5: Order Service Receives the Response</h4><ul><li>The <strong>Order Service</strong> <strong>decodes</strong> the response.</li><li>It continues processing the order.</li><li>If the payment is successful, it confirms the order.</li></ul><h3>Real Example: Implementing RPC Using gRPC</h3><blockquote>Now, let’s see <strong>how this works in code</strong> using gRPC (a popular RPC framework).</blockquote><h4>1️⃣ Define the RPC Service (Proto File)</h4><p>First, we define a <strong>protocol buffer (proto) file</strong> to specify the remote function.</p><pre>syntax = &quot;proto3&quot;;<br>service PaymentService {<br>  rpc ProcessPayment (PaymentRequest) returns (PaymentResponse);<br>}<br>message PaymentRequest {<br>  string userId = 1;<br>  double amount = 2;<br>}<br>message PaymentResponse {<br>  string status = 1;<br>  string transactionId = 2;<br>}</pre><p>This defines an RPC function: ProcessPayment(userId, amount), which returns a PaymentResponse.</p><h4>2️⃣ Implement the Payment Service (Server)</h4><p>The <strong>Payment Service</strong> runs on a remote server and waits for RPC requests.</p><pre>import io.grpc.Server;<br>import io.grpc.ServerBuilder;<br>import io.grpc.stub.StreamObserver;<br>import java.io.IOException;<br><br>public class PaymentService extends PaymentServiceGrpc.PaymentServiceImplBase {<br>    @Override<br>    public void processPayment(PaymentRequest request, StreamObserver&lt;PaymentResponse&gt; responseObserver) {<br>        System.out.println(&quot;Processing payment for user: &quot; + request.getUserId() + &quot;, Amount: &quot; + request.getAmount());<br>        PaymentResponse response = PaymentResponse.newBuilder()<br>                .setStatus(&quot;success&quot;)<br>                .setTransactionId(&quot;TXN&quot; + request.getUserId())<br>                .build();<br>        responseObserver.onNext(response);<br>        responseObserver.onCompleted();<br>    }<br><br>    public static void main(String[] args) throws IOException, InterruptedException {<br>        Server server = ServerBuilder.forPort(50051)<br>                .addService(new PaymentService())<br>                .build()<br>                .start();<br>        System.out.println(&quot;Payment Service started on port 50051...&quot;);<br>        server.awaitTermination();<br>    }<br>}</pre><p>✅ This <strong>Payment Service</strong> listens on <strong>port 50051</strong> and handles RPC calls.</p><h4>3️⃣ Implement the Order Service (Client)</h4><p>The <strong>Order Service</strong> calls the <strong>remote Payment Service</strong>.</p><pre>import io.grpc.ManagedChannel;<br>import io.grpc.ManagedChannelBuilder;<br><br>public class OrderService {<br>    public static void main(String[] args) {<br>        ManagedChannel channel = ManagedChannelBuilder.forAddress(&quot;localhost&quot;, 50051)<br>                .usePlaintext()<br>                .build();<br><br>        PaymentServiceGrpc.PaymentServiceBlockingStub stub = PaymentServiceGrpc.newBlockingStub(channel);<br>        PaymentRequest request = PaymentRequest.newBuilder()<br>                .setUserId(&quot;12345&quot;)<br>                .setAmount(100.0)<br>                .build();<br><br>        PaymentResponse response = stub.processPayment(request);<br>        System.out.println(&quot;Payment Status: &quot; + response.getStatus() + &quot;, Transaction ID: &quot; + response.getTransactionId());<br><br>        channel.shutdown();<br>    }<br>}</pre><p>✅ This <strong>Order Service</strong> calls the <strong>Payment Service</strong> and receives a response.</p><h3>Benefits &amp; Limitations of RPC</h3><h4>✅ Benefits:</h4><ul><li>Faster communication due to <strong>binary serialization</strong>.</li><li>Efficient <strong>data transfer</strong>.</li><li><strong>Strongly typed interfaces</strong> ensure consistency.</li></ul><h4>❌ Limitations:</h4><ul><li>Requires <strong>specific tools</strong> (gRPC, Thrift, etc.).</li><li><strong>Not as widely supported</strong> as REST APIs.</li><li>Higher <strong>learning curve</strong> compared to REST.</li></ul><h3>Final Thoughts</h3><blockquote>🔹 RPC allows microservices to communicate efficiently.</blockquote><blockquote>🔹 It works by sending a request, executing the function remotely, and returning the result.</blockquote><blockquote>🔹 gRPC, Thrift, and JSON-RPC are common frameworks for RPC.</blockquote><blockquote>🔹 Even REST API calls behave similarly to RPC, but they use HTTP instead.</blockquote><p>This is how we build scalable and distributed systems using RPC! 🚀</p><p>Let me know if you have any questions or need more details. Happy coding! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d274e814ce87" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>