<?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 Aakriti Mehrotra on Medium]]></title>
        <description><![CDATA[Stories by Aakriti Mehrotra on Medium]]></description>
        <link>https://medium.com/@aakriti.meh.2004?source=rss-c38849a4b856------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*N0D1TMvvQvWnuPui</url>
            <title>Stories by Aakriti Mehrotra on Medium</title>
            <link>https://medium.com/@aakriti.meh.2004?source=rss-c38849a4b856------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 10:21:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aakriti.meh.2004/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[Your Phone Knows a Disaster Is Coming Before You Do]]></title>
            <link>https://medium.com/@aakriti.meh.2004/your-phone-knows-a-disaster-is-coming-before-you-do-cfbf7d5d739b?source=rss-c38849a4b856------2</link>
            <guid isPermaLink="false">https://medium.com/p/cfbf7d5d739b</guid>
            <category><![CDATA[telecommunication]]></category>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[cap]]></category>
            <category><![CDATA[alerts]]></category>
            <category><![CDATA[firmware]]></category>
            <dc:creator><![CDATA[Aakriti Mehrotra]]></dc:creator>
            <pubDate>Sat, 06 Jun 2026 10:57:24 GMT</pubDate>
            <atom:updated>2026-06-06T10:57:24.266Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AHxNY35U5CWDSGSSXGyF_Q.png" /></figure><p>It was night time around 1:00 AM, when my phone buzzed so loud to wake everyone in my family up (except me because I didn’t sleep yet ..lol), it was a high wind speed alert in my area.<br> It was the first time I had recieved an alert, and I just closed it hearing that siren.<br> About 30 mins later, there was another alert, for thunderstorms, this time, I read it, and since I was already on my laptop, almost done with my work, I though to check this system out. I went and searched about how does this actually work, because it didn’t seem like a simple software.<br> <br> So, here’s what I understood, the whole system, is firmware, telecommunications and Networking protocols. It actually like a 3 layered cake, wth each layer having a different flavour, I mean purpose<br> <br> And, no, I am not going to tell you that there is a government side, then there is your telecom providers, then your cellular OS, of cousre that’s all there, but I am going to tell you about the neiche stuff that I understood<br> <br> Now, let me break down the 3 layers of this cake, I mean the system.</p><h4>Layer 1 — SACHET (The Core Platform Architecture)</h4><p>You might think that there is a person sitting in some government office, hitting some “SEND ALERT” button each time we recieve an alert. Well, the system is actually pretty smart, it used a platform called SACHET (jaagteee rahooo 😆). It is a platform developed by C-DOT (Center for Development of Telematics) for the NDMA (National Disaster management Authority). Think of it as the control room that sits in the middle of everything.<br> <br> Whenever agencies like the India Meteorological Department (IMD), flood monitoring systems, tsunami warning centers, or other disaster management authorities detect something important, they don’t directly start spamming millions of phones.</p><p>SACHET then figures out things like:</p><ul><li>Who needs to receive this alert?</li><li>Which geographic area is affected?</li><li>How serious is the situation?</li><li>Should it be sent immediately or reviewed first?</li><li>Which telecom operators need to be contacted?</li></ul><p>Basically, SACHET acts like a very smart traffic controller.</p><p>It takes raw disaster information, verifies it, maps the affected region, handles permissions, and prepares everything for the next stage.</p><p>Without SACHET, every agency would need to independently coordinate with every telecom operator in the country, which sounds like a nightmare even to think about.</p><p>So yes, the first layer isn’t about sending alerts.</p><p>It’s about deciding <strong>whether an alert should exist in the first place, who should receive it, and how urgent it really is.</strong></p><h4>Layer 2 — CAP (Nooooo Not Consistency Availability and Partition Tolerance Theorem you techiee) — its Common Alerting Protocol</h4><p>Its a language that everyone understands, sort of like the vanilla flavor in any cake. It comes into picture to resolve all the format issues while excange of information between IMD, telecom companies and your phone<br> <br> Without this nothing would work. Whenever SACHET recieves information, it converts everything into a standardised XML format, don’t go away hearing this, its just a predefined structure, something like your email, which contains, to, from, subject, content, etc etc<br> <br> Well here is what the message contains :<br> <br> 1. who sent the alert? <br> 2. What type of alert is it? <br> 3. Is it a new alert, an update, or a cancellation?<br> 4. How severe is the threat? <br> 5. How certain are we that the threat exists?<br> 6. Which geographic area is affected? <br> 7. Which language should people receive it in? <br> <br> I will give you the format of the XML as well, dont punch yourself if you dont understand it, in essence it is exactly the answers to the questions ablove</p><p>1. &lt;identifier&gt;: A unique tracking ID for the specific alert instance.</p><p>2. &lt;sender&gt;: The authenticated agency authorizing the transmission.</p><p>3. &lt;msgType&gt;: Identifies if the alert is an Alert, Update, Cancel, or a system Test.</p><p>4. &lt;scope&gt;: Specifies whether the notice is Public, Restricted, or Private.</p><p>5. &lt;info&gt;: A sub-container nested with localization metadata:</p><ul><li>&lt;language&gt;: Dictates the translation target (SACHET natively supports <strong>21 Indian languages</strong>).</li><li>&lt;category&gt;: e.g., Met (Meteorological), Safety, Rescue, Health.</li><li>&lt;urgency&gt; / &lt;severity&gt; / &lt;certainty&gt;: Triggers distinct device behaviors based on risk factors (e.g., <em>Immediate</em>, <em>Severe</em>, <em>Observed</em>).</li><li>&lt;area&gt;: Houses geospatial coordinates or polygons mapping out the exact risk boundary.</li></ul><h4>Layer 3 — Cellular broadcasts &amp; The secret Listener inside your phone</h4><p>Yeah, you read that right, a “secret listener” inside your phone, but don’t worry, its not listening to your converstations with your girlfriend/boyfriend, or anyone else. It listening to something called a cellular broadcast (of if you want to, call it nature’s family drama — you called it that not me 😂, ha ha )<br> Ok well, you might assume that the alert is an SMS just crying out loud from your phone, but acually its not.</p><p>I am not sure of the Gen- Z and Gen Alpha, but surely the millenials have heard of the radio, which had to be set to a station to hear the news or songs or whatever. That is what is a broadcast, many radios tuning into some station for the content. <br> But its a little different in our case, an alert is sent to cellular towers, and those towers broadcast the message to every compatible phone currently connected to them.</p><p>No phone numbers. No contact lists. No mass texting.<br> Just one transmission reaching everyone in a specific area. Your phone is already prepared for this.</p><p>Deep inside your device is something called the “<em>baseband processor</em>”, a specialized chip responsible for cellular communication. While you’re scrolling Instagram, watching YouTube, or arguing with strangers online, this chip is quietly monitoring special broadcast channels.</p><p>It’s basically standing guard 24/7.</p><p>Most of the time, it ignores everything. But the moment it receives a broadcast marked as an emergency alert, a completely different chain of events begins. The phone doesn’t treat it like a normal notification. Instead, the firmware itself steps in. <br> <br> That loud siren?<br> on pattern that feels stronger than usual?<br> The full-screen popup that refuses to be ignored?<br> That’s not your messaging app.<br> That’s your device’s emergency alert system taking over at the operating-system level. For a few seconds, the phone essentially says:</p><p><em>“I don’t care what you’re doing right now. Read this.”</em></p><p>And that’s exactly why those alerts can cut through silent mode, Do Not Disturb, and whatever random app you’re using at that moment. The notification isn’t fighting with your apps. It has higher authority than them.</p><p>Which, when you think about it, is probably a good thing when the message is literally warning you about a cyclone, flood, or thunderstorm headed your way.</p><p>Well, I did mention compatible devices right, you read a bit more about the protocols that are used in each of the phones in the table below if you want, or you can also just skip it, because now you know the whole essence</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*p3UeENMtoAW1q2Xh2YjFDA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cfbf7d5d739b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Tried Rebuilding Chrome Autofill (Not the password manager). Here’s What I Realised.]]></title>
            <link>https://medium.com/@aakriti.meh.2004/i-tried-rebuilding-chrome-autofill-not-the-password-manager-heres-what-i-realised-c13c73190790?source=rss-c38849a4b856------2</link>
            <guid isPermaLink="false">https://medium.com/p/c13c73190790</guid>
            <category><![CDATA[dom-manipulation]]></category>
            <category><![CDATA[chrome-extension]]></category>
            <category><![CDATA[semantics]]></category>
            <category><![CDATA[tech-deep-dive]]></category>
            <category><![CDATA[autofill]]></category>
            <dc:creator><![CDATA[Aakriti Mehrotra]]></dc:creator>
            <pubDate>Thu, 14 May 2026 04:31:02 GMT</pubDate>
            <atom:updated>2026-05-14T04:31:02.216Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DUcVLvTiSEgo1oqWDgxVzg.png" /><figcaption>Image credits : AI generated</figcaption></figure><p>For the longest time, Chrome Autofill felt like one of those “obvious” browser features that nobody really thinks about. While filling any forms, maybe a job application, a simple Gform, any review forms; We click on a field, and boom, the email is already suggested, the phone number, our name, just click it and it done, no typing needed.</p><p>Sometimes even our company names and previous inputs magically show up without you ever explicitly saving them anywhere.</p><p>It feels effortless.</p><p>So naturally, I thought: <em>“How hard can it really be to recreate this?”</em></p><p>That assumption lasted exactly until I started building my own Chrome extension for automatic form filling.</p><p>And that’s when I realized:</p><blockquote>Chrome Autofill is not just a convenience feature. It’s an entire semantic prediction system hidden behind a deceptively simple UI.</blockquote><h3>The Illusion of Simplicity</h3><p>At first glance, autofill sounds straightforward.</p><p>A webpage contains:</p><pre>&lt;input placeholder=&quot;Email&quot;&gt;</pre><p>You detect the word “email”.</p><p>You insert the user’s email.</p><p>Done.</p><p>Right?</p><p>oh, not even close, Modern websites rarely behave this cleanly.</p><p>Some forms use:</p><ul><li>dynamic React rendering</li><li>generated IDs</li><li>hidden wrappers</li><li>accessibility labels</li><li>custom components</li><li>nested DOM structures</li><li>framework-controlled inputs</li></ul><p>Google Forms alone completely changed how I thought about form automation.</p><p>Unlike traditional forms, Google Forms doesn’t reliably expose:</p><ul><li>meaningful name attributes</li><li>stable IDs</li><li>simple labels</li></ul><p>Sometimes the visible text isn’t even directly attached to the input field. And yet Chrome still fills those fields effortlessly.</p><p>That was the moment I realized: <em>Chrome isn’t just “reading the DOM”</em>. <br>It understands input fields at a much deeper level.</p><h3>My Initial Approach</h3><p>My extension started with a fairly standard heuristic approach.</p><p>I built logic that tried to detect fields using common attributes:</p><pre>[<br>  &quot;aria-label&quot;,<br>  &quot;placeholder&quot;,<br>  &quot;name&quot;,<br>  &quot;id&quot;,<br>  &quot;data-automation-id&quot;,<br>  &quot;data-field-name&quot;,<br>  &quot;data-testid&quot;<br>]</pre><p>Then I mapped keywords:</p><pre>if(text.includes(&quot;email&quot;)) return &quot;email&quot;;<br>if(text.includes(&quot;phone&quot;)) return &quot;phone&quot;;</pre><p>For smaller websites, this worked surprisingly well.</p><p>But the moment I tested Google Forms, linkedin, etc, everything started breaking in different ways. Some forms ignored direct value assignment. Some forms rendered dynamically after page load. Some forms used React-controlled inputs where changing .value did nothing visually. And some forms had no meaningful labels at all.</p><h3>The Google Forms Problem</h3><p>This was probably the biggest turning point.</p><p>I noticed something fascinating:</p><p>Even when my extension couldn’t identify fields properly, Chrome itself still knew:</p><ul><li>where the email field was</li><li>where the phone number field was</li><li>where address information belonged</li></ul><p>Meanwhile, my extension was desperately parsing DOM trees trying to guess labels.</p><p>That raised the obvious question: <em>How does Chrome do this so effortlessl<br></em>The answer is: <em>Chrome Autofill is not just DOM parsing</em>.</p><h3>What Chrome Actually Does</h3><p>Chrome combines multiple systems together:</p><h3>1. HTML Heuristics</h3><p>Many websites include hidden semantic hints like:</p><pre>&lt;input autocomplete=&quot;email&quot;&gt;</pre><p>or</p><pre>&lt;input autocomplete=&quot;organization&quot;&gt;</pre><p>Chrome heavily relies on these.</p><p>This alone gives Chrome an enormous advantage.</p><h3>2. Form Signatures</h3><p>Chrome fingerprints form structures.</p><p>For example:</p><pre>First Name<br>Last Name<br>Email<br>Phone</pre><p>becomes a recognizable form pattern.</p><p>If millions of users have interacted with similar structures before, Chrome already has confidence about what each field represents.</p><h3>3. User History</h3><p>This explains the “company name suggestions” I observed.</p><p>Chrome remembers previously entered values and associates them with similar fields later.</p><p>That’s why old company names suddenly appear while typing into experience sections.</p><p>This isn’t just autofill.</p><p>It’s learned form memory.</p><h3>4. Browser-Level Access</h3><p>Well, this is the biggest difference.</p><p>What my extension sees: <br><em>rendered webpage DOM</em></p><p><strong>Versus</strong></p><p>What Chrome sees: <br><em>browser internals, form metadata, accessibility structures, rendering pipelines</em></p><p>before abstraction layers even appear.</p><p>That’s an unfair advantage extensions simply don’t have.</p><h3>5. Semantic Prediction</h3><p>Chrome also analyzes:</p><ul><li>neighboring text</li><li>field order</li><li>spatial layout</li><li>label relationships</li><li>form sections</li></ul><p>Even when labels are vague like:</p><pre>How can we contact you?</pre><p>Chrome can often infer that it probably expects an email or phone number.</p><p>That’s not simple matching anymore.</p><p>That’s semantic prediction.</p><h3>The Hardest Part: React-Controlled Inputs</h3><p>Another problem I encountered was modern frontend frameworks.</p><p>Many websites don’t react to:</p><pre>input.value = &quot;example&quot;</pre><p>anymore.</p><p>Frameworks like React maintain internal state systems.So visually changing the DOM is not enough. You must simulate actual user typing using:</p><ul><li>native setters</li><li>dispatched input events</li><li>change events</li></ul><p>Otherwise, the form ignores the update entirely.</p><p>This was one of the biggest reasons why my autofill initially “looked” successful while actually filling nothing.</p><h3>What Started as a Small Project Became a much deeper understanding of the DOM Parsing Engine</h3><p>At some point, I <em>stopped</em> thinking of this project as: <em>“a simple Chrome extension” </em>and realised it was an intricate detailing of :</p><ul><li>DOM analysis</li><li>semantic inference</li><li>heuristic mapping</li><li>browser event simulation</li><li>framework compatibility handling</li></ul><p>The deeper I went, the more I appreciated how sophisticated Chrome Autofill actually is.</p><p>It’s one of those features that feels invisible precisely because it’s engineered so well.</p><h3>What I Built</h3><p>After multiple iterations, debugging sessions, and lots of form-breaking moments, I ended up building my own Chrome Extension for automatic form filling, majorly for my job applications.</p><p>It supports:</p><ul><li>personal information</li><li>addresses</li><li>education details</li><li>coding profiles</li><li>social links</li><li>achievements</li><li>experience sections</li></ul><p>and works across:</p><ul><li>Google Forms</li><li>basic job portals</li><li>React-based forms</li><li>common websites</li></ul><p>The project gave me a much deeper appreciation for: browser architecture, extension systems, frontend frameworks, semantic field detection</p><h3>Final Thought</h3><p>Chrome Autofill feels effortless because Chrome has spent years turning form understanding into a browser-level intelligence system.</p><p>When you try rebuilding even a fraction of it yourself, you realize:</p><p>what appears simple on the surface is actually hiding layers of engineering complexity underneath.</p><p>And honestly, that’s what made this project so interesting.</p><h3>GitHub</h3><p>I’ve open-sourced the extension here:</p><p>👉 <a href="https://github.com/AakritiMeh/automatic-form-filler-extension">https://github.com/AakritiMeh/automatic-form-filler-extension</a></p><p>Would love feedback, suggestions, or ideas for improving field detection further.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c13c73190790" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Science and Technology of Airline Pricing — even before AI was known to the mankind]]></title>
            <link>https://medium.com/@aakriti.meh.2004/the-science-and-technology-of-airline-pricing-even-before-ai-was-known-to-the-mankind-5d2df474982a?source=rss-c38849a4b856------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d2df474982a</guid>
            <category><![CDATA[business-strategy]]></category>
            <category><![CDATA[backend-engineering]]></category>
            <category><![CDATA[scalable-architecture]]></category>
            <category><![CDATA[dynamic-pricing]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Aakriti Mehrotra]]></dc:creator>
            <pubDate>Wed, 06 May 2026 10:58:49 GMT</pubDate>
            <atom:updated>2026-05-06T10:58:49.492Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CrANhK-HJVL_MSojfdsQCw.png" /></figure><p>We’ve all experienced it.</p><p>You search for a flight from say Chennai to Delhi.<br>The ticket costs ₹8,200.<br>You wait a few hours.<br>Suddenly:<br>₹5,900.<br>You refresh again at night:<br>₹11,400.<br>And during Diwali?<br>The same route may cross ₹20,000.</p><p>At first glance, it feels random.<br>Sometimes even unfair.</p><p>But behind that single changing number lies one of the most sophisticated business optimization systems ever built — long before modern AI became mainstream.</p><p>And surprisingly, these systems were already operating at massive scale decades ago.</p><p>This is the story of:</p><ul><li>how airlines actually think,</li><li>how pricing systems were engineered,</li><li>how businesses maximize revenue from “expiring inventory,”</li><li>and how mathematics, economics, software architecture, and operations research all come together to decide the price of your ticket.</li></ul><h3>Airlines Don’t Sell Seats.</h3><h3>They Sell Revenue Opportunity.</h3><p>This is the first mental model shift.</p><p>Most people think airlines are trying to:</p><ul><li>fill flights,</li><li>sell all seats,</li><li>or keep prices competitive.</li></ul><p>That’s only partially true.</p><p>An airline’s actual goal is:</p><pre>Maximize total expected revenue<br>from a finite number of seats<br>before departure.</pre><p>And airline seats are unlike almost any other inventory.</p><p>A phone unsold today can be sold tomorrow.<br>A shirt can be discounted next week.</p><p>But once a flight departs:</p><pre>an unsold airline seat becomes permanently worthless.</pre><p>That creates an incredibly difficult business problem.</p><p>Because airlines must constantly balance:</p><p>selling too cheaply too early,<br>vs<br>waiting for future high-paying passengers.</p><p>And that single tension gave birth to the airline Revenue Management industry.</p><h3>The Same Seat Has Different Economic Value</h3><p>This is where business strategy enters.</p><p>The airline knows:<br>not every passenger values a ticket equally.</p><p>So airlines realized something revolutionary:</p><pre>The same physical seat<br>can generate vastly different revenue<br>from different customer segments.</pre><p>And that became the foundation of: “Yield Management”</p><h3>Airlines Don’t Really Sell “Economy”</h3><p>They Sell Fare Buckets</p><p>This is one of the most misunderstood parts of airline pricing.</p><p>Passengers think there are:</p><ul><li>Economy</li><li>Business</li><li>First Class</li></ul><p>But internally airlines divide seats into invisible booking classes.</p><p>Example:</p><p>Fare — BucketPrice<br>T — ₹4,999<br>S — ₹6,500<br>V — ₹8,000<br>M — ₹11,000<br>Y — ₹18,000</p><p>All of these may be:<br>the exact same economy seat.</p><p>The only difference:</p><ul><li>pricing rules</li><li>refundability</li><li>inventory availability</li></ul><p>The airline dynamically decides:</p><ul><li>which buckets stay open,</li><li>which close,</li><li>and how many seats each bucket receives.</li></ul><p>This is where those sudden price jumps come from.</p><p>Not because:<br>“someone bought one seat.”</p><p>But because:<br>the system closed a cheaper fare bucket.</p><h3>Dynamic Pricing Existed Long Before AI</h3><p>One of the most fascinating parts of airline systems is this:</p><p>Modern generative AI did NOT create dynamic pricing.</p><p>Airlines were already running:</p><ul><li>predictive systems,</li><li>probabilistic forecasting,</li><li>optimization engines,</li><li>inventory control algorithms</li></ul><p>decades ago.</p><p>In fact, airline revenue management became one of the earliest industrial applications of:</p><ul><li>Operations Research,</li><li>Mathematical Optimization,</li><li>Probabilistic Forecasting,</li><li>Dynamic Programming,</li><li>and Decision Science.</li></ul><p>These systems weren’t “AI chatbots.”<br>They were industrial-scale optimization engines.</p><h3>The Real Core Problem</h3><p>Every pricing engine is constantly solving:</p><pre>Should we sell this seat now for ₹5K,<br>or protect it for a future passenger<br>who may pay ₹15K later?</pre><p>That sounds simple.</p><p>But mathematically,<br>this becomes an enormous probabilistic optimization problem.</p><p>Because future demand is uncertain.</p><p>And every decision is irreversible.</p><p>If the airline sells too cheaply:</p><ul><li>premium revenue is lost forever.</li></ul><p>If the airline waits too long:</p><ul><li>the seat may remain empty.</li></ul><p>That’s why airline pricing is fundamentally : “stochastic optimization under uncertainty”</p><h3>How the System Actually Thinks</h3><p>The pricing engine continuously evaluates:</p><ul><li>seats remaining</li><li>booking velocity</li><li>time before departure</li><li>historical booking curves</li><li>seasonality</li><li>festivals</li><li>competitor fares</li><li>route profitability</li><li>business vs leisure demand</li><li>cancellation trends</li><li>no-show probabilities</li></ul><p>all in real time.</p><h3>The Booking Curve</h3><p>Every route has historical demand behavior.</p><p>Example:</p><p>Delhi → Mumbai:</p><p>Days Before Flight — Typical Seats Sold<br>30 — 15%<br>15 — 40%<br>7 — 70%<br>2 — 92%</p><p>The system continuously compares:</p><pre>Actual bookings<br>vs<br>Expected bookings</pre><p>If bookings are happening faster than expected:<br>prices rise.</p><p>If slower:<br>cheaper buckets reopen.</p><p>This is why prices sometimes fall unexpectedly too.</p><h3>The Architecture Behind It</h3><p>At a high level,<br>a classical airline Revenue Management System looked something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/262/1*wtJbdUTVR3xIS2-24uB7UA.png" /></figure><p>This wasn’t a single application.</p><p>It was an ecosystem of:</p><ul><li>pricing engines,</li><li>inventory systems,</li><li>reservation systems,</li><li>forecasting engines,</li><li>and distributed transaction systems.</li></ul><h3>The Famous EMSR Logic</h3><p>One of the foundational algorithms was: “Expected Marginal Seat Revenue (EMSR)”</p><p>The core logic:</p><pre>Should low-fare bookings be rejected<br>to preserve inventory for future high-fare demand?</pre><p>Simplified mathematically:</p><p>Expected Future Revenue = P(high demand) X High Fare</p><p>If future expected revenue exceeds current offered fare:</p><ul><li>cheaper buckets close.</li></ul><p>And suddenly your ₹5K ticket becomes ₹10K.</p><p>Even if many seats are still empty.</p><h3>Airlines Optimize Networks, Not Flights</h3><p>This is where things become truly sophisticated.</p><p>Airlines don’t optimize:</p><ul><li>one route,</li><li>one flight,</li><li>or one seat.</li></ul><p>They optimize : “the entire transportation network”</p><p>Example:</p><p>A seat on:<br>Mumbai → Delhi</p><p>may be protected because:<br>a future passenger flying:<br>Mumbai → Delhi → London</p><p>could generate far higher total revenue.</p><p>So a domestic fare may become expensive due to international demand flows.</p><p>This is called: “Origin-Destination Optimization (O&amp;D)”</p><h3>The Business Aspect : Why Leadership Cares So Much About Pricing?</h3><p>Airlines operate on razor-thin margins.</p><p>Fuel costs.<br>Airport fees.<br>Crew costs.<br>Maintenance.<br>Currency fluctuations.</p><p>All heavily impact profitability.</p><p>Which means even:</p><pre>₹200 additional revenue per passenger<br>across millions of passengers<br>creates massive financial impact.</pre><p>That’s why airline leadership obsesses over:</p><ul><li>Yield,</li><li>RASK,</li><li>Load Factor,</li><li>and Inventory Monetization.</li></ul><h4>The CEO Doesn’t Want Full Flights —</h4><p>This surprises many people.</p><p>A 100% full flight is NOT automatically ideal.</p><p>Example:</p><p>Scenario — Revenue<br>180 seats × ₹5K = ₹9 lakh<br>120 seats × ₹12K = ₹14.4 lakh</p><p>Fewer passengers.<br>Higher profitability.</p><p>This is why airlines sometimes intentionally:</p><ul><li>keep prices high,</li><li>reject low-value demand,</li><li>and protect inventory.</li></ul><p>Because: “maximizing margin matters more than maximizing occupancy”</p><h3>Then Came Real-Time Competitor Warfare</h3><p>Airlines constantly monitor competitors.</p><p>If one airline:</p><ul><li>sells out,</li><li>cancels flights,</li><li>reduces capacity,</li><li>or raises fares,</li></ul><p>others immediately react.</p><p>This created highly dynamic pricing ecosystems.</p><p>Essentially:</p><ul><li>algorithm vs algorithm.</li></ul><p>Long before modern AI became fashionable.</p><h3>The Engineering Complexity Was Massive</h3><p>These systems handled:</p><ul><li>millions of searches,</li><li>thousands of flights,</li><li>real-time inventory updates,</li><li>distributed reservations,</li><li>concurrent bookings,</li><li>overbooking calculations,</li><li>and pricing recalculations</li></ul><p>with near-zero downtime.</p><p>And most of this infrastructure was built using:</p><ul><li>C,</li><li>C++,</li><li>COBOL,</li><li>Oracle,</li><li>IBM mainframes,</li><li>distributed transaction systems</li></ul><p>years before cloud-native systems and AI, ML and DL existed.</p><h3>Why This Is One of the Greatest Engineering Problems Ever Solved</h3><p>Because airlines operate in an environment where:</p><pre>future demand is unknown,<br>inventory is finite,<br>decisions are irreversible,<br>and revenue opportunity changes every second.</pre><p>So the system must continuously answer:</p><pre>What is the optimal economic value<br>of this seat<br>at this exact moment?</pre><p>That is not simple pricing.</p><p>That is:</p><ul><li>economics,</li><li>optimization theory,</li><li>probability,</li><li>software engineering,</li><li>business strategy,</li><li>and network science</li></ul><p>all fused together.</p><h3>Final Thought</h3><p>The next time a flight jumps from:<br>₹5K → ₹12K,</p><p>remember:</p><p>behind that single number is not merely a pricing table.</p><p>It is an industrial-scale decision engine evaluating:</p><ul><li>future demand probability,</li><li>customer willingness to pay,</li><li>route economics,</li><li>competitor behavior,</li><li>inventory scarcity,</li><li>and expected network revenue</li></ul><p>in real time.</p><p>Long before AI became mainstream,<br>airlines had already built some of the world’s most sophisticated algorithmic business systems.</p><p>And at its core,<br>the airline industry isn’t just selling transportation.</p><p>It’s solving a massive real-time economic optimization problem — <br>one seat at a time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d2df474982a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Invisible Phone Call]]></title>
            <link>https://medium.com/@aakriti.meh.2004/the-invisible-phone-call-ca93989ec873?source=rss-c38849a4b856------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca93989ec873</guid>
            <category><![CDATA[business-perspective]]></category>
            <category><![CDATA[low-level-design]]></category>
            <category><![CDATA[privacy-protection]]></category>
            <category><![CDATA[backend-architecture]]></category>
            <dc:creator><![CDATA[Aakriti Mehrotra]]></dc:creator>
            <pubDate>Wed, 29 Apr 2026 13:04:14 GMT</pubDate>
            <atom:updated>2026-04-29T13:04:14.659Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cx8_ZjQrfco7aCWETUd3Sg.png" /></figure><p>I was casually booking a ride on Uber, just another routine day, when something small caught my attention. I tapped the “Call Driver” button, made the call, and it worked seamlessly. But then a question hit me: I never saw the driver’s real phone number, and they never saw mine. That moment of curiosity turned into a deep dive into one of the most elegant backend systems I’ve come across.</p><p>What started as a simple observation quickly turned into a technical exploration. I began digging into how companies like Uber, Ola, Amazon’s Delivery systems implement this feature at scale. This isn’t just a UI trick — it’s a full-fledged system designed around privacy, control, and reliability.</p><p>To understand this, I reframed the problem from scratch.</p><h3>Thought Process: Thinking Like the Middleman Builder</h3><p>Step 1: Define the abstraction clearly<br> You are not building a calling system. You are building a privacy-preserving communication bridge between two unknown parties. The system must hide identities, allow controlled communication, be temporary and revocable, and be observable for logs and abuse detection.</p><p>Step 2: Think in mappings<br> At its core, the system is just mappings:<br> Proxy Number → Real Number A<br> Proxy Number → Real Number B<br> Session ID → (A, B, Proxy, TTL-time to live)<br> This is essentially a stateful mapping problem.</p><p>Step 3: Define lifecycle<br> Every interaction follows a strict lifecycle:<br> Session Creation → Assign proxy → Map users <br> Active Routing → Calls routed via backend<br> Monitoring → Logs, analytics, abuse checks<br> Expiry → Destroy mapping and recycle number<br> If lifecycle is not designed well, the system either leaks data or breaks.</p><p>Step 4: Identify control points<br> The system sits in the middle, so it controls who can call whom, when communication is allowed, how long it lasts, and how misuse is handled. This is where real product differentiation happens.</p><h3>Technical Architecture (What is used in companies)</h3><h3>Core Components</h3><ol><li>Telephony Provider Layer<br> Systems integrate with providers like Twilio, Vonage, and Sinch. These provide virtual numbers, call and SMS APIs, and webhook events.</li><li>Backend System<br> The core backend includes:<br> Session Service which creates and stores mappings<br> Routing Logic which routes calls based on proxy lookup<br> State Store such as Redis for fast lookup and a database for persistence</li><li>Number Pool Manager<br> Maintains available proxy numbers, allocates them, and recycles them after expiry.</li><li>Event/Webhook Handler<br> Receives incoming call or SMS events and triggers routing logic.</li><li>Security and Abuse Layer<br> Handles rate limiting, blacklisting, and optional content filtering.</li><li>Observability<br> Logs all interactions, tracks metrics like latency, and raises alerts on failures.</li></ol><pre>Simplified Architecture<br><br>User A → App → Backend → Assign Proxy  <br>↓  <br>Telephony API  <br>↓  <br>User B ← Routed Call ← Proxy Number</pre><p>Now, let’s dive deep into the low level design of this feature</p><h3>Low Level Design</h3><p>At its core, the system has few <strong>core functional requiremnts</strong>:</p><ul><li>Create masked communication session</li><li>Assign proxy number</li><li>Route incoming calls/messages</li><li>Expire sessions after TTL</li><li>Maintain mapping between users</li></ul><p>And, a few <strong>secondary functional requirements</strong></p><ul><li>Logging &amp; observability</li><li>Abuse prevention hooks</li><li>Reusability of proxy numbers</li></ul><p>We also observe a few <strong>edge cases</strong> for this, such as the following:</p><ul><li>Proxy number pool exhausted</li><li>Session expired but call still incoming</li><li>Same users creating multiple sessions</li><li>One user calling outside allowed window</li><li>Race condition in assigning proxy numbers</li><li>Duplicate webhook events</li><li>System restart → lost mappings (need persistence)</li></ul><p>Now, lets discuss a few <strong>core entities</strong></p><p>1. User</p><pre>id: str<br>phone_number: str</pre><p>2. ProxyNumber</p><pre>number: str<br>is_available: bool<br>region: str</pre><p>3. Session</p><pre>session_id: str<br>user_a: User<br>user_b: User<br>proxy_number: ProxyNumber<br>status: ACTIVE | EXPIRED<br>expires_at: datetime</pre><p>4. CallEvent</p><pre>from_number: str<br>to_number: str<br>timestamp: datetime</pre><p>The <strong>interaction flows</strong> that need to be included are :</p><p><em>Flow 1: Session Creation</em></p><ol><li>User A requests connection</li><li>Backend assigns proxy</li><li>Session stored</li><li>Proxy returned</li></ol><p><em>Flow 2: Incoming Call</em></p><ol><li>Call hits /incoming-call</li><li>Lookup proxy → session</li><li>Identify caller</li><li>Route to other user</li></ol><p><em>Flow 3: Expiry</em></p><ol><li>TTL reached</li><li>Session invalidated</li><li>Proxy returned to pool</li></ol><p>Now, if we think of the <strong>Design Patterns and principles </strong>that we can incorporate into our codebase, before implementing it, is</p><ol><li>Strategy Pattern — for the different ways of routing that can be used — for example which strategy needs to be implemented for routing the call, or for the expiration of proxy numbers and sessions</li><li>State Pattern — how will each each session status flow between ACTIVE, EXPIRED and BLOCKED.</li><li>Repository Pattern — To abstract the DB access</li><li>SRP (Single Responsibility) — Each layer has one job</li><li>OCP (Open/Closed) — Easy to extend routing logic</li><li>DIP (Dependency Inversion) — Services depend on abstractions</li><li>Encapsulation — Domain models hide internal logic</li></ol><p>For the codebase of dummy implementation in java, you can check out the github here : <a href="https://github.com/AakritiMeh/calling_feature_demo">Github</a></p><h3>Business Thinking</h3><p>This system is not just technical — it is a core product feature.</p><p>Privacy as a Feature<br> Users trust the platform because their personal data is protected. It prevents off-platform communication and misuse.</p><p>Platform Control<br> The platform controls communication timing, moderation, and data insights. This allows companies to enforce policies and improve safety.</p><p>What started as a casual observation turned into a deep appreciation for how thoughtfully modern systems are designed. This tiny feature — masked calling — is actually a powerful combination of distributed systems, privacy engineering, and business strategy.</p><p>You’ll find similar systems not just in ride-hailing, but in delivery apps, marketplaces, and even dating platforms. It has quietly become a core building block of digital trust.</p><p>At its heart, this system is not about calls — it’s about control, privacy, and creating safe interactions between strangers. And that’s what makes it one of the most elegant “invisible” features in modern software.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca93989ec873" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Caching & Redis: The Backbone of Scalable Systems]]></title>
            <link>https://medium.com/@aakriti.meh.2004/caching-redis-the-backbone-of-scalable-systems-7571489f7359?source=rss-c38849a4b856------2</link>
            <guid isPermaLink="false">https://medium.com/p/7571489f7359</guid>
            <category><![CDATA[memcached]]></category>
            <category><![CDATA[caching]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[caching-strategies]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Aakriti Mehrotra]]></dc:creator>
            <pubDate>Tue, 17 Feb 2026 15:58:13 GMT</pubDate>
            <atom:updated>2026-02-17T15:58:13.712Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*SwzHeJZXEt6YxfWeT3vlaQ.jpeg" /></figure><p>Modern backend systems don’t scale because of faster CPUs.<br>They scale because of <strong>smart caching</strong>.If your application hits the database for every request, performance will degrade, infrastructure costs will rise, and your system will eventually struggle under traffic spikes.Caching is the silent hero that prevents that.Let’s understand it properly — not just definitions, but how it actually works in real production systems.</p><h3>What Is Caching?</h3><p>A <strong>cache</strong> is a fast storage layer (usually in-memory) that stores frequently accessed data so it can be retrieved quickly without recomputing or re-fetching it from a slower source like a database or external API.</p><p>Most caches operate as <strong>key–value stores</strong>:</p><ul><li>Key → Identifier (e.g., user:123)</li><li>Value → Data (e.g., JSON response)</li></ul><p>The goal is simple:</p><blockquote><em>Reduce latency. Reduce database load. Improve scalability.</em></blockquote><h3>Why Caching Matters More Than You Think</h3><p>Imagine your application receives 10,000 requests per minute for the same user profile.</p><p>Without caching:</p><ul><li>10,000 database queries</li><li>Increased CPU and disk usage</li><li>Higher infrastructure costs</li><li>Slower response times</li></ul><p>With caching:</p><ul><li>First request hits database</li><li>Remaining 9,999 served from memory in milliseconds</li></ul><p>That’s the difference between a system that scales and one that collapses.</p><p>Caching also helps when computations are expensive.<br>If generating analytics takes 500ms, you compute once, cache the result, and serve it instantly for the next few minutes.</p><p>Caching turns expensive operations into cheap ones.</p><h3>Why Not Cache Everything?</h3><p>Because memory is expensive and limited.</p><p>If you cache everything:</p><ul><li>Lookup performance can degrade</li><li>Memory usage explodes</li><li>You may store useless data</li></ul><p>This is where <strong>eviction policies</strong> come in.</p><h3>Cache Eviction Policies: Deciding What Stays</h3><p>Since cache size is limited, we must decide which data to remove when it’s full.</p><h3>LRU (Least Recently Used)</h3><p>Removes the least recently accessed item.</p><p>If a piece of data hasn’t been used in a while, it’s probably safe to evict.</p><p>LRU is simple and widely used in production.</p><h3>LFU (Least Frequently Used)</h3><p>Removes the least frequently accessed item.</p><p>Better when long-term access frequency matters more than recency.</p><p>Modern systems often use optimized variants of these algorithms for better hit rates.</p><h3>The Hard Problems in Caching</h3><p>Caching sounds simple. In reality, it introduces serious engineering challenges.</p><h3>1. Thrashing</h3><p>If your cache is too small, items constantly replace each other.</p><p>Result:</p><ul><li>Frequent cache misses</li><li>Minimal performance benefit</li></ul><h3>2. Poor Eviction Strategy</h3><p>Wrong policy → high miss rate → wasted resources.</p><h3>3. Stale Data (The Hardest Problem)</h3><p>If:</p><ul><li>Database updates</li><li>Cache still contains old value</li></ul><p>Users receive outdated information.</p><p>This is critical in systems involving:</p><ul><li>Password updates</li><li>Financial transactions</li><li>Inventory management</li></ul><p>Caching improves speed — but consistency becomes harder.</p><h3>Where Should Cache Live?</h3><p>There are two primary approaches.</p><h3>Local (In-Memory) Cache</h3><p>Stored inside the application server.</p><p>Pros:</p><ul><li>Extremely fast</li><li>Simple to implement</li></ul><p>Cons:</p><ul><li>Lost if server crashes</li><li>Different servers may hold inconsistent data</li><li>Doesn’t scale well in distributed systems</li></ul><p>Useful for small systems or non-critical data.</p><h3>Distributed Cache (Production Standard)</h3><p>In modern architectures, applications use a <strong>shared distributed cache</strong>.</p><p>The most popular example is:</p><h3>🔥 Redis</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*D79f-un7DGzSkb9U.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wyFZ4cPe62B7wVL0.png" /></figure><p>Redis is an in-memory key-value data store used as:</p><ul><li>Distributed cache</li><li>Session store</li><li>Real-time analytics engine</li><li>Leaderboard engine</li><li>Rate limiter</li><li>Pub/Sub messaging system</li></ul><h3>Why Redis Dominates Production Systems</h3><ul><li>Extremely fast (RAM-based)</li><li>Rich data types (strings, hashes, lists, sets, sorted sets, streams)</li><li>Built-in TTL (automatic expiration)</li><li>Replication support</li><li>Clustering and sharding</li><li>Optional persistence (RDB, AOF)</li></ul><p>In a typical production architecture, Redis sits between your app and database:</p><pre>Client<br>   ↓<br>Load Balancer<br>   ↓<br>Application Servers<br>   ↓<br>Redis (Cache Layer)<br>   ↓<br>Database</pre><p>The database becomes the <strong>source of truth</strong>.<br>Redis absorbs most read traffic.</p><h3>Redis vs Memcached</h3><p>Another well-known caching system is:</p><h3>Memcached</h3><p>Memcached is lightweight and extremely fast but supports only string-based key–value pairs and has no persistence.</p><p>Redis, on the other hand:</p><ul><li>Supports complex data types</li><li>Offers clustering natively</li><li>Supports Pub/Sub</li><li>Can persist data</li></ul><p>In modern architectures, Redis is usually preferred due to flexibility and ecosystem maturity.</p><h3>Caching in REST APIs</h3><p>Caching isn’t just about infrastructure — it’s central to API design.</p><h3>Application-Level Caching</h3><p>When a request arrives:</p><ol><li>Generate a cache key</li><li>Check Redis</li><li>If hit → return immediately</li><li>If miss → fetch from DB → store in cache → return</li></ol><p>Example keys:</p><ul><li>user:123</li><li>users:page=2:limit=10</li></ul><p>Keys must uniquely represent request parameters to avoid incorrect responses.</p><h3>Conditional HTTP Caching</h3><p>Using:</p><ul><li>ETag</li><li>Last-Modified</li></ul><p>If resource hasn’t changed, server returns:</p><pre>304 Not Modified</pre><p>No response body. Minimal bandwidth. Faster responses.</p><h3>Cache Invalidation: The Real Engineering Challenge</h3><p>There are multiple strategies.</p><h3>Write-Through</h3><ul><li>Update database</li><li>Update cache immediately</li></ul><p>Strong consistency, slower writes.</p><h3>Write-Back (Write-Around)</h3><ul><li>Update database</li><li>Invalidate cache</li><li>Next read repopulates cache</li></ul><p>More scalable, slightly relaxed consistency.</p><h3>TTL-Based Expiration</h3><ul><li>Entries expire automatically after a time window</li></ul><p>Simple and widely used, but allows temporary staleness.</p><p>Most production systems use a hybrid approach depending on business requirements.</p><h3>Multi-Layer Caching in Real Systems</h3><p>Modern systems rarely rely on a single cache.</p><p>They use layers:</p><ol><li>Browser Cache</li><li>CDN (e.g., Cloudflare)</li><li>Application Cache (Redis)</li><li>Database</li></ol><p>Each layer reduces load on the next.</p><p>This layered approach dramatically improves scalability and resilience.</p><h3>The Core Trade-Off</h3><p>Caching is about balancing:</p><ul><li>Speed vs Consistency</li><li>Memory vs Cost</li><li>Simplicity vs Scalability</li></ul><p>Done right, caching can reduce database load by 70–90%.</p><p>Done wrong, it can introduce subtle bugs and stale data issues.</p><h3>Final Thoughts</h3><p>Caching is not an optimization you add later.</p><p>It is a <strong>foundational design decision</strong> in scalable systems.</p><p>Tools like Redis have become industry standards because they solve real-world distributed caching problems at scale.</p><p>If you’re learning backend engineering or system design, mastering caching is non-negotiable.</p><p>Because in modern systems:</p><blockquote><em>Performance isn’t just about faster code.<br>It’s about avoiding unnecessary work altogether.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7571489f7359" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling 101: From Basic Load Balancing to Consistent Hashing]]></title>
            <link>https://medium.com/@aakriti.meh.2004/scaling-101-from-basic-load-balancing-to-consistent-hashing-afac5731462f?source=rss-c38849a4b856------2</link>
            <guid isPermaLink="false">https://medium.com/p/afac5731462f</guid>
            <category><![CDATA[nginx]]></category>
            <category><![CDATA[consistent-hashing]]></category>
            <category><![CDATA[load-balancing]]></category>
            <dc:creator><![CDATA[Aakriti Mehrotra]]></dc:creator>
            <pubDate>Wed, 11 Feb 2026 15:09:29 GMT</pubDate>
            <atom:updated>2026-02-11T15:09:29.915Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2IsWbCzvmeCVCa-lIWrcpQ.png" /></figure><p>In the world of system design, success often leads to a new set of problems. When an app goes viral, a single server can no longer handle the traffic. You add more servers, but now you face a fundamental question: <strong>Which server should handle which request?</strong></p><p>This is the domain of <strong>Load Balancing</strong>. \Here, I will explain why traditional approaches fail at scale and how <strong>Consistent Hashing</strong> provides the solution used by tech giants.</p><h3>The Basics: Servers, Requests, and Scaling</h3><p>To understand load balancing, we first need to agree on the definitions.</p><ol><li><strong>A Server</strong> is simply a computer running an algorithm to process user requests (e.g., applying a filter to an image).</li><li><strong>A Request</strong> is the input sent by the client (mobile app/browser) to the server.</li></ol><h3>The Scaling Problem</h3><p>Initially, one server handles all traffic. But if your product becomes popular, thousands of concurrent requests will crash that single server. The solution is horizontal scaling: adding more servers to form a cluster.</p><p>But this creates a new challenge. You can’t just send requests randomly; you need a strategy to distribute the load evenly so that no single server is overwhelmed while others sit idle.</p><h3>The Naive Approach: Modulo Hashing</h3><p>The most intuitive way to distribute requests is using simple math. We assign every request a unique ID (like a user_id or session_id), hash it, and map it to a server using the modulo operator.</p><p>ServerIndex = hash(request_id) % NumberOfServers</p><h3>Example</h3><p>Imagine we have 4 servers (S0, S1, S2, S3).</p><ol><li>If a request hashes to 3:<br> 3 % 4 = 3<br> Sent to <strong>S3</strong>.</li><li>If a request hashes to 12:<br> 12 % 4 = 0<br>Sent to <strong>S0</strong>.</li></ol><p>This works perfectly — as long as the number of servers stays fixed. The load is spread evenly (1/N per server), and the mapping is deterministic.</p><h3>The Problem: Adding a Server</h3><p>Real systems are not static. Servers crash, or we add new ones to handle Black Friday traffic.</p><p>Suppose we add a 5th server. The divisor in our equation changes from 4 to 5.</p><p>Old: hash % 4 <br>New: hash % 5</p><p>Mathematically, this changes the result for almost <strong>every single request</strong>. A user previously mapped to Server 1 might now map to Server 4.</p><h3>Why This is Dangerous</h3><p>In a stateless system, this is annoying. In a stateful system (where servers hold local caches or session data), this is catastrophic.</p><ol><li><strong>Cache Misses:</strong> All locally cached data (profiles, sessions) becomes useless because users are routed to “wrong” servers.</li><li><strong>Database Overload:</strong> Since caches are cold, every request hits the primary database simultaneously.</li><li><strong>System Destabilization:</strong> This creates a “thundering herd” effect that can take down the entire platform.</li></ol><h3>The Solution: Consistent Hashing</h3><p>We need a system where adding or removing a server only moves a small fraction of requests, rather than reshuffling the entire deck. Enter <strong>Consistent Hashing</strong>.</p><h3>How It Works: The Ring</h3><p>Instead of a linear array, imagine the entire range of possible hash values mapped onto a circle (a ring), wrapping around from the maximum value back to 0.</p><ol><li><strong>Place Servers on the Ring:</strong> Hash the server IPs/IDs to place them at specific points on the ring.</li><li><strong>Place Requests on the Ring:</strong> Hash the request IDs to place them on the ring.</li><li><strong>Route Clockwise:</strong> To map a request to a server, simply move <strong>clockwise</strong> along the ring. The first server you encounter is the one that handles the request.</li></ol><h3>Why This Solves Scaling</h3><ol><li><strong>Adding a Server:</strong> If we insert a new server, it cuts into the ring segment of its neighbor. It only “steals” the requests that fall between itself and the previous server. All other requests on the ring stay where they are.</li><li><strong>Removing a Server:</strong> If a server fails, its requests simply slide clockwise to the next available server.</li></ol><p>This ensures that when N changes, only approx 1/N of the keys need to be remapped.</p><h3>Refining the Ring: Virtual Nodes</h3><p>Basic consistent hashing has a flaw: <strong>Skewed Load</strong>.</p><p>If you only have a few servers, they might be placed unevenly on the ring. One server might handle a huge segment (hotspot) while another handles a tiny slice.</p><h3>The Fix: Virtual Nodes (VNodes)</h3><p>Instead of mapping a physical server to a single point on the ring, we map it to <strong>multiple points</strong> using different hash functions. These represent “Virtual Nodes.”</p><ol><li><strong>Server A</strong> exists at positions A1, A2, A3…</li><li><strong>Server B</strong> exists at positions B1, B2, B3…</li></ol><p>By interleaving these nodes, we ensure that:</p><ol><li>The load is more evenly distributed.</li><li>If a physical server dies, its load is split among several other servers (who pick up its various VNodes), preventing any single neighbor from being overwhelmed.</li></ol><h3>Real-World Scenario: NGINX and Server Failure</h3><p>Let’s apply this to a common interview question and production scenario.</p><p><strong>Scenario:</strong> External traffic -&gt; NGINX Load Balancer -&gt; 3 Backend Servers.</p><p><strong>Question:</strong> What happens if one server dies?</p><h3>1. Failure Detection</h3><p>NGINX doesn’t just blindly forward traffic. It actively monitors backend health (Health Checks). If Server 2 stops responding (due to a crash or timeout), NGINX marks it as <strong>DOWN</strong>.</p><h3>2. Traffic Rerouting</h3><p>NGINX removes Server 2 from the rotation. The traffic that used to go to Server 2 is now redistributed to Server 1 and Server 3.</p><p><strong>Load Increase:</strong> The remaining servers see their load jump from 33% to 50%.</p><h3>3. The User Experience (Stateless vs. Stateful)</h3><ol><li><strong>Best Case (Stateless):</strong> If your app uses a shared database (Redis/Postgres) for sessions, the user barely notices. Their request is routed to a new server, which pulls their session from the DB, and everything works.</li><li><strong>Worst Case (Stateful):</strong> If sessions were stored in Server 2’s memory, those users are suddenly logged out or lose their shopping carts. This is why modern distributed systems strive to be stateless.</li></ol><h3>Summary</h3><p>Consistent hashing is the backbone of elastic systems like Amazon DynamoDB, Cassandra, and CDNs. It allows systems to scale up and down gracefully, ensuring that a simple server addition doesn’t bring the whole network to its knees.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afac5731462f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving Inset Interval Problem]]></title>
            <link>https://medium.com/@aakriti.meh.2004/solving-inset-interval-problem-0a52357ff4da?source=rss-c38849a4b856------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a52357ff4da</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[dsa-problem]]></category>
            <category><![CDATA[greedy-algorithms]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Aakriti Mehrotra]]></dc:creator>
            <pubDate>Sat, 03 Jan 2026 18:27:42 GMT</pubDate>
            <atom:updated>2026-01-03T18:27:42.169Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Question:</strong> You are given an array of non-overlapping intervals intervals where intervals[i] = [starti, endi] represent the start and the end of the ith interval and intervals is sorted in ascending order by starti. You are also given an interval newInterval = [start, end] that represents the start and end of another interval.Insert newInterval into intervals such that intervals is still sorted in ascending order by starti and intervals still does not have any overlapping intervals (merge overlapping intervals if necessary).</p><p><strong>Solution:</strong></p><pre>def insertNewInterval(intervals, new_interval):<br>        res = []<br>        i = 0<br>        n = len(intervals)<br><br>        while i &lt; n and intervals[i][1] &lt; new_interval[0]:<br>            res.append(intervals[i])<br>            i += 1<br>   <br>        while i &lt; n and intervals[i][0] &lt;= new_interval[1]:<br>            new_interval[0] = min(new_interval[0], intervals[i][0])<br>            new_interval[1] = max(new_interval[1], intervals[i][1])<br>            i += 1<br>        res.append(new_interval)<br>        while i &lt; n:<br>            res.append(intervals[i])<br>            i += 1<br>        return res</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a52357ff4da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving Lemonade Change Problem]]></title>
            <link>https://medium.com/@aakriti.meh.2004/solving-lemonade-change-problem-ca212198a65e?source=rss-c38849a4b856------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca212198a65e</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[greedy-algorithms]]></category>
            <category><![CDATA[sad]]></category>
            <dc:creator><![CDATA[Aakriti Mehrotra]]></dc:creator>
            <pubDate>Fri, 02 Jan 2026 17:07:04 GMT</pubDate>
            <atom:updated>2026-01-02T17:07:04.102Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SH2fowotKgmY5Y4qGga4Vw.png" /></figure><p><strong>Question:</strong> At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer so that the net transaction is that the customer pays $5.</p><p><strong>Solution: <br></strong>For example- <br>bills = [5,5,10,10,5,20]</p><p>We make a dictionary — mp={5:0,10:0,20:0}<br>customer 1 — gives 5 : mp[5]+=1 =&gt; count of(5)=1<br>customer 2— gives 5 : mp[5]+=1 =&gt; count of(5)=2<br>customer 3— gives 10: mp[10]+=1 =&gt; count of(5)=1 and count of (10)=1 <br>customer 4— gives 10: mp[10]+=1 =&gt; count of(5)=0 and count of(10)=2<br>customer 5 — gives 5 : mp[5]+=1 =&gt; count of(5)=1 and count of(10)=2<br>customer 6 — gives 20 : mp[20]+=1 =&gt; count of(5)=0 and count of(10)=1 and count of(20)=1</p><p>Final verdict = True, can process all payments</p><pre>def lemonadeChange(bills):<br>        mp={5:0, 10:0, 20:0}<br>        for bill in bills:<br>            if bill==5:<br>                mp[5]+=1<br>            elif bill==10 :<br>                if (mp[5]&gt;=1):<br>                    mp[5]-=1<br>                    mp[10]+=1<br>                else:<br>                    return False<br>            elif bill==20 :<br>                if (mp[10]&gt;=1 and mp[5]&gt;=1):<br>                    mp[5]-=1<br>                    mp[10]-=1<br>                    mp[20]+=1<br>                elif mp[5]&gt;=3:<br>                    mp[5]-=3<br>                    mp[20]+=1<br>                else:<br>                    return False <br>        return True</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca212198a65e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving the Assign Cookies Question]]></title>
            <link>https://medium.com/@aakriti.meh.2004/solving-the-assign-cookies-question-396d264ceebf?source=rss-c38849a4b856------2</link>
            <guid isPermaLink="false">https://medium.com/p/396d264ceebf</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[sad]]></category>
            <category><![CDATA[greedy-algorithms]]></category>
            <category><![CDATA[problem-solving]]></category>
            <dc:creator><![CDATA[Aakriti Mehrotra]]></dc:creator>
            <pubDate>Thu, 01 Jan 2026 18:08:21 GMT</pubDate>
            <atom:updated>2026-01-01T18:08:21.882Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Question:</strong>What the question states is , if there are ’n’ students, and ‘m’ cookies, given as an array, now each child has a greed factor of g[i], meaning, g[i] is the minimum size of the cookie that can be given to the kid ‘i’.And, cookie, c[j] is the size of the cookie ‘j’.<br>So basically, c[j]≥g[i] for the cookie ‘j’ to be able to satisfy the child ‘i’<br>The task is to maximise the number of children who can be content with the cookies</p><p><strong>Solution:</strong></p><p><em>Example</em> : g= [1,2,3,4] c= [2,3,4]</p><p><em>Approach</em>- We sort both the arrays, greed and cookies, (in this case already sorted).<br>What we can see here is , if we take 2 pointers ‘i’ and ‘j’, i moving through array ‘g’ and j moving through array ‘c’, the first place where we encounter c[j]≥g[i], that is the index where the student’s greed can be satisfied, this way we will get maximum cookies that can be assigned</p><p><em>Pseudocode-</em></p><pre><br>function findMaximumCookieStudents(greed, cookie){<br>  n = len(greed)<br>  m = len(cookie)<br>  l, r = 0, 0<br>  greed.sort()<br>  cookie.sort()<br>  while (l &lt; n and r &lt; m) {<br>    if (cookie[r] &gt;= greed[l]){<br>      l += 1<br>    }<br>    r += 1<br>  }<br>  return l<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=396d264ceebf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>