<?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 Ram Kashigari on Medium]]></title>
        <description><![CDATA[Stories by Ram Kashigari on Medium]]></description>
        <link>https://medium.com/@janakiramsharmak?source=rss-170025a2e9b1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*xD_1hlkofEIf4mXE</url>
            <title>Stories by Ram Kashigari on Medium</title>
            <link>https://medium.com/@janakiramsharmak?source=rss-170025a2e9b1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:44:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@janakiramsharmak/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[Unique Identifier generator: End-to-End System Design]]></title>
            <link>https://medium.com/@janakiramsharmak/unique-identifier-generator-end-to-end-system-design-0fc7ab96e7c4?source=rss-170025a2e9b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/0fc7ab96e7c4</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[amazon]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[design-systems]]></category>
            <dc:creator><![CDATA[Ram Kashigari]]></dc:creator>
            <pubDate>Fri, 04 Jul 2025 07:09:52 GMT</pubDate>
            <atom:updated>2025-07-04T07:09:52.195Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J6PntUl0F3LTOd_mAFmohw.png" /></figure><p>In today’s digital era, where millions of users interact with applications in real time, the ability to generate <strong>unique identifiers</strong> quickly, reliably, and at scale is a foundational need. Whether it’s tagging users, tracking orders, or managing distributed resources, unique IDs power the core logic of modern systems — from platforms like Instagram to microservice-based architectures.</p><p>In this article, we’ll walk through the design of a basic unique Id generation system, which can be extended to generate large Unique Ids. We’ll also break down key trade-offs across <strong>latency, consistency, and scalability</strong>, and highlight how design decisions vary depending on the use case. By the end, you’ll have a practical roadmap for building production-ready ID generation systems in distributed environments.</p><p>Since the problem is often posed in a generic way — “Design a Unique ID Generator” — without clear constraints, we’ll start by anchoring our discussion around the <strong>most common and foundational use case</strong>:</p><blockquote><strong>Generating unique identifiers to represent users within a system.</strong></blockquote><p>This use case allows us to explore the core principles and building blocks of ID generation, such as <strong>uniqueness, ordering, scalability, fault tolerance, and performance</strong>. And importantly, the architecture we develop can be <strong>adapted and extended</strong> to other scenarios — such as generating tokens to access protected resources, transaction IDs, file references, or any other entity that needs to be uniquely identified across distributed systems.</p><h3>High Level Design:</h3><p>Whenever we are trying to solve a system design question, before even jumping in to the solution, the first step is always to ask the right set of questions in including system priorities, functional and non-functional requirements. This helps us in choosing the right set of tools and technologies to build our system.</p><p><strong>Is our priority:</strong></p><ul><li><strong>Latency?</strong> (We want the ID fast)</li><li><strong>Consistency?</strong> (We must never generate duplicates, even under failure)</li></ul><p>Depending on the answer, your stack and trade-offs will differ.</p><p>Okay for now, Let’s assume we need to build a <strong>globally distributed Unique ID Generator</strong> for users that prioritizes <strong>scalability and low latency</strong>. Here’s how I would approach it:</p><h4>1. Stateless ID Generation Service</h4><ul><li>Deploy multiple instances of the ID generator across regions.</li><li>Route traffic through a <strong>Load Balancer</strong>.</li><li>Each service instance is responsible for generating IDs without needing to query a database.</li></ul><h4>2. Storage Strategy Based on Priorities</h4><ol><li>If <strong>latency</strong> is the priority:</li></ol><ul><li>Use a <strong>NoSQL database</strong> (e.g., MongoDB or DynamoDB) to store user-ID mappings.</li><li>Leverage built-in features like <strong>sharding</strong> and high availability.</li></ul><p>2. If <strong>consistency</strong> is key:</p><ul><li>Use a <strong>relational SQL database</strong> (e.g., PostgreSQL) to enforce constraints and ACID guarantees.</li><li>Use auto-increment or UUIDs via sequences.</li></ul><h4>3. Scalability</h4><ul><li>Use <strong>horizontal scaling</strong> for the ID generator service (stateless).</li></ul><p><strong>For database:</strong></p><ul><li>Employ <strong>read replicas</strong> (read-heavy systems benefit here).</li><li>For SQL DBs, consider <strong>manual sharding</strong> based on:</li><li>Region</li><li>Prefix characters</li><li>Hash-based partitioning (for even distribution)</li></ul><h4>4. Failover &amp; Availability</h4><ul><li>Database replicas ensure <strong>failover capability</strong>.</li><li>Load balancer health checks reroute traffic in case of service failure.</li><li>Ensure <strong>at-least-once delivery</strong> semantics when persisting ID mappings (via retries or message queues).</li></ul><h3>Low Level Design:</h3><p>Now, let us design the system and the logic that would help us in generating unique Ids.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*LK1MI3538sS_UfvwVd1h3g.png" /><figcaption>basic LLD for generating unique Identifiers for users within a system.</figcaption></figure><p>In the image above, I’ve illustrated a simple <strong>Low-Level Design (LLD)</strong> for a Unique ID Generation System. While the logic is straightforward, the underlying structure follows <strong>Object-Oriented Design (OOD) principles</strong>, ensuring clean separation of responsibilities and extensibility for real-world systems.</p><p>To follow the <strong>Single Responsibility Principle (SRP)</strong> — where each class has only one reason to change — I’ve divided the system into two core classes:</p><ol><li><strong>user class</strong>: Defines the scope of data involved in the ID generation process. This includes attributes like username, emailid, security_question, and timestamp.</li><li><strong>IdGenerator class</strong>: Handles the logic for generating a unique ID based on the provided user data. This ensures that the logic is decoupled from the data model, making the system easier to extend, maintain, and test.</li></ol><p>This design pattern provides a modular, extensible foundation for building upon additional requirements like expiration, auditing, or security layers.</p><p>The ID is generated using a combination of the user’s information:</p><ul><li>username</li><li>emailid</li><li>security_question</li><li>timestamp</li></ul><p>This data is used to generate a raw string, from which a subset of characters is sampled to add randomness. The resulting string is then hashed using the <strong>SHA-256 algorithm</strong> to create a compact, secure, and uniform-length ID.</p><p>While I’ve used SHA-256 in this implementation, other hashing algorithms (like SHA-512, BLAKE2, or even custom encoding strategies) can be explored depending on the system’s security and performance requirements.</p><h3>Failover and Collision Handling</h3><p>To handle potential collisions (however rare in hashing), the logic includes a <strong>retry mechanism</strong>. We define a MAX_RETRIES value to attempt ID regeneration in case a collision is detected (e.g., if an ID already exists in the database).</p><p>This provides basic <strong>failover</strong> capability at the code level and prevents infinite loops or silent failures.</p><h3>Extending to Expiry &amp; Regeneration</h3><p>This design can be <strong>easily extended</strong> to support:</p><ul><li><strong>Expiration logic</strong>: Embedding timestamps in the ID or storing creation time separately allows the system to check if an ID is stale.</li><li><strong>Regeneration logic</strong>: If an ID has expired, we can trigger regeneration using the same core logic, ensuring the system remains secure and up-to-date.</li></ul><p>Such features are particularly useful in use cases like:</p><ul><li>Access tokens</li><li>Session identifiers</li><li>Public-private key mappings</li><li>One-time secret links</li><li>Time-bound transaction references</li></ul><h3>Final Thoughts</h3><p>This simple HLD and LLD demonstrates how clean class separation and basic cryptographic tools can power a <strong>robust and extensible unique ID generation system</strong>. Whether you’re building something as simple as user IDs or as complex as tokenized access systems, designing with scalability, security, and modularity in mind sets the foundation for production-readiness.</p><p>Upnext: Will dive deep into UUIDs, SnowFlake Id, GUIDs and how we can generate huge Identifiers that are practically used in today’s large scale systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0fc7ab96e7c4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This Bot Knows If Your Code Smells (and it is really not shy about it!)]]></title>
            <link>https://medium.com/@janakiramsharmak/this-bot-knows-if-your-code-smells-and-it-is-really-not-shy-about-it-58a97b4f7b53?source=rss-170025a2e9b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/58a97b4f7b53</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Ram Kashigari]]></dc:creator>
            <pubDate>Thu, 05 Jun 2025 17:55:13 GMT</pubDate>
            <atom:updated>2025-06-05T19:06:10.182Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In this article, I’ll break down how I built an automated code quality reviewer integrated with AWS dashboard using FastAPI, React, GitHub webhooks, and cloud-native architecture — perfect for DevOps workflows and modern full-stack teams.</blockquote><p>This article is all about my project “Automated Code Quality Reviewer”, the tech stack behind it, the architecture that connects everything, and the difficulties I overcame. I believe you’ll find something here to pique your curiosity, regardless of whether you’re a Developer, a DevOps enthusiast, or just someone who wants to know what modern automation looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xY82aB1s3BChSxzfA1eMMA.png" /></figure><h3>1. Why do we need this?</h3><blockquote>“Every developer has at some point pushed code, crossed fingers, and hoped for the best. What if code review wasn’t just automated, but intelligent, integrated, and insight-driven? That’s the vision behind my Automated Code Quality Reviewer.”</blockquote><p>Code reviews are a critical part of the development lifecycle — but let’s be honest, they’re often a bottleneck.</p><p>In fast-moving teams, reviews can be rushed, skipped, or reduced to just fixing linting errors. Even when done properly, they tend to be inconsistent — what one reviewer catches, another might miss. And while tools like linters help enforce style, they rarely go beyond the surface to analyze structure, complexity, or potential security risks.</p><p>At the same time, teams running infrastructure on the cloud often lack visibility into their live environments. Developers usually don’t know what’s running, what’s idle, or what’s consuming resources until someone gets a billing alert or logs into the AWS console manually.</p><p>So, the problems that I wanted to solve using this project are:</p><ol><li>Lack of consistency and speed in code reviews</li><li>Limited static analysis beyond basic linting</li><li>No seamless way to trigger analysis on GitHub events</li><li>Low visibility into real-time AWS infrastructure health</li></ol><p><em>What if a system could automatically review code like a senior developer, offer insights beyond formatting, and also keep tabs on the health of your cloud resources — all in one place?</em></p><p>That’s the gap this project bridges.</p><h3>2. Core Features</h3><p>This project isn’t just a linter wrapped in an API — it’s a complete, intelligent ecosystem that connects your codebase, GitHub activity, and AWS infrastructure. Here’s a breakdown of the key features that bring it all together:</p><ol><li><strong>Automated Code Quality Analysis:</strong></li></ol><p>&gt; Supports both direct code input and GitHub repository URLs.<br>&gt; Leverages python tools like <strong>Pylint</strong>, <strong>Flake8</strong>, and <strong>Bandit</strong> to detect code smells, security flaws, and complexity issues.<br>&gt; Augmented with ML models (and OpenAI where applicable) to go beyond syntax — offering contextual feedback on maintainability and structure.</p><p><strong>2. Backend API system with Fast API:</strong></p><p>&gt; Built with <strong>FastAPI</strong>, the backend exposes clean, RESTful endpoints to receive code or GitHub events.<br>&gt; Deployed on <strong>AWS EKS</strong>, supporting async tasks via <strong>Celery + Redis</strong> for fast, non-blocking analysis.<br>&gt; Follows best practices for CORS, routing, and secure input handling.</p><p><strong>3. React Frontend with Modern Dashboards:</strong></p><p>&gt; Built using <strong>React + Material-UI</strong>, hosted on <strong>Vercel</strong> for rapid, global delivery.<br>&gt; Clean UI to submit code, check past analysis history, and visualize AWS resources.<br>&gt; Fully responsive and mobile-friendly.</p><p><strong>4. GitHub Webhook Integration:</strong></p><p>&gt; Automatically analyzes code on every new push to a connected GitHub repo.<br>&gt; Uses <strong>HMAC signature verification</strong> to ensure secure and validated events.<br>&gt; Eliminates the need for manual intervention — just push your code, and it gets reviewed.</p><p><strong>5. AWS Resource Dashboard:</strong></p><p>&gt; Real-time visibility into <strong>EC2</strong>, <strong>EKS</strong>, and <strong>VPC</strong> resources using <strong>Boto3</strong>.<br>&gt; Color-coded cards display resource states with CPU usage, uptime, and more.<br>&gt; Frontend includes demo “Stop” and “Delete” buttons to simulate resource management features.</p><p><strong>6. Secrets &amp; DevOps Ready:</strong></p><p>&gt; Uses <strong>Kubernetes Secrets </strong>for storing sensitive credentials like tokens and webhook secrets.<br>&gt; Backend and worker services are fully containerized with <strong>Docker</strong>, and orchestrated using <strong>Kubernetes manifests</strong>.<br>&gt; Ready for CI/CD pipelines and scalable deployments.</p><blockquote>“The goal was simple: build a tool that’s useful to developers right from day one, but built with an architecture that can scale with a team.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DeNlLY7yBNCsUy_eSy8-jg.png" /></figure><h3>3. Technology Stack</h3><pre>Frontend: React, TypeScript, Material-UI, Vercel  <br>Backend: FastAPI, Celery, Redis, SQLAlchemy, Pydantic  <br>Cloud: AWS EC2, EKS, RDS, API Gateway, Secrets Manager  <br>CI/CD: Docker, Kubernetes, GitHub Webhooks  <br>Analysis: Pylint, Flake8, Bandit, OpenAI APIs (optional)</pre><h3>4. Architecture</h3><p>The architecture behind the Automated Code Quality Reviewer is designed for scalability, automation, and real-world usability. It all starts at the <strong>React frontend</strong>, where users can either paste code directly or submit a GitHub repository link for analysis. This request is sent to the <strong>FastAPI backend</strong>, which is deployed on <strong>AWS EC2</strong> or <strong>EKS</strong>, and exposed via <strong>API Gateway</strong> with proper CORS configurations. For GitHub repositories, a <strong>webhook listener</strong> is also active — automatically triggering a new analysis whenever code is pushed to a connected repo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*stoDiBB3rUza8ZKgih0nfQ.png" /></figure><p>Once a request reaches the backend, it’s handed off to a <strong>Celery worker</strong> via <strong>Redis</strong>, ensuring the main API stays responsive. The worker executes various code quality tools like <strong>Pylint</strong>, <strong>Flake8</strong>, <strong>Bandit</strong>, and optional <strong>ML-based reviewers</strong> to generate detailed feedback. These results are stored in <strong>PostgreSQL</strong> (hosted on <strong>RDS</strong>) and made available to the frontend for visualization. Simultaneously, another set of API endpoints fetches <strong>live AWS resource metrics</strong> (EC2, EKS, VPC) using <strong>Boto3</strong>, and returns the data to a <strong>Material-UI dashboard</strong> where it’s rendered with status indicators and actionable buttons.</p><p>All credentials, tokens, and secrets are securely managed using <strong>Kubernetes Secrets</strong>, while the entire application stack is containerized with <strong>Docker</strong> and orchestrated using <strong>Kubernetes manifests</strong> — making it fully production-ready and cloud-native.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7BjmseW8a0x_jI8c0kEavQ.png" /></figure><h3>5. Implementation Milestones</h3><blockquote>This project wasn’t built in a weekend — it evolved through careful planning, iteration, and problem-solving. Below are the key milestones that shaped the Automated Code Quality Reviewer into a full-stack, cloud-native system.</blockquote><h4>1. FastAPI Backend: The Brain of the Operation</h4><p>I started with <strong>FastAPI</strong> because of its speed, async capabilities, and Python-native ecosystem — which made integrating tools like Pylint, Flake8, and Bandit seamless. I structured the backend to expose clean, RESTful endpoints for both direct code submission and GitHub-triggered analysis. Every API followed proper request validation using <strong>Pydantic</strong>, ensuring robustness from the get-go.</p><blockquote>“FastAPI made it easy to stay agile while building something production-grade.”</blockquote><h4>2. GitHub Webhook Integration: Automate Everything</h4><p>Next came the heart of automation: GitHub webhooks. I configured a webhook listener that automatically triggers analysis whenever code is pushed to a linked repository. The webhook is protected with <strong>HMAC SHA256</strong> signature verification to ensure authenticity. This turned my tool into a passive reviewer — always watching, always analyzing.</p><blockquote>“Code analysis without needing to click a button? That’s the dream for any dev.”</blockquote><h4>3. Celery + Redis: Async Job Processing</h4><p>Running multiple linters and analysis tools can slow down the API — so I offloaded this to a <strong>Celery</strong> worker queue powered by <strong>Redis</strong>. Now, all heavy lifting happens in the background. The frontend stays fast, the backend stays responsive, and the user gets results within seconds of a push or submission.</p><blockquote>“Scaling the brain means splitting the thinking into pieces. That’s what Celery gave me.”</blockquote><h4>4. PostgreSQL Database for History and Persistence</h4><p>All analysis results are stored in a <strong>PostgreSQL</strong> database, making it easy to track historical trends, review past submissions, or debug recurring issues. Whether deployed locally or on <strong>AWS RDS</strong>, the database ensures every review is traceable and reportable.</p><blockquote>“A good reviewer remembers. So does a good backend.”</blockquote><h4>5. React Frontend on Vercel: Beautiful, Simple, Powerful</h4><p>I built a <strong>React + TypeScript</strong> frontend and deployed it on <strong>Vercel</strong> for blazing-fast delivery. Using <strong>Material-UI</strong>, I designed clean dashboards where users can:</p><ul><li>Submit code or GitHub URLs</li><li>View current and past analysis</li><li>Monitor AWS infrastructure</li></ul><blockquote>Everything is responsive, styled, and organized for developers — not just to see feedback, but to act on it.</blockquote><h4>6. AWS Resource Dashboard: Cloud Health in One Glance</h4><p>I added a dashboard to monitor <strong>EC2</strong>, <strong>EKS</strong>, and <strong>VPC</strong> resources in real time using <strong>Boto3</strong>. The FastAPI backend fetches live cloud metrics, and the frontend displays them using color-coded cards, uptime badges, and action buttons (simulated for now). This added real-world DevOps visibility to the project.</p><blockquote>“Why stop at reviewing code? Let’s review your infrastructure too.”</blockquote><h4>7. Kubernetes &amp; Docker: Production-Ready Everything</h4><p>To make the system scalable, I dockerized the backend, Celery worker, and Redis using <strong>Docker</strong>, and deployed the stack using <strong>Kubernetes manifests</strong>. I also injected secrets securely through <strong>Kubernetes Secrets</strong> and <strong>AWS Secrets Manager</strong>, so no credentials were ever hard-coded or exposed.</p><blockquote>“Shipping a project means thinking beyond your laptop. Kubernetes made it real.”</blockquote><h4>8. Debugging, Tuning &amp; API Gateway Integration</h4><p>This wasn’t without its hurdles. I spent hours fixing <strong>CORS issues</strong>, debugging <strong>GitHub webhook region mismatches</strong>, and making sure <strong>API Gateway</strong> worked cleanly with Vercel. These tiny details ended up being critical to the experience.</p><blockquote>“Building is one thing. Debugging is where you really learn what you built.”</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCrxO7BmvYn-WSbnNnbgVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ly5bW34RO08ilvmqH09f2A.png" /></figure><h3>6. What Makes This Project Unique</h3><ul><li>Real-time GitHub-triggered analysis.</li><li>Cloud-native, observable, and DevOps-friendly.</li><li>Designed with developers <em>and</em> ops teams in mind.</li><li>Easily extensible — want ESLint, Prettier, or custom rules? Just plug them in.</li></ul><h3>7. What’s Next?</h3><p>While the current version of the <strong>Automated Code Quality Reviewer</strong> delivers end-to-end code analysis and infrastructure visibility, there’s still a lot of exciting potential to unlock. Here’s what I’m trying to working on next:</p><ol><li><strong>Live AWS Resource Control</strong></li><li><strong>Support for Multiple Programming Languages</strong></li><li><strong>CI/CD Integration &amp; Slack/Gmail Alerts</strong></li></ol><h3>8. Smarter Feedback with LLMs</h3><p>On the experimental side, I’m exploring deeper ML/NLP integration using <strong>Open AI or fine-tuned LLMs</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HEbwGGNt71AuMhRA00eiMA.png" /></figure><ul><li>Turn static analysis into <strong>natural language suggestions</strong>.</li><li>Provide <strong>refactoring tips</strong>, explain <em>why</em> a change is needed, not just <em>what</em>.</li><li>Learn from past reviews to adapt and prioritize based on your codebase’s style.</li></ul><blockquote>This project is just the beginning of something much bigger — a smarter, developer-first ecosystem that doesn’t just catch bugs, but helps developers write better code and manage their systems more responsibly.</blockquote><p>Github repo: <a href="https://github.com/supernova2001/Automated-Code-Quality-Reviewer">https://github.com/supernova2001/Automated-Code-Quality-Reviewer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58a97b4f7b53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Balancing Act in System Design: From Performance to Partition Tolerance]]></title>
            <link>https://medium.com/@janakiramsharmak/balancing-act-in-system-design-from-performance-to-partition-tolerance-dbebefc47a15?source=rss-170025a2e9b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbebefc47a15</guid>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Ram Kashigari]]></dc:creator>
            <pubDate>Tue, 03 Jun 2025 04:13:11 GMT</pubDate>
            <atom:updated>2025-06-03T04:13:11.802Z</atom:updated>
            <content:encoded><![CDATA[<p>Performance and scalability are always at odds when developing systems, whether you’re creating the next unicorn startup or navigating enterprise spaghetti. It’s like attempting to create a vehicle that can be used as a bus and a race car. Building systems that don’t malfunction, lag, or leave users feeling abandoned requires a thorough understanding of tradeoffs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*s2Gt24c6j-cQPvdmor9Omw.png" /></figure><h3>Scalability</h3><p>Scalability refers to a system’s ability to <strong>handle increasing load</strong> by either enhancing existing resources or adding new ones. There are two main approaches:</p><p><strong>&gt; Vertical Scaling: </strong>Also known as <strong>scaling up</strong>, this involves upgrading the existing infrastructure — like moving from a t2.micro to a t3.large instance in AWS. It increases compute, memory, or storage on the same machine.</p><p><strong>Pro(s): Simpler to implement and the infrastructure doesn’t become complex.</strong></p><p><strong>Con(s): Biggest disadvantage would be that it has physical and cost limitations. After certain point, it could become difficult to scale up based on our application’s needs.</strong></p><p><strong>&gt; Horizontal Scaling:</strong> Also called <strong>scaling out</strong>, this strategy adds more machines or instances to handle growing load. Instead of one powerful server, you distribute the workload across many modest servers.</p><p><strong>Pro(s): Offers overall elasticity and resilience.</strong></p><p><strong>Con(s): Requires orchestration (to manage multiple resources: load balancers to balance load among various host machines, etc.)</strong></p><p><strong>Best Practice:</strong> In the industry, a combination of <strong>horizontal scaling</strong> with proper load balancing and stateless services is usually more effective for long-term growth and fault tolerance.</p><h3>Performance</h3><p>Performance focuses on <strong>how efficiently a system processes individual requests</strong>. It’s about minimizing latency and maximizing responsiveness.</p><p>If a service responds in 100ms under light load, that’s great performance. But performance without scalability can fail catastrophically under traffic spikes.</p><p><strong>Key performance boosters:</strong></p><ul><li>Efficient algorithms</li><li>Caching layers</li><li>Optimized database queries</li><li>Lightweight data transfers</li></ul><h3>Now comes the actual concept: Performance vs. Scalability: The Tradeoff</h3><ul><li>Prioritizing <strong>performance</strong> often optimizes for <em>individual user experience</em> under ideal conditions.</li><li>Prioritizing <strong>scalability</strong> ensures the system remains available and stable as load increases, potentially at the cost of latency.</li></ul><h4>Example:</h4><ul><li>In an <strong>e-commerce platform</strong>, adding items to a cart might take <strong>100ms</strong> under low load (performance focus).</li><li>During a flash sale, without scalability, the system might slow down or crash.</li><li>A scalable design may introduce slight latency (e.g., 500ms) but handle <strong>thousands of concurrent users</strong> smoothly.</li></ul><h3>Latency vs. Throughput</h3><ul><li><strong>Latency</strong>: Time taken to process a single request (e.g., API call response time).</li><li><strong>Throughput</strong>: Number of requests processed per unit time (e.g., 1000 requests/sec).</li></ul><p>For a well balanced system: There should be a balance between the latency and overall throughput of the system.</p><blockquote>Distributed systems are like long-distance relationships — a few things are always a little off :(</blockquote><p>The <strong>CAP theorem</strong> says that in any distributed system, you can only guarantee <strong>two out of three</strong> things at any given moment:</p><ul><li><strong>C</strong>onsistency — Everyone sees the same thing at the same time.</li><li><strong>A</strong>vailability — Everyone gets a response, even if it’s not perfect.</li><li><strong>P</strong>artition Tolerance — The system still works even if parts of it can’t talk to each other.</li></ul><p><strong>For example:</strong><br> You’re ordering pizza from an app that uses a global distributed system. Half the servers are in the U.S., half are in Asia. Suddenly, the connection between them drops (a <em>partition</em>). What happens now?</p><h4>1. CP (Consistency + Partition Tolerance):</h4><p>The system refuses to serve your order until the servers come up again.<br><strong>You get the <em>right</em> pizza… eventually.</strong><br> Usually, this works great for banking applications, where it’s better to show no balance than a wrong balance and confuse account holders.</p><h4>2. AP (Availability + Partition Tolerance):</h4><p>The app serves your order from whichever server is reachable — even if the toppings list is a bit outdated.<br><strong>You get <em>a</em> pizza… but maybe you wanted chicken and got pineapple.</strong><br>Useful for social media: it’s fine if your like count or comment count or no of posts aren’t accurate at times.</p><h3>Why not all three?</h3><p>Because the nature (LOL) (and network failures) won’t allow it. Once there’s a partition, you must <strong>choose between being accurate or being responsive.</strong></p><h3>Rule of Thumb:</h3><ul><li><strong>Need precision?</strong> Go <strong>CP</strong>.<br> <em>Think financial transactions, medical records, booking systems.</em></li><li><strong>Need uptime at all costs irrespective of the situation?</strong> Go <strong>AP</strong>.<br> <em>Think news feeds, product catalogs, food delivery menus.</em></li></ul><blockquote>To conclude, Designing scalable, high-performance systems isn’t about chasing perfection — it’s about <strong>making informed tradeoffs</strong> based on what your application <em>really</em> needs.</blockquote><p>We should always remember the fact that, while designing a system, there’s no one-size-fits-all. A fintech startup and a meme-sharing app have <strong>very different priorities</strong> — and their systems should reflect that.</p><p><strong>Understand your system’s goals, know your user expectations, and design for what matters most. Your Ops and Infra team will definitely <em>Thank You</em>!!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbebefc47a15" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Patterns and System Architecture: Walmart.com Case Study]]></title>
            <link>https://medium.com/@janakiramsharmak/design-patterns-and-system-architecture-walmart-com-case-study-eac58b8ddb58?source=rss-170025a2e9b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/eac58b8ddb58</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[walmart]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-design]]></category>
            <dc:creator><![CDATA[Ram Kashigari]]></dc:creator>
            <pubDate>Fri, 30 May 2025 23:17:05 GMT</pubDate>
            <atom:updated>2025-05-30T23:17:05.501Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine you’re building a full-fledged e-commerce platform, one that allows users to browse, search, purchase, and track products online. Platforms like Walmart.com have numerous backend functionalities enabling smooth ordering, payment processing, inventory checks, and more. But what really happens behind the scenes when a user visits Walmart.com?</p><h3>Step-by-Step: What Happens When You Enter Walmart.com</h3><p>When a user types walmart.com into their browser, they’re initiating a request for a resource—whether it’s a landing page, a product detail page, or a payment gateway. Here&#39;s what happens:</p><ol><li><strong>DNS Resolution</strong>:</li></ol><ul><li>The internet doesn’t understand human-readable URLs. It communicates using IP addresses.</li><li>A <strong>DNS (Domain Name System)</strong> translates walmart.com into an IP address via a DNS resolver.</li></ul><p>2. <strong>Connection Establishment</strong>:</p><ul><li>A <strong>TCP connection</strong> is established between the client and the server.</li><li>This is followed by a <strong>TLS handshake</strong> to secure the communication (HTTPS).</li></ul><p>3. <strong>Static Content Delivery via CDN</strong>:</p><ul><li>Static files (HTML, CSS, JS, images, videos) are fetched from a <strong>Content Delivery Network (CDN)</strong>.</li><li>CDNs are distributed globally to reduce latency and offload the origin server.</li></ul><p>4. <strong>Load Balancer</strong>:</p><ul><li>For dynamic content or API requests, the request is routed through a <strong>load balancer</strong>.</li><li>The load balancer distributes incoming requests across multiple web servers to prevent overloading and support high availability.</li></ul><p>5. <strong>Web Server &amp; Application Layer</strong>:</p><ul><li>The selected web server processes the request.</li><li>It checks <strong>cache</strong> (e.g., Redis, Memcached) to see if the resource is already stored.</li><li>If not in cache, the server queries the <strong>database</strong>, caches the result, and returns the response to the user.</li></ul><h3>Designing for Availability and Scalability</h3><p>Two pillars of any system reliability are <strong>availability</strong> and <strong>scalability</strong>:</p><ul><li><strong>Availability</strong>: Deploying the same application across multiple servers in different regions ensures that if one server fails, traffic is routed to another.</li><li><strong>Scalability</strong>: Using <strong>microservices architecture</strong> allows each functionality (user service, cart service, payment service, etc.) to scale independently, enabling efficient resource management.</li></ul><h3>Availability and Scalability in the Database Layer</h3><p>The database layer can become a bottleneck under heavy load. To design a fault-tolerant and scalable database layer, we implement:</p><h4>1. Database Replication</h4><p>Replication increases read scalability and system availability:</p><ol><li><strong>Master-Slave Replication</strong>:</li></ol><ul><li>Write operations go to the <strong>master</strong>.</li><li>Read operations are distributed among <strong>slave</strong> replicas.</li><li>Supports automatic <strong>failover</strong> where a slave is promoted if the master fails.</li><li><strong>Multi-Master Replication</strong>:</li><li>All nodes can accept writes.</li><li>Complex conflict resolution is required.</li></ul><h4>2. Sharding</h4><p>Sharding improves write scalability by distributing data across partitions:</p><ul><li>Data is divided based on a <strong>shard key</strong> (e.g., user ID).</li><li>Each shard contains a subset of the data, stored on different servers.</li><li>Challenges include uneven data distribution, complex joins, and routing queries to the right shard.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*4A2jYn_vxsjhFIG2Yxk8Mw.jpeg" /></figure><h3>What Walmart.com Likely Uses</h3><p>Based on industry practices and insights from Walmart Global Tech:</p><h4>Ensuring Availability and Scalability at the Server Layer</h4><ul><li>Load Balancers</li><li>Microservices Architecture</li><li>Containerization &amp; Orchestration (Kubernetes)</li><li>Global Multi-Region Deployments</li><li>Service Mesh and Observability</li><li>Infrastructure as Code (IaC) &amp; Auto-Provisioning</li></ul><h4>Design Patterns likely used by Walmart</h4><ul><li>Microservices</li><li>CQRS (Command Query Responsibility Segregation)</li><li>Circuit Breaker Pattern</li><li>Event-Driven Architecture</li></ul><h4>Database Replication</h4><ul><li>Walmart likely uses <strong>replication</strong> for high availability and read scalability.</li><li>Frequently accessed data like <strong>user profiles</strong>, <strong>product catalog</strong>, and <strong>store inventories</strong> are served from regional replicas.</li><li>Technologies: PostgreSQL, MySQL with replicas, or NoSQL solutions like MongoDB or Cassandra.</li></ul><h4>Sharding</h4><ul><li>Walmart likely shards data that is frequently written to, such as:</li><li><strong>Shopping cart items</strong></li><li><strong>Order histories</strong></li><li><strong>User sessions</strong></li><li>Sharding enables distributed storage and write throughput across millions of users and transactions.</li></ul><h4>Hybrid Model</h4><p><strong>A combination of sharding and replication:</strong></p><ul><li>Data is first sharded based on a logical key.</li><li>Each shard is then <strong>replicated</strong> across multiple regions.</li><li>This hybrid approach ensures:</li><li>High availability</li><li>Geographic distribution</li><li>Scalable read and write operations</li></ul><p>By leveraging both <strong>design patterns</strong> (like microservices, caching, and CDN), <strong>server-level </strong>and <strong>data-layer strategies</strong> (like replication and sharding), Walmart.com is able to deliver a seamless, highly available, and scalable e-commerce experience to millions of users worldwide.</p><blockquote>All the above information that I have presented is completely based on my assumptions, Walmart online blogs available and the insights that I got by going through the system design architectures of similar platforms.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eac58b8ddb58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Heap: The Underrated Yet Powerful Hero in DSA]]></title>
            <link>https://medium.com/@janakiramsharmak/heap-the-underrated-yet-powerful-hero-in-dsa-6e0e562223ce?source=rss-170025a2e9b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e0e562223ce</guid>
            <category><![CDATA[heap-memory]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[dsa-training]]></category>
            <category><![CDATA[heap]]></category>
            <category><![CDATA[problem-solving]]></category>
            <dc:creator><![CDATA[Ram Kashigari]]></dc:creator>
            <pubDate>Wed, 28 May 2025 23:47:37 GMT</pubDate>
            <atom:updated>2025-05-28T23:47:37.388Z</atom:updated>
            <content:encoded><![CDATA[<p>When diving into the world of Data Structures and Algorithms (DSA), we often find ourselves working with strings, arrays, and hash maps. These structures frequently come to our rescue in solving everyday coding problems and optimizing our solutions. However, there’s one powerful data structure that doesn’t always get the spotlight it deserves — the <strong>Heap</strong>.</p><h3>What is a Heap?</h3><p>The first question that comes to our mind is what is a heap? A <strong>heap</strong> is a specialized tree-based data structure that satisfies the <em>heap property</em>. It is always a <strong>complete binary tree</strong>, meaning all levels are fully filled except possibly the last, which is filled from left to right.</p><p>But here’s what sets it apart: the way the elements are <strong>ordered</strong>.</p><p>There are two main types of heaps:</p><ul><li><strong>Min-Heap</strong>: The value of the parent node is less than or equal to the values of its children.</li><li><strong>Max-Heap</strong>: The value of the parent node is greater than or equal to the values of its children.</li></ul><p>This ordering ensures that the root of the tree is always the <strong>minimum or maximum</strong> value, making access to the highest-priority element extremely efficient — in constant time.</p><h3><strong>But…..Why do we even need a heap?</strong></h3><p>Imagine you have a collection of elements that need to be processed based on their values — either in <strong>ascending</strong> or <strong>descending</strong> order. The most straightforward approach might be to store these elements in an array, sort them, and then access them one by one.</p><p>But… wait!<br> Have you considered the <strong>cost</strong> of this operation?</p><p>Using an efficient sorting algorithm like Merge Sort would still take <strong>O(n log n)</strong> time. While that’s optimal for general sorting, what if you only need the <strong>maximum or minimum element repeatedly</strong>, without sorting the entire dataset every time?</p><p><strong>This is where the heap truly shines.</strong></p><p>A heap allows you to maintain a semi-sorted structure where the <strong>highest (max-heap)</strong> or <strong>lowest (min-heap)</strong> priority element is always accessible in <strong>O(1)</strong> time. And inserting or removing elements only takes <strong>O(log n)</strong> time, making heaps an excellent choice for problems where you need frequent access to the smallest or largest elements without the overhead of full sorting.</p><p>A heap not only enables us to access elements in order based on their value but also allows prioritization based on <strong>custom-defined priorities</strong> — making it ideal for scenarios where each element has a distinct importance or weight.</p><p>Hmm…That’s quite interesting. Now, let us deep dive into the internal implementation of a heap.</p><h3>Heap and its implementation</h3><p>To effectively represent an entire binary tree, a heap is usually implemented as an array. Any element located at index i:</p><ul><li>Parent is at <strong>(i-1)//2</strong></li><li>Left child is at <strong>2*i+1</strong></li><li>Right child is at<strong> 2*i+2</strong></li></ul><p>This structure ensures no space is wasted on pointers, and relationships between nodes are computed using indices.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*3uJNtH7Nih5pLKZ9lbilUg.png" /><figcaption>Max heap</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/331/1*VfJesjOfzY6UJyC8qTOWNQ.png" /><figcaption>Min Heap</figcaption></figure><h4>Heapify:</h4><p>Heapify is a process used to maintain the <strong>heap property</strong> — either min-heap or max-heap. It is commonly used in:</p><ul><li>Building a heap from an unordered array (bottom-up approach)</li><li>Restoring heap structure after insertion or deletion</li></ul><p><strong>Max-heapify</strong> ensures that the value at the current node is <strong>greater than or equal to</strong> its children. If not, it swaps the value with the larger child and recursively calls heapify.</p><p><strong>Time complexity</strong>: O(log n)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*aNGNL9q1xm73Iz15Bv9rNg.png" /><figcaption>Heapify: converting a normal array into a max heap (can also be min heap)</figcaption></figure><h4>Removing the Max element:</h4><p>To remove the <strong>maximum element</strong> (i.e., the root):</p><ol><li>Swap the root with the last element.</li><li>Remove the last element (which was the root).</li><li>Call heapify on the root to restore the heap property.</li></ol><p><strong>Time complexity</strong>: O(log n)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/1*VDZsle729NH3nKBsBsvEGg.png" /><figcaption>removing max/min element from the heap</figcaption></figure><h4>Adding an element to the heap:</h4><p>insert a new element:</p><ol><li>Add it to the <strong>end</strong> of the array.</li><li>Compare it with its parent and <strong>bubble it up</strong> (swap) until the heap property is restored.</li></ol><p>This process is known as <strong>percolate up</strong> (push it up and then repeat till we reach the top).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*l8jsEHA63L3kRSAKei5lGQ.png" /><figcaption>Inserting a new element in a max heap.</figcaption></figure><p><strong>Time complexity</strong>: O(log n)</p><h3>Real world use cases of a Heap:</h3><ul><li>&gt; CPU Task Scheduling (Priority queue)</li><li>&gt; Dijkstra’s Algorithm (min-heap)</li><li>&gt; Garbage collection (decide which memory blocks to free first based on the priority factors)</li><li>&gt; Cache eviction policies: LRU and LFU can be optimised (original implementation uses a hashmap and a doubly linked list) using a Min/Max Heap.</li><li>&gt; Load Balancing : Picking up servers based on priority : Heap definitely helps us in this.</li><li>&gt; Top K elements: Classic use of a heap where we pull up top k elements or top kth element.</li></ul><p>Above are some of the most common use-cases of a heap. But yeah whenever we solve a problem where we deal with a sequence of elements based on a specific metric(like weight or priority or value): Try using a heap! it won’t disappoint you! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e0e562223ce" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design essentials -1: Parking Lot system]]></title>
            <link>https://medium.com/@janakiramsharmak/system-design-essentials-1-parking-lot-system-a11be48f4f23?source=rss-170025a2e9b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a11be48f4f23</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[system-design-project]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <dc:creator><![CDATA[Ram Kashigari]]></dc:creator>
            <pubDate>Tue, 27 May 2025 22:09:48 GMT</pubDate>
            <atom:updated>2025-05-27T22:14:21.399Z</atom:updated>
            <content:encoded><![CDATA[<p>Our task is to build a parking lot system with multiple levels. (something similar to the parking lot system in shopping malls). In our system, we need to be able to accept 3 types of vehicles: car, bus and a bike. ( for time being, a small item, medium item and large item).</p><p><strong>Constraints:</strong></p><ol><li>Motorcycles can be parked in any spot.</li><li>Cars can be parked only in large spots.</li><li>Buses can be parked only when there are 5 large spots in the same row.</li></ol><p>(similar constraints can be expected in interviews with varying types of vehicles or parking conditions. One thing that we need to remember is that we need to make sure that we are able to satisfy the conditions required for each type of vehicle to be parked).</p><p>When we talk about a system we need to get clarity around the constraints that we would be considering to build our system. and this forms the first step of designing any system.</p><p><strong>Functional requirements: (functionalities):</strong></p><ol><li>The system should allow us to park the vehicles.</li><li>The system should allow us to unpark a vehicle.</li><li>User should know the number of available spots per level and per vehicle type.</li><li>Edge cases: what if the lot is full, what if the lot is full for specific type of vehicles and available for other types, invalid input.</li></ol><p>The system we build must allow us to perform the above tasks. They form the core functionalities or functional requirements of our system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/0*bIvtylSzSWDJrgNx" /></figure><h3>Flow of the system:</h3><ol><li>User gets an option to park/unpark a vehicle on the system.</li><li>If the user selects park:</li><li>User gets an option to select the type of the vehicle</li></ol><p>2. If the user selects “Bike”, directly show all the available spots along with the level (level number) and the amount charged per hour for the spot.</p><p>3. If the user selects “Car”, show only large spots in each level and the amount charged per hour for the spot.</p><p>4. If the user selects “Bus”, check if there are any large spots side by side on the same row and show the available options at each level and the amount charged per hour for the spot.</p><ol><li>Once the user selects the option, show the amount charged per hour and give an option for the user to select the number of hours.</li><li>Once after user selects the number of hours, ask the user to enter the vehicle number for identification.</li><li>Then, redirect the user to the payment gateway and allow the user to pay for the reserved spot.</li><li>(Optional): Show the amount collected either on the system on the user end or to the admin on the admin side.</li></ol><h3>Services:</h3><p><strong>ParkingService: (takes the type of parking service as an input)</strong></p><ul><li>user_id Id</li><li>service_type String</li></ul><p><strong>VehicleService: (takes the vehicle details: type of the vehicle, vehicle id, user id)</strong></p><ul><li>user_id Id</li><li>vehicle_type String</li><li>service_id Id</li></ul><p><strong>SpotManagementService:</strong></p><ul><li>spot_availability Number</li><li>reserve_spot Boolean</li><li>Free_up_spot Boolean</li></ul><p><strong>SpotBookingService:</strong></p><ul><li>user_id Id</li><li>vehicle_type String</li><li>price Int</li><li>start_time Int (Booking time)</li><li>expiry_time Int (End time)</li><li>vehicle_id Int</li><li>phone_number Number</li><li>payment_id Id</li><li>booking_status</li></ul><p><strong>NotificatonService:</strong></p><ul><li>user_id Id</li><li>no_of_hours int</li><li>vehicle_id int</li><li>phone_number Number</li><li>alert String</li><li>status String</li></ul><p>Note/something to be remember: For any booking related use case, store the status of booking. It should follow atomicity. (it should either be fully processed or the action must be rejected).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/265/0*ipOUDpnQBuyGK4Za" /><figcaption>classes in the basic parking lot system</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Xttv3u6WUEw92CAI" /><figcaption>services in the parking lot system (as per the above design)</figcaption></figure><h3>Race conditions (important):</h3><ol><li>Here in our system, we would be having limited spots available at any point of time as these spots are occupied on timely basis. So, there is a chance of several requests going through the system and trying to access the same resource at the same time.</li><li>These kind of situations are known as race conditions where limited resources are being accessed or trying to be accessed by multiple people.</li><li>We should ensure integrity and consistency of our system in these kind of situations.</li><li>In order to avoid this situation, we need to implement the concept of locking on our shared resources (spots in this case).</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a11be48f4f23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Beauty of Binary Search]]></title>
            <link>https://medium.com/@janakiramsharmak/the-beauty-of-binary-search-b0373025bec3?source=rss-170025a2e9b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b0373025bec3</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[binary-search]]></category>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[dsa-problem]]></category>
            <category><![CDATA[dsa-courses]]></category>
            <dc:creator><![CDATA[Ram Kashigari]]></dc:creator>
            <pubDate>Sat, 24 May 2025 23:04:11 GMT</pubDate>
            <atom:updated>2025-05-24T23:06:56.919Z</atom:updated>
            <content:encoded><![CDATA[<blockquote><em>Binary search, though rooted in the simple constraint of a sorted array, proves to be a powerful and versatile technique that underpins a wide variety of problems in data structures and algorithms.</em></blockquote><p>Recently, while solving various DSA problems, I found binary search to be one of the most efficient and reliable tools in my arsenal. Its power goes far beyond simple element lookup — many problems that don’t appear to be traditional search problems at first glance can still be approached effectively using binary search, especially when they involve navigating through a sorted or potentially sortable sequence.</p><h3>A brief introduction: What is a Binary Search?</h3><p>Binary search is a technique of finding an element within an array by repeatedly dividing the array into halves till we find the element. It is a divide and conquer method, where we are dividing the array into smaller half each time, based on a specific condition of finding a particular element.</p><p><strong>The only constraint that we need to keep in mind in-order to apply binary search is that: the array must be sorted.</strong></p><p>In a traditional approach of finding an element, the time that it takes to find an element would be O(n) as we will be traversing through the entire array, covering all the elements. In the case of binary search, it will be O(logn) as we will be dividing the array into a half in each iteration, till we find the element that we need. We need to divide the array according to the value of the element that we are finding. As the array is sorted, the element could either be on the lower side of the array or on the upper side of the array. So, to make the search strategy efficient, we pick the middle most element and compare it with the element that we are trying to find to see on which part the element lies. We repeat this process for each half till we get the element that we need.</p><h3>Why Binary Search is beautiful?</h3><p>Well, this is the whole purpose of this article. To explain why binary search is beautiful.</p><p>Binary search isn’t just about finding a number in a sorted array — its true beauty lies in how <em>flexibly</em> and <em>creatively</em> it can be applied to a wide variety of seemingly unrelated problems. Once you recognize that binary search is really about <strong>searching through a space of possibilities</strong>, a whole new world of problem-solving opens up.</p><p>Let’s explore some elegant and surprising applications of binary search in DSA:</p><ol><li><strong>Finding the Longest Increasing Subsequence in a given sequence of elements:</strong></li></ol><p>Problem: <a href="https://leetcode.com/problems/longest-increasing-subsequence/">https://leetcode.com/problems/longest-increasing-subsequence/</a></p><p>In the classical LIS problem, we want to find the longest subsequence of increasing numbers in an array. A brute-force or DP approach takes O(n²) where we use two loops to traverse and store the sequence, but a clever use of binary search can reduce it to <strong>O(n log n)</strong>.</p><p>In this problem, while using binary search, we keep track of the possible tails for each LIS that we create while traversing through the given sequence. For every new element:</p><ol><li>We first check if the element can form a tail, by checking if it is larger than the largest element that we have tracked so far. If so, we just add it to the array and traverse.</li><li>Else, we use <strong>binary search</strong> to find the <strong>first element in the list which is greater than the current element and place this element in the appropriate position. This will either continue the current LIS or start a new sequence from this element.</strong></li></ol><pre>tails_list = [0]<br>tails_list[0]=nums[0]<br><br>for i in range(1,len(nums)):<br>    if(max(tails_list)&lt;nums[i]):<br>       tails_list.append(nums[i])<br>    else:<br>       index = binary(tails_list,nums[i])<br>       tails_list[index]=nums[i]<br><br><br>#binary is the function that performs binary search on the tails_list to find the right position for nums[i]</pre><p><strong>2. Koko eating bananas:</strong></p><p>Problem: <a href="https://leetcode.com/problems/koko-eating-bananas/">https://leetcode.com/problems/koko-eating-bananas/</a></p><p>This is a classic problem where binary search comes as a saviour. Let us say, we have a pile of bananas as an array and the maximum time that Koko can spend to complete all these piles. We need to find the minimum number of bananas (k) that Koko need to eat every hour in order to complete all the bananas in the given stipulated time. Here, the answer isn’t <em>in</em> the array — instead, we binary search over a <strong>range of potential answers (speeds)</strong>. At each step, we check if a given k is feasible (can she finish on time?). If yes, we try smaller k, else we try larger.</p><p>This is a classic case of <strong>binary search on the solution space</strong>, not the input data.</p><pre>while(low&lt;=high):<br>  <br>  mid = (low+high)//2<br>  hours = 0<br>  for pile in piles:<br>      hours+=math.ceil(pile/mid) <br>      if(hours&lt;=h):<br>         answer = min(answer,mid)<br>         high = mid-1<br>      else:<br>         low = mid+1</pre><p><strong>3. Finding peaks in the given array:</strong></p><p>Problem: <a href="https://leetcode.com/problems/find-peak-element/description/">https://leetcode.com/problems/find-peak-element/description/</a></p><p>Given an array where adjacent elements are not equal, a <em>peak</em> is an element that is greater than its neighbors. The task is to find <strong>any</strong> peak in <strong>O(log n)</strong>. In this problem, the array is not completely sorted, but it looks like a slope where one half of it would be increasing and the other half after the peak would be decreasing.</p><ul><li>Pick a middle element mid</li><li>If array[mid]&gt;array[mid+1], the peak is in the <strong>left half</strong></li><li>Else, it’s in the <strong>right half</strong></li></ul><p>The twist in this problem would be when there are duplicate elements in the array. Even this problem has the implementation of binary search which can make our solution much more simple and efficient.</p><p>What unites these diverse problems is that binary search isn’t used to find a value <em>in</em> an array — it’s used to narrow down a <strong>range of possibilities</strong> based on a <strong>yes/no decision</strong>.</p><p>So whenever we encounter a problem, we can question :</p><blockquote><em>“Can I frame this problem as a decision-making process over a sorted or monotonic space?”</em></blockquote><p>This makes Binary Search the most powerful and efficient tool unknowingly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0373025bec3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rate limiting in System Design]]></title>
            <link>https://medium.com/@janakiramsharmak/rate-limiting-in-system-design-2d6ad6dd63d4?source=rss-170025a2e9b1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d6ad6dd63d4</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[system-design-concepts]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Ram Kashigari]]></dc:creator>
            <pubDate>Fri, 23 May 2025 05:18:59 GMT</pubDate>
            <atom:updated>2025-05-23T05:54:45.159Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Ever wondered why Instagram sometimes blocks you from following too many accounts at once? Or why you can’t spam likes and comments nonstop?</em> It’s not magic — it’s something called <strong>rate limiting.</strong></p><p>Rate limiting is a crucial concept in system design, acting as a safeguard against abuse and ensuring fair usage of resources. It controls how often a user can perform certain actions within a specific timeframe. This isn’t just about social media — <strong>banking, e-commerce, and other critical applications rely on rate limiting to prevent their systems from crashing under heavy load</strong>.</p><h3>Why do we need rate limiting?</h3><p>Let’s look at an example to understand the significance of rate limiting.</p><p>Imagine <strong>ABC Bank</strong>, a global financial institution operating in over 30 countries. Millions of users rely on its web and mobile applications for daily transactions. Now, suppose the bank’s IT team made a critical mistake — they forgot to implement a rate limiter. (Let us just assume :)).</p><p>One day, a malicious hacker launches an attack, bombarding the bank’s servers with thousands of transaction requests per second using automated bots. <strong>Without a rate limiter, the system struggles to process this massive influx of requests, slowing down for legitimate users — or worse, crashing entirely.</strong> This is known as a <strong>Denial-of-Service (DoS) attack</strong>, where an attacker floods a system with traffic, making it unavailable to real users.</p><p>Every system has a limit on how many requests it can handle at once, no matter how powerful the infrastructure is. <strong>Without rate limiting, a single bad actor can bring down an entire platform</strong>, causing frustration for users and financial losses for businesses.</p><h3>Ways to implement rate limiting</h3><p>In the world of Information Technology, every problem has multiple solutions, and <strong>rate limiting is no exception</strong>. Depending on the scale and complexity of a system, different algorithms can be used to <strong>control the flow of requests</strong> and <strong>prevent system abuse</strong>.</p><p>Rate limiting can be implemented on both the <strong>client-side</strong> and <strong>server-side</strong>, but server-side implementation is preferred. <strong>Why?</strong> Because client-side rate limiting gives users more control, making it easier for bad actors to manipulate the system. Instead, <strong>server-side rate limiting (at the web server or gateway) ensures stronger protection against abuse.</strong></p><ol><li>Token bucket algorithm</li></ol><p>Imagine a bucket filled with tokens, each representing a request. Every time a request is made, <strong>a token is consumed</strong>. If the bucket is empty, <strong>new requests must wait</strong> until more tokens are added. The bucket refills at a constant rate, ensuring that <strong>bursts of traffic can be handled up to a certain limit</strong> while preventing excessive requests.</p><p>Big tech companies like <strong>Amazon</strong> use the <strong>Token Bucket Algorithm</strong> to manage request rates efficiently.</p><p>2. Leaking bucket algorithm</p><p>This works similarly to the <strong>Token Bucket Algorithm</strong> but follows a <strong>First In, First Out (FIFO)</strong> approach using a queue. <strong>Requests enter the queue and are processed at a fixed rate</strong>. If the queue is full, <strong>new requests are dropped until space is available</strong>.</p><p>The <strong>Leaky Bucket Algorithm</strong> ensures a smooth flow of requests, preventing sudden traffic spikes from overwhelming the system.</p><p>3. Fixed window counter algorithm</p><p>Here, time is divided into <strong>fixed-size windows</strong> (e.g., every minute). Each window has a counter that tracks incoming requests. Once the counter reaches the <strong>maximum allowed limit</strong>, <strong>any additional requests are rejected</strong> until the next window starts.</p><p>4. Sliding window log algorithm</p><p>To solve the <strong>edge problem</strong> of the Fixed Window Counter, the <strong>Sliding Window Log Algorithm</strong> maintains <strong>timestamps of requests</strong> in a cache (like <strong>Redis</strong>). As new requests come in, <strong>old timestamps are removed</strong> based on the defined rate limit.</p><p>5. Sliding window counter algorithm</p><p>This is a <strong>hybrid</strong> approach, combining elements of both <strong>Fixed Window Counter</strong> and <strong>Sliding Window Log</strong>. It introduces a <strong>rolling window</strong> that considers both: <strong>Requests in the current window and Requests from the previous window, weighted by overlap. </strong>This method is <strong>less commonly used</strong> but can be effective in certain <strong>high-traffic applications</strong> where <strong>precise request distribution</strong> is needed.</p><p><em>requests in current window + requests in previous window * percentage of overlap between previous and current windows</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*puwpVHNjjJxQJq0UaVAfKQ.jpeg" /><figcaption>Idea of how rate limiting through tokens and sliding window works</figcaption></figure><p>Choosing the algorithm completely depends on the size of the system and the pros and cons that each algorithm comes up with. Ultimately, the goal of <strong>any rate limiting mechanism</strong> is to <strong>protect the system from abuse while ensuring a smooth user experience.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d6ad6dd63d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>