<?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 Dishant on Medium]]></title>
        <description><![CDATA[Stories by Dishant on Medium]]></description>
        <link>https://medium.com/@shoonyam.108?source=rss-a4076e4e3df3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QxFzr2pEbXlllU39</url>
            <title>Stories by Dishant on Medium</title>
            <link>https://medium.com/@shoonyam.108?source=rss-a4076e4e3df3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:57:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shoonyam.108/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 Does Intelligent Load Managment Looks Like ?]]></title>
            <link>https://medium.com/@shoonyam.108/how-does-intelligent-load-managment-looks-like-c6fde6244dac?source=rss-a4076e4e3df3------2</link>
            <guid isPermaLink="false">https://medium.com/p/c6fde6244dac</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Dishant]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 20:11:23 GMT</pubDate>
            <atom:updated>2026-03-03T20:11:48.483Z</atom:updated>
            <content:encoded><![CDATA[<p>When Scalabiliy is not about just limiting RPS</p><h3><strong>Introduction</strong></h3><p>Millions of users all around the world use Uber, and at such scale, minor problems are not minor anymore. Make a small mistake, and that can lead to the failure of the whole system worldwide. We are talking about 170 million users, thousands of backend services running continuously and receiving millions of requests, and databases running queries at a massive scale.</p><p>What we are going to solve is the issue of overloading. After overloading, we also usually face issues with fairness among different services. What happens when a single service is facing a major traffic spike or is consuming more resources than others? This can lead to an unfair distribution of resources. Systems where such loads are not detected may never see it as an issue, but then the services using these extra resources create delays for other services. Those services were never meant to be slowed, but due to a single service, all others are suffering. This leads to an unfair distribution of resources. So we need to build a system that can offer a solution for overloading and unfairness among services.</p><h3>The 3-Layer System</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/506/1*o9X5bxwy3o2Po5WzclDVHw.png" /></figure><p>The database works in 3 layers. The first layer is the <strong>Query engine</strong>. As the name suggests, it works as the brain in terms of knowing where to access and write in this huge database. It also handles the authorization of the request. It is the intelligent part of the storage. Then we have the <strong>storage engine</strong>, which actually stores the data. Uber uses MySQL underneath it. Finally, this system needs to be preserved and managed. This is done by the <strong>Control plane</strong>, which helps in scaling the DB, monitoring health, and handling the DB ecosystem.</p><h3>Docstore &amp; Schemaless</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/896/1*6lD0lS0Iznutx7Tu6p202A.png" /></figure><p>Uber has 2 different DBs using the same architecture, just storing different data in the second layer. <strong>Docstore </strong>supports full CRUD operations and thus has the major chunk of data such as user profiles, trips, payments, etc. <strong>Schemaless </strong>contains data such as logs, events, tracking data, and metrics, just like a logbook.</p><h3><strong>Challenges</strong></h3><h4>Quota-Based Rate Limiting in the Query Engine Layer</h4><p>First, we will understand what Uber came up with earlier and then what their approach was to handle it. They gave every request a cost (based on how much data it reads/writes). Every user would have a fixed quota, and when it crossed the limit, it would show 429 Too Many Requests and store the quota usage in Redis.</p><p>There were 4 big problems because of this.</p><p><strong>Problem 1: Too Much Complexity</strong><br> The round cycle of checking Redis for quota and updating it every time led to extra latency and increased the complexity.</p><p><strong>Problem 2: Wrong Layer for Overload Detection</strong><br> Our brain doesn’t know the state of different parameters such as load and latency, which are required to make good decisions about databases.</p><p><strong>Problem 3: Cost Model Was Wrong<br></strong> The cost was based on bytes returned, not on how much compute it took to return that result. Even if it took way too much work to return 2 results with a similar number of bytes, they would be assigned the same cost.</p><p><strong>Problem 4: Static Quotas Don’t Work in Real Life<br></strong> Static quotas turned out to be useless in dynamic real-world situations. In multitenant systems, they become ineffective as quotas don’t adapt.</p><h3>The Realization</h3><p><strong>Overload management must live near the storage layer.</strong></p><p>It is like saying the brain knows how to handle a task, but the pressure it takes on the body to carry out that task is known to the body better than the brain. So if we need to manage the overall health of the system, the knowledge lies with the body and not just the brain.</p><h3>Identifying the Right Signal for Overload</h3><p>The number of <strong>queries per second</strong> (QPS) used to judge the overload of the system is similar to judging the overloading of a parking system by just the number of vehicles entering the parking lot. They can be cars, bikes, electric scooters, or pickup trucks. They are all different but will be counted as equal when they enter the parking lot.</p><p>I hope you can see where the flaw is.</p><p>We need to differentiate them based on the size they are going to occupy. 10 pickup trucks are not equal to 10 sedans or 10 bikes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/361/1*QI7j-K5qZKjfQKHXLCG5dA.png" /></figure><p>A better method is concurrency, which is:</p><p>“Number of requests currently running at the same time.”</p><p><strong>Concurrency</strong> = Throughput × Latency</p><p><strong>Throughput</strong> = how many requests per second</p><p><strong>Latency</strong> = how long each request takes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*ord_nCNXgCd_Dcs3Shm46Q.png" /></figure><p>This simply means the total load that is on the system right now, which is exactly what we wanted to measure. Now 10 big requests can’t hide from the fact that they will cause a bigger load on the system, as their concurrency will be more than several smaller requests.</p><h3>Balancing Resilience and Fairness</h3><p>So the main tasks of our backend are to be resilient and fair. If the system is being overloaded, then it should handle high-priority tasks and manage lower-priority ones accordingly. This makes the system resilient. If any one tenant is consuming a lot of resources, then that tenant should be returned with error 429 Too Many Requests. The overall system load may be fine and may not even crash because of that tenant’s behavior, but it still needs to be stopped. This situation is called the noisy neighbor problem, where one tenant asks for much more resources.</p><h3>Building the Foundation of a Unified Load Manager</h3><h4>Controlled Delay: Smarter Queuing Under Pressure</h4><p>CoDel = Controlled Delay</p><p>Instead of asking how many requests are there in the queue, it looks at how long the requests have been waiting.</p><p>So we will create 3 different queues:</p><p><strong>Read Queue</strong>: For read operations, fast lookups.<br><strong>Write Queue</strong>: For write operations, which are heavier than reads.<br><strong>Slow Queue</strong>: The heaviest tasks are sorted in this queue, such as table scans.</p><p>This gives better isolation. A slow scan won’t block fast reads.</p><h3>Adaptive LIFO</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/865/1*cOlG7FsNiHlM903zfRnI8Q.png" /></figure><p>If the queue waiting time surpasses a threshold delay, then we switch from FIFO to LIFO.</p><p><strong>But why LIFO?</strong></p><p>LIFO is better when processing new requests first and then dropping old, stale requests, making it better for fresh requests. The main idea is not to waste time on old requests and focus on new ones.</p><p>By prioritizing fresh requests:</p><ul><li>Latency improves.</li><li>Retries reduce.</li><li>The system stabilizes faster.</li></ul><h3>Scorecard Engine</h3><p>The system that protects from the noisy neighbor problem is the <strong>scorecard engine.</strong></p><p>Different kinds of tenants are provided with different limits, some more and some less according to what is required (some might get more priority since they are high-level processes). This prevents the whole system from failing just because of a single tenant.</p><p>Another way to see this is that it helps in reducing the blast radius significantly, since it will stop the overloading of different services before it translates into a whole system disaster.</p><h3>Regulators</h3><p>Overload can sometimes be more “hidden” than what we might think it would look like. Sometimes, even when being within usage limits, things can go pretty bad. The requests may cause too much disk usage, memory usage, or too much thread usage while being under the request limit. So to detect and regulate them early on, we use regulators.</p><p>There are 4 kinds of regulators.</p><ol><li><strong>Write Bytes Regulator</strong>: When fewer requests cause massive payloads and can cause disk I/O saturation.</li><li><strong>Partition Key Regulator</strong>: When too many requests target the same key and one shard is targeted while others are idle. The PK regulator cuts off traffic if something like that ever happens.</li><li><strong>Memory Regulator</strong>: When the requests lead to low memory, causing an out-of-memory crash.</li><li><strong>Goroutines Regulator</strong>: (Goroutines = lightweight threads in Go.) When too many goroutines overload the thread scheduler, this regulator ensures that never happens.</li></ol><h3>The Simpler picture</h3><p>The whole system can be defined by 4 major pillars</p><p><strong>Concurrency-based detection</strong> : detects system pressure.</p><p><strong>CoDel queues</strong> : manage request delay smartly.</p><p><strong>Scorecard</strong> : per-tenant fairness.</p><p><strong>Regulators</strong> : protect specific resources (I/O, memory, hot keys, threads).</p><h3>Limitations</h3><h4><strong>CoDel Treated All Requests the Same</strong></h4><p>CoDel had no memory of request priority. It could only see every request as equally important, which might seem fair but not during times of disaster when we need the system to handle critical tasks and not treat every action equally. No priority led to essential services being dropped, impacting the overall performance of the application.</p><h4><strong>Static Limits Don’t Work in Dynamic Systems</strong></h4><p>Static limits turned out to be a disaster in real-world systems as they needed to be changed based on requirements. Constant manual tuning led to more interference instead of handling it automatically.</p><h4><strong>Thundering Herd Problem</strong></h4><p>Many requests are retried automatically, assuming that they might not have worked properly the first time. This leads to overloading of the system again, as the requests we denied the first time queue themselves again. This creates a repeating cycle and is called the “Thundering Herd Problem.”</p><h4><strong>Blast Radius Increased</strong></h4><p>Since no priority was given, high-priority tasks were also denied, leading to a halt in processes that were really important for the application to run. Users who needed to perform high-priority tasks such as payments would be stuck, leading to a bad experience for both drivers and customers.</p><h3>Evolving the Architecture</h3><h4>Cinnamon Replaces CoDel</h4><p>Cinnamon was a priority-aware load shedder. Let me explain how it works and how it was better than CoDel.</p><p>The requests were prioritized using notations such as t0, t1, t2… t5, with t0 being the highest priority and t5 being the lowest. So during overload, the pool of requests that were going to be dropped was not just any request from the whole pool, but rather those requests that were lower in priority. Only when they were denied would we move to higher-priority queues to remove requests. This protected high-priority requests from getting denied, such as<strong> ride requests, real-time pricing</strong>, and <strong>payments</strong>. Now there were just a read queue and a write queue, since long-running operations were simply marked as low priority. Now the system was more stable and aware of the resources being used by the application.</p><h3>Lessons Learned</h3><ul><li><strong>Prioritization is paramount</strong>. Effective load-shedding starts with deciding what matters most. Protect critical, user-facing traffic first. Everything else is secondary.</li><li><strong>Fail fast, don’t block</strong>. Rejecting early is almost always better than holding requests in memory until they expire. It reduces wasted work, keeps latencies predictable, prevents OOMs, and makes the system more resilient under stress.</li><li><strong>PID regulation for stable shedding</strong>. Simple, reactive shedding based solely on current error rates often causes instability, overcorrecting too late, and too hard. PID based regulation brings balance by incorporating system history and directional trends, making it a critical tool for smooth, sustained, and resilient overload control.</li><li><strong>Place control close to the source of truth</strong>. The best shedding decisions happen where the state lives. Protection in the layer that has full context, typically the storage layer in stateful systems.</li><li><strong>Embrace dynamism</strong>. Avoid static configurations wherever possible. Your system should be intelligent enough to adapt to different scenarios, based on the context.</li><li><strong>Invest in visibility and monitoring</strong>. Good observability is the foundation for tuning and trust. Track what’s being shed, why it’s being shed, and how each component contributes to system pressure.</li><li><strong>Simplicity over complexity</strong>. This is a meta principle that guides all the other decisions.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c6fde6244dac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Surviving the 300,000 Request Spike: How I Built a Self-Healing Rate Limiter]]></title>
            <link>https://medium.com/@shoonyam.108/surviving-the-300-000-request-spike-how-i-built-a-self-healing-rate-limiter-2432e54a36ff?source=rss-a4076e4e3df3------2</link>
            <guid isPermaLink="false">https://medium.com/p/2432e54a36ff</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[backend-development]]></category>
            <dc:creator><![CDATA[Dishant]]></dc:creator>
            <pubDate>Fri, 20 Feb 2026 08:37:00 GMT</pubDate>
            <atom:updated>2026-02-20T08:37:00.350Z</atom:updated>
            <content:encoded><![CDATA[<h4>The “Self-DDoS” Paradox</h4><p>Most developers think their Rate Limiter protects their database. The truth? At 30,000 requests per second, a traditional Token Bucket doesn’t protect your system <strong>it kills it</strong>. While your “precise” Redis script is busy counting raindrops, the network round-trips are saturating your CPU and self-inflicting a DDoS on your own infrastructure. I built <strong>MeshShield</strong> to solve this, a three-tier adaptive architecture that swaps expensive stateful “counting” for a high-speed probabilistic “squeeze,” allowing my system to touch <strong>55,000 RPS</strong> with a <strong>1ms P99 latency</strong> while the industry standards were still waiting for a Redis response.</p><h4>Previous Architecture</h4><p>The foundational architecture of modern rate limiting is the <strong>Token Bucket</strong> algorithm, typically powered by <strong>Redis</strong>. It is designed for surgical precision during “Peace-Time” traffic when everything feels fine. For every incoming request, the server performs a lookup in Redis to ask: <em>“Does this bucket have a token left?”</em>. If the count is greater than zero, the server decrements it by one and allows the request to pass. Tokens are then automatically replenished at a fixed interval to ensure a steady, predictable quota.</p><p>To ensure this works at scale, we must solve the <strong>Race Condition</strong>. If two requests hit the server at the exact same microsecond, they might both see “1 token left” and both proceed, effectively bypassing your limit. To prevent this, we encapsulate the <strong>Lookup and Decrement</strong> logic into a single <strong>Atomic Action</strong>. By using <strong>Lua scripts</strong> executed directly on the Redis server, we ensure that these two steps happen as one inseparable unit, guaranteeing 100% accuracy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/835/1*_jBD1JKojoVvsH8-3zA68A.png" /><figcaption>Fig : Redis Refil logic</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*NOs3OOEuWF8oG4NrMUCReQ.png" /><figcaption>Fig : Redis lookup logic</figcaption></figure><h4>The Token Bucket Architecture</h4><p>As the <strong>RPS</strong> (Requests Per Second) increases, the system begins to suffocate under its own rules. Because the Token Bucket requires a lookup for <strong>every single request</strong>, the Gateway is forced into a constant loop of querying Redis and waiting for a response.</p><p>At an “insane” scale like <strong>30,000</strong> requests per second this round-trip becomes an expensive tax on the system’s resources. The CPU spends more time managing network sockets and waiting for I/O than it does processing actual data. Eventually, the rate limiter begins to lag, but not because the server is overloaded with work it’s lagging because of the sheer volume of <strong>Redis checks</strong>.</p><p><strong>The Irony</strong>: The tool you built to protect your database is now the very thing causing your system to crash.</p><h4>The Culprit: Round-Trip Latency</h4><p>The main reason for this failure is the requirement for <strong>Global Synchronicity</strong>. In a high-traffic storm, trying to maintain a perfectly accurate count across a distributed system is a death sentence. The round-trip for every request at that scale creates a “clog” in the pipes. By the time Redis answers one request, ten more have arrived, leading to a cascading failure where the protector becomes the bottleneck. To survive, we have to stop asking for permission and start making autonomous decisions at the edge.</p><h4>What Failure Looks Like: The “Self-Inflicted” DDoS</h4><p>In a high-intensity surge, the Token Bucket doesn’t just “stop” traffic; it jams the gears of the entire machine.</p><ul><li><strong>CPU Paralysis</strong>: The CPU halts because it is buried under a mountain of Redis requests. The compute required to manage tens of thousands of simultaneous I/O operations is so high that there is nothing left for the actual application logic, effectively jamming the whole system.</li><li><strong>Resource Exhaustion</strong>: Every time the Gateway talks to Redis, it consumes a <strong>Network Socket</strong> and a slice of <strong>Memory</strong>. At 30k+ RPS, this leads to an immediate exhaustion of available ports and memory. This prevents your server from doing anything else it can’t talk to your database, it can’t fetch other APIs, and it can’t even respond to health checks.</li><li><strong>The Chain Reaction</strong>: Because the Token Bucket is hammering Redis with “Check-and-Decrement” Lua scripts, Redis becomes slow for everyone. Your rate limiter has effectively self-DDoS’d your entire infrastructure.</li><li><strong>The Result</strong>: Users who aren’t even being rate-limited (like those trying to log in) find themselves locked out because the shared session store in Redis is timing out under the weight of the rate-limit checks.</li></ul><h4>The Reality of the Token Bucket</h4><p>We often prioritize “fairness” in our algorithms, but in the middle of a DDoS or a massive spike, fairness doesn’t matter; survival does.</p><p>“So, how do the giants like Uber or Netflix handle these ‘Tsunami’ moments? When you have millions of users, a 10% traffic spike can be larger than the entire capacity of a smaller startup. They don’t survive by trying to count every single ‘raindrop’ in the hurricane; they survive by embracing a principle called Graceful Degradation.</p><p>They realize that in a crisis, availability is better than accuracy.</p><p>Instead of letting the entire system ‘redline’ and crash leaving 100% of users in the dark they use Adaptive Control Loops. They intentionally ‘squeeze’ the traffic, sacrificing a portion of the requests to ensure the core infrastructure remains stable. It’s a calculated trade-off: I would rather serve 5,000 users perfectly and reject the other 25,000, than try to serve everyone and have the entire system ‘die’ for all 30,000.</p><p>But how do you build a system that knows exactly when to ‘squeeze’ and by how much? You stop looking at your Gateway as a simple guard and start looking at it as part of a Distributed Mesh.”</p><h4>The Architecture</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*Q6-NCvVDymcXouZKggtMyQ.png" /></figure><h4>1. The Clients (Edge Gateways)</h4><p>At the bottom tier, we have the Clients (which, in our case, are the API Gateways). These are the front-line soldiers stationed at the edge of your network.</p><ul><li><strong>Role</strong>: They process every single incoming request from users.</li><li><strong>Duty</strong>: They enforce the current rate-limiting strategy (like our Token Bucket or GRL) and track traffic metrics in real-time.</li><li><strong>Telemetry</strong>: Instead of calling a global database for every hit, they send periodic “heartbeats” of their traffic data upward to the next layer.</li></ul><h4>2. The Aggregators (Zone Level)</h4><p>The middle tier consists of Aggregators, typically organized by Zones (e.g., Zone A for East Coast, Zone B for West Coast).</p><ul><li><strong>Role</strong>: They act as “regional managers.” They collect the rapid-fire telemetry from all the Clients in their specific zone.</li><li><strong>Summarization</strong>: By summing up the traffic from hundreds of gateways into a single regional report, they drastically reduce the amount of data that needs to reach the “Brain.”</li><li><strong>Buffer</strong>: They provide a layer of resilience; if the Global Controller is momentarily slow, the Aggregators can still provide regional stability.</li></ul><h4><strong>3. The Global/Regional Controller (The Brain)</strong></h4><p>At the very top sits the Global/Regional Rate Limiter Controller. This is the central intelligence of the entire operation.</p><ul><li><strong>Role</strong>: It looks at the aggregated data from every zone to get a “God’s Eye View” of the entire network’s health.</li><li><strong>The Decision Maker</strong>: If it sees that Zone A is under a DDoS attack while Zone B is quiet, it can dynamically calculate a unique dropRatio for each region.</li><li><strong>Broadcast</strong>: It pushes the new “Game Plan” (the updated configuration) back down through the Aggregators to the Clients, closing the feedback loop.</li></ul><h4><strong>What is Drop ratio ?</strong></h4><p>In very simple terms, the Drop Ratio is a volume knob for your incoming traffic. It tells the system what percentage of people to “drop” (reject) at the door to keep the server from crashing.</p><p>Think of it like a crowded club with a maximum capacity:</p><ul><li><strong>Drop Ratio = 0 (0%):</strong> The club is empty. Everyone is allowed in.</li><li><strong>Drop Ratio = 0.5 (50%)</strong>: The club is getting full. The bouncer flips a coin for every person in line; “Heads” you come in, “Tails” you stay out.</li><li><strong>Drop Ratio = 0.9 (90%): </strong>The club is at a breaking point. The bouncer only lets 1 out of every 10 people in.</li></ul><h4><strong>The “Squeeze” Formula</strong></h4><p>Your system (the “Brain”) calculates this number automatically based on how much the traffic exceeds your limit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*zMT6ZRiJHjnw4Q2mIogSdA.png" /></figure><h4>The Flow of GRL (Refined)</h4><p>The story begins when systems are working peacefully; the <strong>RPS </strong>(Requests Per Second) are well under the limit, and everything is running smoothly. But suddenly, traffic sees a massive spike due to an unknown or perhaps very well-known event. This creates a situation where we know our traditional <strong>Token Bucket</strong> method will struggle, or even crash the underlying state-store. To handle this, we switch to the<strong> GRL (Global Rate Limiting)</strong> system to come to our rescue.</p><p>In this architecture, the <strong>Clients</strong> (our API Gateways) act as <strong>Sensors</strong>. They pick up the real-time changes in the environment, specifically the surge in requests loading the server. This telemetry is then sent to Aggregators, which combine the data to show the collective load on the entire Zone before passing it to the <strong>Global Controller</strong>.</p><p>The <strong>Controller </strong>then dynamically calculates a <strong>Drop Ratio </strong>for the system. This ratio defines how much the traffic needs to be “squeezed” to stabilize the infrastructure. For example, if the ratio is set to 0.5, it means the global load must be reduced to <strong>50%</strong> of its current volume.</p><p>In simpler terms, we are going to allow just a few “lucky” requests (and yes, it really is a game of probability) to pass through to the backend. Because this logic is applied at the edge, the load is shared by the whole system globally, ensuring that no single service is completely compromised during rough times. The system stays alive for that lucky 50%, achieving exactly what we wanted: a resilient, fair system that allows the infrastructure to face the load “fair and square” rather than collapsing entirely.</p><h4>How the “Game of Luck” Works</h4><p>In a traditional system, you are essentially waiting for a “yes/no” from a central database (Redis). In <strong>GRL</strong>, the Gateway makes its own destiny using a <strong>Probabilistic Filter</strong>.</p><h4>The Logic</h4><p>For every single incoming request, the Gateway executes a simple, local check:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*eeRbKCltyEDEYObMzbtibA.png" /></figure><h4>Why this is “Insanely” Efficient</h4><ul><li><strong>Zero Latency</strong>: Fetching from Redis takes milliseconds (10^{-3} seconds). Generating a random number takes nanoseconds (10^{-9} seconds). You are making the decision 1,000,000 times faster.</li><li><strong>Zero Memory</strong>: You don’t need to store “tokens” or “counts” for every user. The Gateway doesn’t need to remember the last request; it just looks at the current one and flips the coin.</li><li><strong>The Law of Large Numbers</strong>: While it’s “luck” for one request, over 30,000 requests, the math is incredibly precise. If the Drop Ratio is 0.7, you are guaranteed that almost exactly 30% of traffic will get through, protecting your backend with mathematical certainty.</li></ul><h4>THE RESULTS</h4><h4>GRL</h4><p>Lets talk about what we did in our project and what were our observations, and what does the numbers say about this architecture to keep the system alive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*wK8_Ltyg9S0yEujCBPhA-w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*Zalhye2qBQzNmvmUZKdqvA.png" /></figure><h4>The High-Level Proof</h4><p>Our test successfully pushed the system to its limits, handling over <strong>211,000</strong> requests in just<strong> 10 seconds</strong>. While a standard Token Bucket would have likely crashed under the weight of these Redis checks, our adaptive system stayed alive and healthy.</p><p><strong>Total Traffic Handled</strong> : 211,000 requests<br><strong>Peak Throughput</strong> : 53,397 RPS<br><strong>Average Latency</strong> : 0.07 ms<br><strong>System Stability</strong> : HEALTHY (immediately after spike)</p><h4>Analysis of the “Squeeze”</h4><p>The GRL logs show exactly how the adaptive control loop protected your infrastructure in real-time:</p><ul><li><strong>Phase 1</strong>: Detecting the Surge: When traffic jumped from 1,565 RPS to 23,333 RPS (surpassing your 22,000 limit), the Brain immediately transitioned from “Healthy” to “SQUEEZING”.</li><li><strong>Phase 2</strong>: The Adaptive Squeeze: As traffic peaked at an insane 53,397 RPS, the Brain dynamically calculated a 59% Drop Ratio. This means it was shedding 59% of the traffic at the edge to protect your core services.</li><li><strong>Phase 3</strong>: Smooth Recovery: As soon as the traffic dropped back to 13,094 RPS, the Brain automatically reset the Drop Ratio to 0%, returning the system to a “HEALTHY” state within one second.</li></ul><h4>Token Bucket</h4><p>When we forced the system to operate strictly using the Token Bucket algorithm under a high-intensity surge, the data revealed the “hidden ceiling” of stateful rate limiting. Without the adaptive “Squeeze” to protect the infrastructure, we witnessed a classic case of Resource Saturation.</p><h4>The Data: Token Bucket Under Stress</h4><p>In this run, the Brain logged “HEALTHY” even at massive traffic volumes because the adaptive logic was disabled. However, the performance metrics tell a different story of a system struggling to breathe:</p><ul><li><strong>Total Requests Attempted</strong>: 165,000 in 11.02 seconds.</li><li><strong>Peak Throughput</strong>: Capped at 18,015 RPS (97.5th percentile).</li><li><strong>Average Throughput</strong>: 15,024 RPS.</li><li><strong>Success Rate</strong>: 122,332 (2xx) out of 165k attempts.</li><li><strong>Latency</strong>: 0.08 ms average, with a Max spike of 20 ms.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*RuvbDDHhoOUDuQ80R5c2AQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/628/1*lJ5Fc4SFxh5P3LTwGHmg7g.png" /></figure><h4><strong>Analysis: Why the System Capped</strong></h4><h4>1. The “Redis Tax” Bottleneck</h4><p>The most striking observation is that while the test was designed to push 30k–50k RPS, the Token Bucket could only “see” and process 15,024 RPS on average. This is the Network I/O Ceiling. Because every single request required a round-trip to Redis to execute a Lua script, the Gateway’s connection pool became a bottleneck. The system was physically incapable of asking for permission any faster than the network and Redis could respond.</p><h4>2. Artificial Throughput Limit</h4><p>Notice that in the adaptive GRL test, we reached 53,397 RPS. In the Token Bucket test, we struggled to hit 18,000 RPS. The system wasn’t “full” of user data; it was “full” of rate-limiting checks. The compute power was being wasted on bookkeeping (checking tokens) rather than processing traffic.</p><h4>3. The Self-Inflicted Load</h4><p>By attempting to maintain 100% precision during a storm, the system performed 165,000 atomic operations in 11 seconds. This is an enormous amount of stress to place on a shared state-store (Redis). In a production environment, this behavior often slows down other critical services like session management or database caching, leading to a total site outage.</p><h4>Latency : The “Squeeze” vs. The “Clog”</h4><p>At first glance, 36ms looks “worse” than 20ms. However, you have to look at what the system was doing at that exact moment.</p><h4>1. Handling the “Un-Handled” (53k RPS vs 15k RPS)</h4><ul><li><strong>Token Bucket</strong>: The system never reached 53,000 RPS. It was “clogged” at 15,000 RPS. Because the “pipes” were already full, it simply couldn’t accept any more requests to even process them. It’s easy to have lower max latency when you are doing <strong>3x less work.</strong></li><li><strong>GRL</strong>: Your system was processing a massive flood of <strong>53,397 requests every second</strong>. When you push that much data through a single Node.js event loop, you get minor “micro-bursts” where the CPU is momentarily busy calculating the drop logic for thousands of requests at once.</li></ul><h4><strong>2. The Cost of the “Decision”</strong></h4><p>In the Token Bucket test, the system was consistent because it was consistently slow. In the GRL test, the 36ms spike likely happened at the exact millisecond the Brain sent the “SQUEEZE” command.</p><ul><li>For a split second, the Gateway has to receive the new configuration, update its internal state, and start dropping traffic.</li><li>That 36ms is the “<strong>reaction time</strong>” of the system adjusting to a massive Tsunami.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/523/1*796mX3ZPntF5T5_ljy8hEw.png" /></figure><p><strong>The Analysis</strong>: The fact that our <strong>P99 </strong>is still <strong>1ms</strong> means that for <strong>99%</strong> of our users, the experience was identical or better than the Token Bucket, even though we were handling triple the traffic. The 36ms is an “outlier” a single request that got caught in a momentary CPU spike while the system was busy saving itself.</p><h4><strong>Comparison</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*1guL3_h4BzXrmMi9rCBhtg.png" /></figure><h4>Some other results with different Global limits</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*a5A-iVRKlWvUv680bMb0dw.png" /><figcaption>Figure : Global Limit is 27000 RPS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*Q1YpHt679_XuX3jI0Q18lw.png" /><figcaption>Figure : Global Limit is 30000 RPS</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*Q3FfcSbyfr34hr2zIPpQXg.png" /><figcaption>Figure : Global Limit is 27860 RPS</figcaption></figure><h4>Final Conclusion: Surviving the Tsunami</h4><p>The primary goal of this project was to build a system capable of surviving extreme peak traffic that would paralyze traditional infrastructures. Through our testing, we proved that while standard Token Bucket methods are precise, they are fundamentally limited by the “Redis Tax”. In a production environment, those traditional methods would have capped at a much lower RPS, causing the system to clog, latency to spiral, and the application to eventually crash under its own weight.</p><p>By implementing Global Rate Limiting (GRL), we moved away from that rigid ceiling. We created a dynamic defense mechanism that doesn’t just “fail” when it’s overwhelmed it adapts.</p><h4>Key Takeaways:</h4><ul><li><strong>Dynamic Management</strong>: Instead of a hard crash, our system managed traffic dynamically, identifying spikes and “squeezing” the load to protect core services.</li><li><strong>Infrastructure Preservation</strong>: By offloading the “decision” to a global controller and the “enforcement” to local gateways, we touched peaks of 55,270 RPS without saturating our state-store.</li><li><strong>Strategic Survival</strong>: This is the same strategy used by massive systems like Uber and Netflix. It acknowledges a hard truth: in a crisis, total failure is unacceptable. It is far better to proceed with the “lucky ones” who survive the squeeze than to let the entire application die for 100% of your users.</li></ul><p>Ultimately, GRL proves that modern rate limiting isn’t about counting requests it’s about managing capacity fair and square, ensuring that even in the worst of times, the system stays standing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2432e54a36ff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What if every drink you had made you a little less you?]]></title>
            <link>https://medium.com/@shoonyam.108/what-if-every-drink-you-had-made-you-a-little-less-you-1231960c4702?source=rss-a4076e4e3df3------2</link>
            <guid isPermaLink="false">https://medium.com/p/1231960c4702</guid>
            <category><![CDATA[memory-loss]]></category>
            <category><![CDATA[who]]></category>
            <category><![CDATA[brain-health]]></category>
            <category><![CDATA[alcohol]]></category>
            <category><![CDATA[health]]></category>
            <dc:creator><![CDATA[Dishant]]></dc:creator>
            <pubDate>Wed, 02 Jul 2025 05:28:10 GMT</pubDate>
            <atom:updated>2025-07-02T05:28:10.655Z</atom:updated>
            <content:encoded><![CDATA[<h3>What if every drink you had made you a little less you? The science behind memory loss, WHO’s warning, and the silent link to Alzheimer’s.</h3><h3>If WHO admits confusion on safe limits, maybe we should too</h3><p>One of the many things which surprised me was that <strong>WHO</strong> can’t decide what can be a safe limit to drink alcohol, and before you start your backlash on <strong>WHO</strong> regarding their standards being pretty much on the unrealistic side and too good for most people, I think it’s really not something they haven’t tried hard to figure out, considering how big a problem it is for society. Even a small number could have done justice to the subject, like Ohh, you can have such low amounts and you’re good taking alcohol, but straight up saying there’s no possible way to justify any amount of alcohol as bearable is kind of a thing to wonder about.</p><h3>INTRODUCTION</h3><p>Alcohol is actually <strong>ethanol</strong> (a chemical compound), which breaks into <strong>acetaldehyde</strong> in our body. This is considered a<strong> Group 1 carcinogen</strong> by the International Agency for Research on Cancer. It can damage DNA and interfere with its repair mechanisms, <br>Well, the liver then further breaks it down into <strong>acetate</strong>, which is harmless, until your liver is not damaged by the effects of acetaldehyde.</p><p>Light alcohols include wine, rice wine, apple cider, beer, chicha, and toddy, with alcohol content ranging from <strong>4% to 18%</strong>. Distill them, and you get hard alcohols such as tequila, whisky, rum, vodka, and brandy, ranging from <strong>35% to 80%</strong> Alcohol content.</p><h3>Interesting Facts</h3><p>I’m not gonna talk about the stages of liver damage to the point where it gets hard as a rock, but here are a few interesting facts which I think should have a look:</p><ol><li><strong>Blackouts</strong> hamper those regions of the brain which form long term memory. So, you will tend to forget your best possible memory of your life. In broader terms, you are losing yourself, because I think these memories have a huge impact on you as a person and the more you lose them, a part of you is literally dying.</li><li>It can <strong>literally</strong> change your DNA( Cancer and Alzheimer)</li><li>It can kill you in one session <strong>YES!</strong> just after a few hours of drinking. A 2024 study noted this can occur in <strong>healthy individuals</strong> after binge drinking, increasing <strong>stroke</strong> risk. This is a hidden danger, as most associate alcohol with long term heart issues, not immediate effects after one night out( We all have noticed a sudden rise in cases of strokes in recent years).</li><li>The pancreas, at a stage, starts to <strong>digest itself</strong> as a side effect of drinking alcohol.</li><li>The <strong>Red wine</strong> myth that it is good for health. Well, the antioxidants it provides are in no way adjusting for the cons of drinking it.</li><li><strong>Women</strong> face higher risks due to lower alcohol dehydrogenase levels, higher body fat, and smaller size, leading to higher blood alcohol concentrations.</li><li><strong>4.7% </strong>of deaths worldwide are from alcohol.</li><li>Studies show<strong> 20% to 68%</strong> of suicide victims had alcohol use disorder, particularly among<strong> males,</strong> linking it to increased suicide risk.</li><li>Some heavy drinkers experience olfactory <strong>hallucinations</strong>, smelling things that aren’t there, due to alcohol’s impact on the brain’s olfactory cortex.10.</li><li><strong>45%</strong> of accidents are drunk driving cases and makes the majority for the deaths in these cases. which means in case you let yourself into such an accident, you are most likely going to either die or kill another person.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1231960c4702" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hidden Genius Behind Your Everyday Products: From Cotton Fields to AI]]></title>
            <link>https://medium.com/@shoonyam.108/the-hidden-genius-behind-your-everyday-products-from-cotton-fields-to-ai-20b1a889d6f4?source=rss-a4076e4e3df3------2</link>
            <guid isPermaLink="false">https://medium.com/p/20b1a889d6f4</guid>
            <dc:creator><![CDATA[Dishant]]></dc:creator>
            <pubDate>Sun, 15 Jun 2025 03:39:48 GMT</pubDate>
            <atom:updated>2025-06-15T03:39:48.512Z</atom:updated>
            <content:encoded><![CDATA[<p>Every day, we surround ourselves with products that shape our lives — smartphones, air conditioners, clothing, and beyond. These items, often tied to recognizable brands, are more than mere objects. Beneath their sleek designs or simple fabrics lies a tapestry of innovation, engineering, and human ingenuity spanning centuries. When you buy a product, you’re not just exchanging money for an item; you’re investing in the collective intelligence that brought it into existence. From the cotton fields to the algorithms driving your shopping apps, the journey of every product reveals intricate systems designed to simplify your life. Let’s dive into this complexity with a familiar example: a t-shirt purchased online.</p><h3>The Layers of Convenience</h3><p>Picture a t-shirt you recently ordered from an e-commerce platform. At its core, your interaction involves two elements: the app you used to shop and the t-shirt itself. Each is a testament to modern engineering and logistics, working together to deliver convenience.</p><p>The app, often backed by a retail giant, is a technological marvel. It manages millions of products, from clothing to electronics, storing vast amounts of data about sizes, colors, and availability. It updates inventory in real time, processes your payment securely, and coordinates with warehouses and delivery services to get your t-shirt to your doorstep. Behind this smooth experience are cloud servers, machine learning algorithms, and teams of developers ensuring the system doesn’t falter. The company balances customer satisfaction with profitability, paying employees and maintaining operations — all without you needing to think about it. This invisible orchestration is what makes online shopping feel effortless.</p><p>Then there’s the t-shirt itself, which begins its journey far from your closet. It starts in cotton fields, where farmers cultivate raw materials under unpredictable weather and market conditions. The cotton is harvested, ginned to remove seeds, and sent to textile factories. There, it’s spun into thread, woven into fabric, dyed, and sewn into the final product. These factories churn out thousands of garments daily, each requiring precision to meet quality standards. The t-shirt then travels to warehouses or retail stores, where it’s either boxed for online orders or displayed on racks. Every step involves workers, machinery, and logistical decisions, all culminating in the moment you click “buy.”</p><h3>The Cost of Convenience</h3><p>The price tag on your t-shirt reflects more than just cotton and labor. It accounts for the entire production chain, from farming to delivery, plus the innovation that makes it possible. Consumers, however, are unpredictable buyers. Unlike businesses that purchase in bulk with long-term agreements, individuals shop based on personal needs, trends, or impulses. This makes selling to consumers riskier for brands. A retailer might reorder from a manufacturer if the product sells well, but if customers reject it, the brand’s reputation suffers — not the factory workers or delivery drivers. This risk explains why brands often command higher profit margins; they bear the weight of public scrutiny.</p><p>The reward for navigating this risk is brand value. A well-made product builds trust, encouraging repeat purchases and fostering loyalty. But a single misstep — poor stitching, delayed shipping — can damage a brand’s image. This pressure drives companies to prioritize quality, innovation, and customer experience, ensuring their products stand out in a competitive market. For example, a brand like Patagonia invests in sustainable materials, knowing that eco-conscious consumers value transparency and ethics alongside quality.</p><h3>The DIY Myth and the Power of Collaboration</h3><p>In college, the “Do It Yourself” (DIY) narrative is often championed. Learning to code, sew, or build something from scratch is empowering and valuable. But the products we rely on daily aren’t the work of solitary creators. They’re the result of collaboration across disciplines and continents. Take your smartphone: material scientists develop durable screens, software engineers craft intuitive interfaces, and logistics experts ensure global distribution. No single person could master all these skills or produce such a device alone. The real magic of modern products lies in orchestrated teamwork, where diverse talents unite to achieve something greater than any individual effort.</p><h3>Hype vs. Substance</h3><p>Marketing is a powerful tool for shaping how we view products. A viral TikTok campaign or a celebrity endorsement can spark excitement for a new sneaker or gadget. But hype is fleeting. A product must deliver real value — whether through durability, functionality, or style — to retain customers. Relying solely on marketing is a shaky strategy; it might draw attention initially, but it won’t sustain a brand. Consider the rise and fall of certain tech startups that promised revolutionary products but failed to deliver. Smart brands balance promotion with substance, knowing that a great product outshines any ad campaign over time.</p><h3>How Brands Turn Complexity into Convenience (and Why AI Matters)</h3><p>This brings us to artificial intelligence (AI), a tool reshaping how businesses create and deliver products. AI acts as a “wrapper,” streamlining complex processes and boosting efficiency. It serves two critical roles in the world of products and brands, transforming both the back end and the front end of operations.</p><p>First, AI simplifies repetitive, monotonous tasks. In warehouses, AI-powered robots sort packages and optimize storage, reducing errors and speeding up fulfillment. In customer service, chatbots handle routine questions like tracking orders, freeing human agents for more complex issues. This efficiency lowers costs, allowing companies to offer competitive prices. However, for workers in roles involving simple, repetitive tasks, AI poses a challenge. These jobs are at risk, not because humans lack ability but because AI performs them more consistently and cheaply. For instance, automated checkout systems in retail stores have reduced the need for cashiers, shifting the labor landscape.</p><p>Second, AI empowers professionals at higher levels. For managers, designers, or marketers, AI is a force multiplier. It analyzes vast datasets to predict trends, personalize customer experiences, or optimize supply chains. A marketing team might use AI to study consumer behavior, crafting campaigns that resonate with specific audiences. A product designer could leverage AI to simulate prototypes, saving time and resources. These tools don’t replace skilled workers; they enhance their capabilities, enabling them to achieve more in less time. This makes them more valuable in their fields, as they can focus on creativity and strategy rather than repetitive tasks.</p><h3>The Market Rewards the Product</h3><p>At the end of the day, consumers judge products based on results, not the tools used to make them. Whether a t-shirt was sewn by hand or a smartphone was designed with AI assistance, people care about quality, utility, and convenience. Businesses are celebrated for exceptional design and functionality, not for the layers of complexity behind the scenes. AI is just one of those layers, alongside manufacturing, logistics, and marketing. Most customers don’t think about these processes — they just want a product that works.</p><p>When AI is used effectively, it can enhance a brand’s reputation. For example, recommendation algorithms on platforms like Amazon or Netflix suggest products or shows tailored to your preferences, making your experience more enjoyable. These systems don’t overshadow the product; they elevate it by removing friction. As AI continues to integrate into business operations, it’s likely to earn public appreciation for enabling faster, better products — though it will remain one of many tools in the intricate dance of delivering convenience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20b1a889d6f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>