<?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 Ankush kunwar on Medium]]></title>
        <description><![CDATA[Stories by Ankush kunwar on Medium]]></description>
        <link>https://medium.com/@ankushkunwar7777?source=rss-5bfd1de25146------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PM2XzrQiIZioeOOqKmzx8Q.jpeg</url>
            <title>Stories by Ankush kunwar on Medium</title>
            <link>https://medium.com/@ankushkunwar7777?source=rss-5bfd1de25146------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:17:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ankushkunwar7777/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[Over-Engineering vs Right-Thinking in System Design]]></title>
            <link>https://ankushkunwar7777.medium.com/over-engineering-vs-right-thinking-in-system-design-69b11f765a44?source=rss-5bfd1de25146------2</link>
            <guid isPermaLink="false">https://medium.com/p/69b11f765a44</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ankush kunwar]]></dc:creator>
            <pubDate>Sat, 20 Dec 2025 03:02:18 GMT</pubDate>
            <atom:updated>2025-12-20T03:02:18.433Z</atom:updated>
            <content:encoded><![CDATA[<p>“Good engineers build systems that work.<br> Great engineers build systems that stay simple.”</p><p>System design is <strong>not about drawing many boxes</strong>.<br> It is about making <strong>correct decisions under uncertainty</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ou87Fsx_u0Lar8-UdZXCLQ.png" /></figure><p>One of the <strong>biggest mistakes engineers make</strong> — especially as they grow — is <strong>over-engineering</strong>.</p><p>This article will teach you:</p><ul><li>What over-engineering really is</li><li>Why it happens</li><li>How to detect it early</li><li>How senior/principal architects think differently</li><li>Scenario-based examples with correct solutions</li><li>A repeatable decision framework</li></ul><h4>1️⃣<strong> What Is Over-Engineering (Real Definition)</strong></h4><p><strong>Over-engineering = Introducing unnecessary complexity that does not solve a current, clearly defined problem.</strong></p><p>It is <strong>not</strong>:</p><ul><li>Using modern tools</li><li>Writing scalable code</li><li>Thinking about future</li></ul><p>It <strong>is</strong>:</p><ul><li>Solving <em>imaginary future problems</em></li><li>Adding components “just in case”</li><li>Increasing operational cost without business value</li></ul><h4>2️⃣<strong> Why Engineers Over-Engineer (Honest Reasons)</strong></h4><p>Understanding <em>why</em> it happens helps prevent it.</p><p>🔹<strong> 1. Resume-Driven Design</strong></p><p>“Kafka, Kubernetes, Microservices look good”</p><p>❌ Architecture should serve <strong>business</strong>, not CVs.</p><p>🔹<strong> 2. Fear of Future Scale</strong></p><p>“What if we get 1 billion users?”</p><p>Reality:</p><ul><li>90% systems never reach that scale</li><li>Complexity hurts you <strong>today</strong>, not in the future</li></ul><p>🔹<strong> 3. Copying Big Tech Architectures</strong></p><p>“Netflix / Uber does this”</p><p>What’s ignored:</p><ul><li>Team size</li><li>Traffic</li><li>Operational maturity</li></ul><p>🔹<strong> 4. Lack of Operational Experience</strong></p><p>Engineers who’ve never:</p><ul><li>Debugged prod</li><li>Handled on-call</li><li>Managed outages</li></ul><p>…tend to over-design.</p><h4><strong>3️⃣ The Right Thinking: How Architects Actually Think</strong></h4><p>Senior and principal architects follow <strong>three mental rules</strong>:</p><p>🧠<strong> Rule 1: Solve Today’s Problem, Enable Tomorrow</strong></p><p>Design for <strong>change</strong>, not <strong>fantasy scale</strong></p><p>🧠<strong> Rule 2: Complexity Must Be Earned</strong></p><p>Every new component must justify its existence</p><p>🧠<strong> Rule 3: Operational Simplicity Is a Feature</strong></p><p>If your system is hard to operate, it’s a bad system</p><h4>4️⃣<strong> Over-Engineering Detection Checklist (Use This Always)</strong></h4><p>Before adding <strong>any component</strong>, ask:</p><ol><li>What problem does this solve <strong>today</strong>?</li><li>What breaks if we remove it?</li><li>Can we add it later without rewriting?</li><li>Does this increase on-call burden?</li><li>Can a junior engineer understand it?</li></ol><p>👉 If answers are weak → <strong>you are over-engineering</strong></p><h4><strong>5️⃣ Scenario-Based Learning (MOST IMPORTANT)</strong></h4><p>Let’s train your <strong>architecture intuition</strong>.</p><p>🧩<strong> Scenario 1: Sending Email After User Signup</strong></p><p><strong>Requirement</strong></p><ul><li>One email after signup</li><li>Low traffic</li><li>Reliability required</li></ul><p>❌ <strong>Over-Engineered</strong></p><ul><li>Kafka</li><li>Schema registry</li><li>Event sourcing</li></ul><p>✅ <strong>Right Thinking</strong></p><ul><li>Async queue (Celery / SQS)</li><li>Retry + DLQ</li></ul><p>🧠 <strong>Architect Reasoning</strong></p><p>One producer, one consumer → queue is enough<br> Kafka adds complexity without value</p><p>🧩<strong> Scenario 2: Internal Admin Dashboard</strong></p><p><strong>Requirement</strong></p><ul><li>30 internal users</li><li>CRUD operations</li><li>Normal availability</li></ul><p>❌ <strong>Over-Engineered</strong></p><ul><li>Microservices</li><li>Kubernetes</li><li>Redis</li><li>API Gateway</li></ul><p>✅ <strong>Right Thinking</strong></p><ul><li>Single backend service</li><li>Relational DB</li><li>Simple deployment</li></ul><p>🧠 <strong>Rule Learned</strong></p><p>Internal + low traffic = simple architecture</p><p>🧩<strong> Scenario 3: Audit Logs (Compliance)</strong></p><p><strong>Requirement</strong></p><ul><li>Append-only logs</li><li>Stored for 7 years</li><li>Rarely queried</li></ul><p>❌ <strong>Over-Engineered</strong></p><ul><li>Kafka</li><li>CQRS</li><li>Event sourcing</li></ul><p>✅ <strong>Right Thinking</strong></p><ul><li>Append to DB or object storage</li><li>Partition by date</li><li>Batch query when needed</li></ul><p>🧠 <strong>Rule Learned</strong></p><p>CQRS is for read/write divergence, not archival storage</p><p>🧩<strong> Scenario 4: Startup Backend (Early Stage)</strong></p><p><strong>Requirement</strong></p><ul><li>Unknown traffic</li><li>4 engineers</li><li>Fast iteration</li></ul><p>❌ <strong>Over-Engineered</strong></p><ul><li>Microservices</li><li>Service mesh</li><li>Distributed tracing</li></ul><p>✅ <strong>Right Thinking</strong></p><ul><li>Modular monolith</li><li>Clear domain boundaries</li><li>Vertical scaling</li></ul><p>🧠 <strong>Rule Learned</strong></p><p>Optimize for speed of change, not scale</p><p>🧩<strong> Scenario 5: Rate Limiting Public API</strong></p><p><strong>Requirement</strong></p><ul><li>5K RPS</li><li>Prevent abuse</li></ul><p>❌ <strong>Over-Engineered</strong></p><ul><li>Custom distributed rate-limiter</li><li>Zookeeper coordination</li></ul><p>✅ <strong>Right Thinking</strong></p><ul><li>Redis token bucket</li><li>API gateway support</li></ul><p>🧠 <strong>Rule Learned</strong></p><p>Use infra capabilities before building your own</p><h4>6️⃣<strong> Microservices: The Biggest Over-Engineering Trap</strong></h4><p>❌<strong> When Microservices Are Wrong</strong></p><ul><li>Small team</li><li>Low traffic</li><li>Tight coupling</li><li>Frequent schema changes</li></ul><p>✅<strong> When Microservices Are Right</strong></p><ul><li>Independent teams</li><li>Clear domain boundaries</li><li>Independent scaling needs</li><li>Organizational scaling problem</li></ul><p><strong>Microservices solve team-scale problems, not code problems</strong></p><h4>7️⃣<strong> Kafka: Powerful but Often Misused</strong></h4><p>❌<strong> Kafka Is Overkill When:</strong></p><ul><li>Single consumer</li><li>No replay</li><li>Low throughput</li><li>Simple async flow</li></ul><p>✅<strong> Kafka Is Justified When:</strong></p><ul><li>Multiple consumers</li><li>Event replay needed</li><li>Streaming analytics</li><li>High throughput pipelines</li></ul><h4><strong>The Ultimate System Design Template (Use This)</strong></h4><p>Every system should follow:</p><ol><li>Clarify requirements</li><li>Define non-functional priorities</li><li>Design simplest baseline</li><li>Identify bottlenecks</li><li>Plan evolution paths</li><li>Justify every component</li></ol><h4>⭐<strong> Final Golden Rule (Memorize This)</strong></h4><p><strong>“Complexity is a liability.<br> Add it only when the problem forces you.”</strong></p><h3>Thank you for reading !!!</h3><p>If you enjoy this article and would like to <strong>Buy Me a Coffee, </strong><a href="https://ko-fi.com/ankushkunwar">please click here.</a></p><p>you can connect with me on <a href="https://www.linkedin.com/in/ankush-kunwar777/">Linkedin</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=69b11f765a44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Some Scenario Based Question for Microservice: HLD]]></title>
            <link>https://ankushkunwar7777.medium.com/some-scenario-based-question-for-microservice-hld-270f4277d47c?source=rss-5bfd1de25146------2</link>
            <guid isPermaLink="false">https://medium.com/p/270f4277d47c</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <dc:creator><![CDATA[Ankush kunwar]]></dc:creator>
            <pubDate>Sat, 22 Feb 2025 15:28:56 GMT</pubDate>
            <atom:updated>2025-02-22T15:28:56.046Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/708/0*Vu51p473xVUBBueE" /></figure><h4><strong>Scenario 1: Handling Partial Failures in Microservice Communication</strong></h4><h4>Question:</h4><p>You have three microservices:</p><ul><li><strong>Order Service</strong> (handles orders)</li><li><strong>Payment Service</strong> (processes payments)</li><li><strong>Notification Service</strong> (sends confirmation emails)</li></ul><p>The <strong>Order Service</strong> calls the <strong>Payment Service</strong> to process payments and then calls the <strong>Notification Service</strong> to send confirmation emails. Sometimes, the <strong>Payment Service</strong> succeeds, but the <strong>Notification Service</strong> fails. How would you handle this scenario to ensure system consistency?</p><h4>Solution:</h4><p>To handle partial failures, implement <strong>Transaction Outbox Pattern</strong> or <strong>SAGA Pattern</strong>:</p><ol><li><strong>Transaction Outbox Pattern:</strong></li></ol><ul><li>Store the notification request in an “Outbox” table in the <strong>Order Service</strong> database.</li><li>A background worker (event-driven approach) periodically checks and retries sending notifications.</li></ul><p><strong>2. SAGA Pattern:</strong></p><ul><li>Use a <strong>choreography-based SAGA</strong> where the <strong>Payment Service</strong> publishes an event (PaymentCompleted).</li><li>The <strong>Notification Service</strong> listens to the event and sends an email.</li><li>If the notification fails, it retries or publishes a NotificationFailed event, triggering a rollback or manual intervention.</li></ul><h4>Scenario 2: Ensuring Data Consistency Across Microservices</h4><h4>Question:</h4><p>Your e-commerce application consists of two services:</p><ul><li><strong>Inventory Service</strong> (keeps track of product stock)</li><li><strong>Order Service</strong> (processes customer orders)</li></ul><p>A customer places an order, and the <strong>Order Service</strong> calls the <strong>Inventory Service</strong> to reduce stock. However, after reducing stock, the <strong>Order Service</strong> crashes before completing the order. How can you ensure data consistency?</p><h4>Solution:</h4><p>Use <strong>SAGA Pattern</strong> or <strong>Eventual Consistency with Compensation</strong>:</p><ol><li><strong>Choreography SAGA Approach:</strong></li></ol><ul><li><strong>Order Service</strong> starts the process and reduces stock via <strong>Inventory Service</strong>.</li><li>If the order process fails, <strong>Inventory Service</strong> listens to a rollback event (OrderFailed) and restores stock.</li></ul><ol><li><strong>Orchestration-based SAGA:</strong></li></ol><ul><li>Use a <strong>SAGA Orchestrator</strong> (e.g., a workflow engine like Camunda or Temporal).</li><li>If the order fails, the orchestrator triggers a rollback by calling <strong>Inventory Service</strong> to restore stock.</li></ul><p><strong>2. Using Eventual Consistency:</strong></p><ul><li>Store a local copy of the transaction status in a database and periodically reconcile inconsistencies.</li></ul><h4>Scenario 3: Choosing the Right Communication Pattern</h4><h4>Question:</h4><p>Your system has a <strong>Product Catalog Service</strong> and a <strong>Recommendation Service</strong>. The <strong>Recommendation Service</strong> needs product details in real time for recommendations. Which microservice communication method would you choose and why?</p><h4>Solution:</h4><ol><li><strong>Synchronous REST API (HTTP) Approach:</strong></li></ol><ul><li>If the Recommendation Service needs product details <strong>immediately</strong>, a synchronous REST API call is suitable.</li><li>However, this adds <strong>tight coupling</strong> and <strong>latency risks</strong> if the <strong>Product Catalog Service</strong> is slow.</li></ul><p><strong>2. Asynchronous Messaging Approach (Event-Driven Architecture)</strong></p><ul><li><strong>Best for Scalability &amp; Decoupling:</strong></li><li>The <strong>Product Catalog Service</strong> publishes an event (ProductUpdated).</li><li>The <strong>Recommendation Service</strong> subscribes to this event and updates its local cache.</li><li><strong>Technology:</strong> Kafka, RabbitMQ, or AWS SNS/SQS for event streaming.</li></ul><p><strong>Final Choice:</strong> Use <strong>event-driven communication</strong> to achieve high availability and decoupling while maintaining eventual consistency.</p><h4>Scenario 4: Circuit Breaker for Resilient Microservices</h4><h4>Question:</h4><p>You have a <strong>User Service</strong> that calls an external <strong>Third-Party Payment Gateway API</strong>. Sometimes, the API experiences downtime, causing <strong>User Service</strong> to hang. How can you make the service resilient?</p><h4>Solution:</h4><p>Use the <strong>Circuit Breaker Pattern</strong> (e.g., Netflix Hystrix or Resilience4j):</p><ol><li>If the <strong>payment API</strong> is down, the circuit breaker trips after a few failures.</li><li>Instead of blocking, the circuit breaker <strong>returns a fallback response</strong> (e.g., “Payment is temporarily unavailable”).</li><li>Once the payment API recovers, the circuit breaker <strong>resets</strong> and resumes normal operation.</li></ol><p>Example using <strong>Resilience4j</strong> (Java):</p><pre>@CircuitBreaker(name = &quot;paymentService&quot;, fallbackMethod = &quot;fallbackPayment&quot;)<br>public String processPayment() {<br>    return restTemplate.getForObject(&quot;https://payment-gateway.com/pay&quot;, String.class);<br>}</pre><pre>public String fallbackPayment(Exception e) {<br>    return &quot;Payment service is down. Please try again later.&quot;;<br>}</pre><h4>Scenario 5: Rate Limiting to Prevent Service Overload</h4><h4>Question:</h4><p>Your <strong>Authentication Service</strong> is being bombarded with login requests, causing slowdowns. How can you prevent abuse while ensuring normal traffic is not affected?</p><h4>Solution:</h4><p>Implement <strong>Rate Limiting</strong> using:</p><ol><li><strong>Token Bucket Algorithm:</strong></li></ol><ul><li>Limit users to <strong>N</strong> requests per minute using Redis (e.g., redis-cell for rate-limiting).</li></ul><p><strong>2. API Gateway Throttling:</strong></p><ul><li>If using <strong>Kong, Nginx, or AWS API Gateway</strong>, enforce rate limits at the gateway level.</li></ul><p>Example using <strong>Redis + Python Flask</strong>:</p><pre>import redis<br>from flask import Flask, request, jsonify<br><br>app = Flask(__name__)<br>r = redis.Redis(host=&#39;localhost&#39;, port=6379, db=0)<br>def is_rate_limited(user_id):<br>    key = f&quot;rate_limit:{user_id}&quot;<br>    count = r.incr(key)<br>    if count == 1:<br>        r.expire(key, 60)  # 60 seconds window<br>    return count &gt; 5  # Limit to 5 requests per minute<br>@app.route(&quot;/login&quot;, methods=[&quot;POST&quot;])<br>def login():<br>    user_id = request.json.get(&quot;user_id&quot;)<br>    if is_rate_limited(user_id):<br>        return jsonify({&quot;error&quot;: &quot;Too many login attempts&quot;}), 429<br>    return jsonify({&quot;message&quot;: &quot;Login successful&quot;})<br>if __name__ == &quot;__main__&quot;:<br>    app.run()</pre><h4>Scenario 6: Handling Duplicate Messages in Event-Driven Systems</h4><h4>Question:</h4><p>Your <strong>Order Service</strong> sends an OrderCreated event to <strong>Inventory Service</strong>. Due to network issues, the event is sometimes received multiple times, causing duplicate stock reductions. How do you prevent this?</p><h4>Solution:</h4><p>Use <strong>Idempotency &amp; Deduplication Mechanisms:</strong></p><ol><li><strong>Use a Unique Request ID:</strong></li></ol><ul><li>Assign a unique order_id to every event.</li><li>Store processed order_ids in Redis or a database and discard duplicates.</li></ul><p><strong>2. Idempotent Operations:</strong></p><ul><li>Instead of decrement_stock(quantity), use set_stock(new_value), ensuring the result remains the same.</li></ul><p>Example: Deduplication using Redis</p><pre>def process_order(order_id, stock_change):<br>    if redis_client.exists(order_id):<br>        return &quot;Duplicate event ignored&quot;<br>    redis_client.set(order_id, &quot;processed&quot;, ex=3600)  # Expire after 1 hour<br>    inventory_service.update_stock(stock_change)</pre><h3>Conclusion</h3><ul><li><strong>Resilience Patterns:</strong> Circuit Breaker, Rate Limiting, Retry Mechanism</li><li><strong>Consistency Strategies:</strong> SAGA Pattern, Eventual Consistency, Outbox Pattern</li><li><strong>Communication Strategies:</strong> REST (synchronous) vs. Event-driven (asynchronous)</li><li><strong>Scalability Techniques:</strong> API Gateway, Load Balancing, Caching</li></ul><h4><strong>Thank you for reading!</strong> ☕✨</h4><p>If you found this article valuable and would like to support my work, you can <a href="https://ko-fi.com/ankushkunwar"><strong>Buy Me a Coffee</strong>.</a> Your support means a lot!</p><p>Let’s connect! Feel free to reach out on <a href="https://www.linkedin.com/in/ankush-kunwar777/"><strong>LinkedIn</strong></a>. I’d love to hear your thoughts, answer any questions, or just chat about tech! 💡</p><p>Also, don’t forget to <strong>like, share, and drop a comment</strong> if this resonated with you. Your feedback keeps me going! 🔥</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=270f4277d47c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Estimation in Software Development: An In-Depth]]></title>
            <link>https://ankushkunwar7777.medium.com/estimation-in-software-development-an-in-depth-6eef07a58ac0?source=rss-5bfd1de25146------2</link>
            <guid isPermaLink="false">https://medium.com/p/6eef07a58ac0</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ankush kunwar]]></dc:creator>
            <pubDate>Sat, 15 Feb 2025 14:31:38 GMT</pubDate>
            <atom:updated>2025-02-15T14:31:38.416Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/902/0*6fA_F2IN2JxuXJcw.png" /></figure><p>Software development estimation is the process of predicting the effort, time, and cost required to develop a software product or feature. Estimation plays a critical role in project planning, resource allocation, budgeting, and risk management.</p><p>This guide will cover:</p><ul><li>Importance of estimation</li><li>Common challenges</li><li>Types of estimation techniques</li><li>Popular estimation methodologies</li><li>Factors affecting estimation</li><li>Best practices for accurate estimation</li></ul><h3>1. Importance of Estimation</h3><p>Software estimation is essential because:</p><ul><li>It <strong>helps in planning</strong> project timelines and deliverables.</li><li>It <strong>allocates resources efficiently</strong> (developers, testers, designers, etc.).</li><li>It <strong>determines the project cost</strong> for budgeting.</li><li>It <strong>mitigates risks</strong> by identifying potential bottlenecks early.</li><li>It <strong>sets realistic expectations</strong> for stakeholders, clients, and teams.</li></ul><p>Poor estimation can lead to:</p><ul><li><strong>Cost overruns</strong> due to underestimation.</li><li><strong>Missed deadlines</strong> affecting business goals.</li><li><strong>Scope creep</strong> as developers struggle to accommodate unforeseen complexities.</li><li><strong>Lower quality</strong> due to rushed development.</li></ul><h3>2. Common Challenges in Estimation</h3><p>Estimating software development is inherently difficult due to:</p><ol><li><strong>Unclear or Changing Requirements</strong> — Scope changes can increase development time.</li><li><strong>Unknown Complexity</strong> — Some problems are harder than they initially appear.</li><li><strong>Lack of Historical Data</strong> — New teams or projects may not have past metrics.</li><li><strong>Dependency on External Factors</strong> — API integrations, third-party services, and hardware dependencies.</li><li><strong>Human Biases</strong> — Optimism bias or “best-case scenario” thinking can lead to underestimation.</li><li><strong>Overlooking Testing &amp; Maintenance</strong> — Estimations often focus on development but ignore QA, bug fixing, and future maintenance.</li></ol><h3>3. Types of Estimation Techniques</h3><p>Different estimation techniques are used depending on project size, complexity, and available data.</p><h3>A. Effort-Based Estimation</h3><ol><li><strong>Expert Judgment</strong> — Based on the experience of senior developers.</li><li><strong>Analogous Estimation</strong> — Uses past similar projects for reference.</li><li><strong>Three-Point Estimation (PERT — Program Evaluation and Review Technique)</strong> — Calculates the average based on:</li></ol><ul><li><strong>Optimistic (O)</strong></li><li><strong>Pessimistic (P)</strong></li><li><strong>Most Likely (M)</strong><br>Formula:</li></ul><pre>E=O+4M+P/6<br>​</pre><h3>B. Decomposition-Based Estimation</h3><ol><li><strong>Work Breakdown Structure (WBS)</strong> — Breaks the project into smaller tasks and estimates each separately.</li><li><strong>Function Point Analysis (FPA)</strong> — Measures software size in function points based on inputs, outputs, user interactions, etc.</li><li><strong>Story Points (Agile)</strong> — Assigns complexity-based points to user stories.</li></ol><h3>C. Empirical Estimation Methods</h3><ol><li><strong>COCOMO (Constructive Cost Model)</strong> — Uses mathematical formulas based on project size.</li><li><strong>T-shirt Sizing</strong> — Uses broad categories like Small, Medium, Large, XL for effort estimation.</li><li><strong>Use-Case Points</strong> — Estimates effort based on use-case complexity.</li></ol><h3>4. Popular Estimation Methodologies</h3><h3>A. Agile Estimation</h3><p>Used in Scrum, Kanban, and other Agile methodologies.</p><ul><li><strong>Story Points</strong> — Estimations based on complexity rather than time.</li><li><strong>Planning Poker</strong> — Team-based estimation using Fibonacci sequence values (1, 2, 3, 5, 8, 13, etc.).</li><li><strong>Velocity-Based Estimation</strong> — Uses past team performance to predict future work capacity.</li></ul><h3>B. Waterfall Estimation</h3><p>Used in traditional software development.</p><ul><li><strong>Gantt Charts</strong> — Plan project milestones and deadlines.</li><li><strong>Critical Path Method (CPM)</strong> — Identifies the longest sequence of dependent tasks.</li></ul><h3>C. Hybrid Estimation</h3><p>Combines Agile and Waterfall estimation techniques, often used in large enterprises.</p><h3>5. Factors Affecting Estimation</h3><ol><li><strong>Project Size</strong> — Larger projects require more estimation effort.</li><li><strong>Team Experience</strong> — Experienced teams can estimate more accurately.</li><li><strong>Technology Stack</strong> — Unfamiliar technologies increase risk and effort.</li><li><strong>Code Complexity</strong> — Complex logic, security requirements, and performance optimizations.</li><li><strong>Integration Needs</strong> — External services, databases, and legacy system dependencies.</li><li><strong>Quality Requirements</strong> — Higher quality standards increase testing time.</li><li><strong>Client Involvement</strong> — Frequent feedback loops affect estimation accuracy.</li></ol><h3>6. Best Practices for Accurate Estimation</h3><ol><li><strong>Break Down the Work</strong> — Use a WBS to estimate in smaller, manageable tasks.</li><li><strong>Use Multiple Estimation Techniques</strong> — Cross-check results from different methods.</li><li><strong>Involve the Right People</strong> — Developers, testers, and architects should contribute.</li><li><strong>Consider Risks and Buffers</strong> — Add contingency time for unexpected issues.</li><li><strong>Validate with Historical Data</strong> — Use previous project metrics when available.</li><li><strong>Continuously Refine Estimates</strong> — As the project progresses, adjust estimates based on real progress.</li><li><strong>Avoid Overconfidence</strong> — Challenge optimistic assumptions and account for unknowns.</li></ol><h3>Conclusion</h3><p>Software development estimation is a critical skill that requires experience, structured approaches, and continuous refinement. By understanding different estimation techniques, methodologies, and best practices, teams can improve accuracy, reduce risks, and deliver successful software projects.</p><h3>Thank you for reading !!!</h3><p>If you enjoy this article and would like to <strong>Buy Me a Coffee, </strong><a href="https://ko-fi.com/ankushkunwar">please click here.</a></p><p>you can connect with me on <a href="https://www.linkedin.com/in/ankush-kunwar777/">Linkedin</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6eef07a58ac0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[High-Level Design (HLD) System Design Cheatsheet]]></title>
            <link>https://ankushkunwar7777.medium.com/high-level-design-hld-system-design-cheatsheet-58dd74e66113?source=rss-5bfd1de25146------2</link>
            <guid isPermaLink="false">https://medium.com/p/58dd74e66113</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Ankush kunwar]]></dc:creator>
            <pubDate>Sat, 01 Feb 2025 14:12:22 GMT</pubDate>
            <atom:updated>2025-02-01T14:12:22.185Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Understanding Requirements</h3><ul><li><strong>Functional Requirements:</strong> Core features (e.g., user login, messaging, video streaming, etc.).</li><li><strong>Non-Functional Requirements:</strong> Scalability, availability, fault tolerance, consistency, etc.</li><li><strong>Constraints &amp; Assumptions:</strong> Users, data size, traffic volume, latency requirements.</li></ul><h3>2. Defining System Components</h3><ul><li><strong>Client Layer:</strong> Web, mobile apps, APIs.</li><li><strong>Application Layer:</strong> Microservices, monolith, API gateways.</li><li><strong>Data Layer:</strong> Databases (SQL/NoSQL), caching (Redis, Memcached).</li><li><strong>Storage Layer:</strong> Blob storage, file storage, CDN.</li><li><strong>Networking:</strong> Load balancers, reverse proxies.</li></ul><h3>3. Database Selection</h3><ul><li><strong>Relational Databases (SQL)</strong>: ACID compliance, structured data.</li><li><strong>NoSQL Databases</strong>: Document-based (MongoDB), Key-value (Redis), Columnar (Cassandra), Graph (Neo4j).</li><li><strong>Sharding &amp; Partitioning</strong>: Horizontal scaling.</li><li><strong>Replication</strong>: Master-slave, leader-follower.</li><li><strong>Indexing &amp; Query Optimisation</strong>.</li></ul><h3>4. Scalability &amp; Performance</h3><p><strong>Load Balancing</strong>: Round-robin, Least connections, Consistent hashing.</p><p><strong>Caching Strategies</strong>:</p><ul><li><strong>CDN</strong> for static content.</li><li><strong>Application caching</strong> (Redis, Memcached).</li><li><strong>Database caching</strong> (Read replicas, materialized views).</li></ul><p><strong>Asynchronous Processing</strong>:</p><ul><li>Message queues (Kafka, RabbitMQ, SQS).</li><li>Event-driven architecture.</li></ul><h3>5. Availability &amp; Fault Tolerance</h3><ul><li><strong>Replication</strong>: Multi-region, Multi-master, Read replicas.</li><li><strong>Failover &amp; Redundancy</strong>: Hot standby, cold standby.</li><li><strong>Distributed Systems Principles</strong>: CAP Theorem (Consistency, Availability, Partition Tolerance).</li></ul><h3>6. Consistency &amp; Data Integrity</h3><ul><li><strong>Strong vs Eventual Consistency</strong>.</li><li><strong>Distributed Transactions</strong>: Two-phase commit, Saga pattern.</li><li><strong>Quorum-based Voting (Raft, Paxos)</strong>.</li></ul><h3>7. Security Considerations</h3><ul><li><strong>Authentication &amp; Authorization</strong>: OAuth, JWT, OpenID.</li><li><strong>Data Encryption</strong>: TLS, SSL, AES.</li><li><strong>Rate Limiting &amp; API Security</strong>.</li><li><strong>DDOS Protection, Firewalls, IDS/IPS</strong>.</li></ul><h3>8. Monitoring &amp; Logging</h3><ul><li><strong>Metrics Collection</strong>: Prometheus, Grafana.</li><li><strong>Logging &amp; Analysis</strong>: ELK Stack (Elasticsearch, Logstash, Kibana), Splunk.</li><li><strong>Alerting &amp; Incident Management</strong>: PagerDuty, Opsgenie.</li></ul><h3>9. Common System Design Problems</h3><ul><li><strong>URL Shortener</strong>: Hashing, unique ID generation.</li><li><strong>Rate Limiting</strong>: Token bucket, leaky bucket.</li><li><strong>Messaging Queue</strong>: Kafka, RabbitMQ, SQS.</li><li><strong>Designing Instagram/Twitter</strong>: Timeline generation, fan-out.</li><li><strong>Designing Netflix/YouTube</strong>: Content delivery, CDN.</li><li><strong>Designing Uber</strong>: Real-time tracking, geospatial indexing.</li></ul><h3>10. Interview Tips</h3><ul><li><strong>Clarify Requirements First</strong>.</li><li><strong>Start with a High-Level Architecture</strong> before diving deep.</li><li><strong>Discuss Trade-offs</strong> (CAP theorem, consistency vs availability).</li><li><strong>Think About Scaling Early</strong>.</li><li><strong>Use a Whiteboard or Paper to Diagram Your Solution</strong>.</li><li><strong>Keep It Conversational &amp; Collaborative</strong>.</li></ul><h3>Final Note:</h3><p>System design interviews are about demonstrating structured thinking, scalability trade-offs, and handling real-world constraints effectively. Practice designing different systems and focus on reasoning over perfect solutions!</p><h3>Thank you for reading !!!</h3><p>If you enjoy this article and would like to <strong>Buy Me a Coffee, </strong><a href="https://ko-fi.com/ankushkunwar">please click here.</a></p><p>you can connect with me on <a href="https://www.linkedin.com/in/ankush-kunwar777/">Linkedin</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58dd74e66113" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sharding Concept in depth:- System Design]]></title>
            <link>https://ankushkunwar7777.medium.com/sharding-concept-in-depth-system-design-ce9ddc0c5f9c?source=rss-5bfd1de25146------2</link>
            <guid isPermaLink="false">https://medium.com/p/ce9ddc0c5f9c</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ankush kunwar]]></dc:creator>
            <pubDate>Sat, 01 Feb 2025 14:03:13 GMT</pubDate>
            <atom:updated>2025-02-01T14:03:13.470Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*sYkDWmOMQpjvZaRh.jpg" /></figure><h3>What is Sharding?</h3><p>Sharding is a database architecture pattern that involves splitting a large dataset into smaller, more manageable pieces called “shards.” Each shard is an independent database that contains a subset of the overall data. The goal of sharding is to improve <strong>scalability, performance, and availability</strong> by distributing the database workload across multiple servers.</p><h3>1. Why Do We Need Sharding?</h3><p>Sharding is primarily used to address challenges related to <strong>scalability</strong> and <strong>performance</strong> in databases that experience high traffic and large datasets. Some of the key reasons for sharding include:</p><ol><li><strong>Scalability</strong></li></ol><ul><li>Vertical scaling (adding more CPU/RAM to a single machine) has limitations.</li><li>Sharding allows for horizontal scaling by adding more machines.</li></ul><p><strong>2. Performance Improvement</strong></p><ul><li>Queries become faster because they run on smaller datasets (each shard contains only a subset of data).</li><li>Reduces contention for system resources (CPU, memory, disk I/O).</li></ul><p><strong>3. High Availability &amp; Fault Tolerance</strong></p><ul><li>If one shard fails, only a part of the data is affected, not the entire system.</li><li>It prevents a single point of failure (SPOF).</li></ul><p><strong>5. Geographical Distribution</strong></p><ul><li>Data can be stored closer to users in different regions to reduce latency.</li></ul><h3>2. Where is Sharding Possible?</h3><p>Sharding is useful in databases where <strong>read and write operations</strong> are high and dataset size grows rapidly. It is commonly used in:</p><ol><li><strong>Large-scale web applications</strong></li></ol><ul><li>Social media (Facebook, Twitter, Instagram)</li><li>E-commerce platforms (Amazon, eBay)</li><li>Online gaming applications</li></ul><p><strong>2. Multitenant SaaS applications</strong></p><ul><li>When each customer or tenant has its own data.</li></ul><p><strong>3. Financial systems</strong></p><ul><li>Large transaction volumes (stock exchanges, payment processing).</li></ul><p><strong>4. Time-series databases</strong></p><ul><li>Logging systems (Splunk, ELK Stack).</li></ul><h3>Where is Sharding NOT Recommended?</h3><p>Sharding is not ideal when:</p><ol><li><strong>Data is small and fits comfortably in a single database.</strong></li><li><strong>Cross-shard queries are frequent and complex.</strong></li></ol><ul><li>Joins and aggregations across shards can be expensive.</li></ul><p><strong>3. ACID compliance is strict.</strong></p><ul><li>Distributed transactions across shards can be hard to manage.</li></ul><p><strong>4. Sharding adds operational complexity.</strong></p><ul><li>It requires careful planning, monitoring, and maintenance.</li></ul><h3>3. SQL vs NoSQL: Sharding Comparison</h3><p>Sharding works differently in <strong>SQL (relational) databases</strong> and <strong>NoSQL (non-relational) databases</strong> due to differences in data models and transaction handling.</p><p><strong>Schema Design</strong></p><ul><li><strong>SQL Databases (MySQL, PostgreSQL):</strong><br>SQL databases utilize a rigid and structured schema based on tables and relationships. The structure is defined before data insertion, and any changes typically require migrations.</li><li><strong>NoSQL Databases (MongoDB, Cassandra):</strong><br>NoSQL systems offer a flexible, often schema-less design. Data can be stored in formats like JSON or key-value pairs, allowing for rapid iteration and adjustments without the need for strict predefined structures.</li></ul><p><strong>Sharding Mechanisms</strong></p><ul><li><strong>SQL Databases:</strong><br>Sharding in SQL environments is generally manual. Developers need to implement sharding logic at the application level or use middleware to partition the data across multiple databases. This approach can be complex, especially when dealing with relational constraints and joins.</li><li><strong>NoSQL Databases:</strong><br>Many NoSQL databases come with built-in sharding capabilities. Systems like MongoDB and Cassandra automatically distribute data across shards based on a defined shard key, reducing the operational overhead and simplifying the scaling process.</li></ul><p><strong>ACID Support and Consistency</strong></p><ul><li><strong>SQL Databases:</strong><br>SQL databases are designed to offer strong ACID (Atomicity, Consistency, Isolation, Durability) guarantees. While this ensures robust transactional integrity, it also makes sharding more challenging because maintaining ACID properties across multiple shards can be complex.</li><li><strong>NoSQL Databases:</strong><br>In contrast, NoSQL databases often prioritize scalability over strong consistency, favoring eventual consistency models. This trade-off makes sharding easier to implement, as the system can relax strict transactional requirements in favor of performance and horizontal scalability.</li></ul><p><strong>Query Complexity and Data Relationships</strong></p><ul><li><strong>SQL Databases:</strong><br>SQL systems support complex queries involving joins and multi-table transactions. However, when data is spread across shards, cross-shard joins and transactions can become problematic, often requiring additional logic to handle distributed queries effectively.</li><li><strong>NoSQL Databases:</strong><br>NoSQL databases are typically optimized for simple, fast key-based access. While they may not support complex joins natively, this design facilitates faster lookups and operations on distributed data, which aligns well with the principles of horizontal scaling.</li></ul><p><strong>Scalability</strong></p><ul><li><strong>SQL Databases:</strong><br>Traditional SQL databases often face limitations when scaling horizontally due to their monolithic architecture and reliance on strict consistency. Scaling out usually involves significant engineering efforts, such as implementing manual sharding or leveraging read replicas.</li><li><strong>NoSQL Databases:</strong><br>NoSQL systems are inherently designed for horizontal scaling. With built-in support for sharding and distributed data storage, these databases can more easily handle increasing loads and large volumes of data across multiple servers.</li></ul><h3>SQL Sharding</h3><p><strong>Manual process</strong>: SQL databases don’t have built-in sharding, so developers must implement it at the application level.</p><p><strong>Challenges</strong>:</p><ul><li>Hard to maintain foreign key relationships across shards.</li><li>Difficulties with ACID compliance (cross-shard transactions).</li><li>Querying across shards requires extra logic.</li></ul><h3>NoSQL Sharding</h3><p><strong>Automatic or built-in</strong>: NoSQL databases like MongoDB and Cassandra support native sharding.</p><p><strong>Advantages</strong>:</p><ul><li>Designed for horizontal scaling.</li><li>No need for strict foreign key relationships.</li><li>Supports distributed queries.</li></ul><h3>4. Sharding Strategies</h3><p>There are multiple ways to distribute data across shards:</p><ol><li><strong>Key-based (Hash Sharding)</strong></li></ol><ul><li>A hash function determines which shard stores a record.</li><li>Ensures even distribution but hard to change shard count.</li><li>Used in <strong>MongoDB, Cassandra</strong>.</li></ul><p><strong>2. Range-based Sharding</strong></p><ul><li>Data is partitioned based on a range (e.g., users with ID 1–1000 in shard A).</li><li>Good for sequential queries but can create <strong>hotspots</strong>.</li><li>Used in <strong>PostgreSQL (partitioning)</strong>.</li></ul><p><strong>3. Geographical Sharding</strong></p><ul><li>Data is stored in shards based on user location (e.g., US data in one shard, EU data in another).</li><li>Used in <strong>multi-region databases</strong>.</li></ul><p><strong>4. Entity-based Sharding</strong></p><ul><li>Data related to a specific entity (e.g., customer ID, company) is stored in one shard.</li><li>Used in <strong>multi tenant SaaS</strong>.</li></ul><h3>5. When and Where to Use Sharding</h3><p><strong>Use Sharding When</strong>:</p><ul><li>Your dataset is too large for a single machine.</li><li>You need high write throughput.</li><li>Your application needs horizontal scalability.</li><li>Your workload consists of many independent queries.</li></ul><p><strong>Avoid Sharding When</strong>:</p><ul><li>Your database size is small.</li><li>Your queries require frequent joins across shards.</li><li>You need strict ACID transactions.</li></ul><h3>6. Conclusion</h3><p>Sharding is a powerful technique for scaling databases, but it comes with trade-offs in <strong>complexity and data consistency</strong>.</p><ul><li><strong>SQL databases</strong> require <strong>manual sharding</strong> and struggle with cross-shard operations.</li><li><strong>NoSQL databases</strong> like <strong>MongoDB and Cassandra</strong> provide <strong>built-in sharding</strong> for easier horizontal scaling.</li></ul><p>When choosing whether to shard, consider <strong>query patterns, data size, and operational complexity</strong>. In many cases, alternatives like <strong>read replicas or partitioning</strong> may be preferable before resorting to full sharding.</p><h3>Thank you for reading !!!</h3><p>If you enjoy this article and would like to <strong>Buy Me a Coffee, </strong><a href="https://ko-fi.com/ankushkunwar">please click here.</a></p><p>you can connect with me on <a href="https://www.linkedin.com/in/ankush-kunwar777/">Linkedin</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ce9ddc0c5f9c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Everything About File Handling in python.]]></title>
            <link>https://ankushkunwar7777.medium.com/everything-about-file-handling-in-python-1ccb38f96170?source=rss-5bfd1de25146------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ccb38f96170</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ankush kunwar]]></dc:creator>
            <pubDate>Sun, 18 Aug 2024 10:31:46 GMT</pubDate>
            <atom:updated>2024-08-18T10:31:46.133Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7jDmKxkEMBgCqJDRsZeMGw.jpeg" /></figure><p>File handling is an essential aspect of programming, and Python provides various functions and methods to work with files. This includes reading from and writing to files, as well as other file operations like deleting, copying, and renaming.</p><h4>Basic Operations</h4><ol><li><strong>Opening a File</strong></li></ol><ul><li>To work with files, you first need to open them using the open() function.</li><li>The syntax is: open(filename, mode)</li><li><strong>filename</strong>: The name of the file you want to open.</li><li><strong>mode</strong>: This specifies the purpose for which you want to open the file.</li><li>Common modes include:</li><li>&#39;r&#39;: Read (default mode). Opens the file for reading.</li><li>&#39;w&#39;: Write. Opens the file for writing (creates a new file or truncates the existing file).</li><li>&#39;a&#39;: Append. Opens the file for appending (adds content to the end of the file).</li><li>&#39;b&#39;: Binary mode (e.g., &#39;rb&#39; for reading in binary mode, &#39;wb&#39; for writing in binary mode).</li><li>&#39;x&#39;: Create. Creates a new file and opens it for writing; raises an error if the file already exists.</li><li>&#39;+&#39;: Read and write (e.g., &#39;r+&#39;, &#39;w+&#39;).</li></ul><p><strong>2. Reading from a File</strong></p><ul><li><strong>read(size)</strong>: Reads size bytes from the file. If no size is specified, it reads the entire file.</li><li><strong>readline()</strong>: Reads a single line from the file.</li><li><strong>readlines()</strong>: Reads all lines in a file and returns them as a list.</li></ul><p><strong>3. Writing to a File</strong></p><ul><li><strong>write(string)</strong>: Writes the string to the file.</li><li><strong>writelines(list_of_strings)</strong>: Writes a list of strings to the file.</li></ul><p><strong>4. Closing a File</strong></p><ul><li>Always close a file after you’re done working with it using the <strong>close()</strong> method. This ensures that all changes are saved, and resources are freed.</li><li>Alternatively, you can use the with statement, which automatically closes the file when the block is exited.</li></ul><pre>with open(&#39;example.txt&#39;, &#39;w&#39;) as file:<br>    file.write(&#39;Hello, World!&#39;)</pre><p><strong>5. Appending to a File</strong></p><ul><li>Use the &#39;a&#39; mode to add content to the end of an existing file.</li></ul><pre>with open(&#39;example.txt&#39;, &#39;a&#39;) as file:<br>    file.write(&#39;\nAppended text&#39;)</pre><p><strong>6. File Positioning</strong></p><ul><li><strong>tell()</strong>: Returns the current file position.</li><li><strong>seek(offset, from_what)</strong>: Changes the file position. offset is the number of bytes to move, and from_what determines the reference point (0 for start of the file, 1 for current position, 2 for end of the file).</li></ul><h4>Working with Different File Types</h4><p><strong>Text Files</strong>: Files that contain readable characters, like .txt files.</p><ul><li>Use &#39;r&#39;, &#39;w&#39;, &#39;a&#39; modes.</li></ul><p><strong>Binary Files</strong>: Files that contain data in binary format, like images or executables.</p><ul><li>Use &#39;rb&#39;, &#39;wb&#39;, &#39;ab&#39; modes.</li></ul><h4>File Handling Libraries</h4><p>Python’s built-in file handling capabilities are sufficient for most tasks. However, there are additional libraries that can be used for more advanced file handling:</p><ol><li><strong>os Module</strong></li></ol><ul><li>Provides functions for interacting with the operating system, including file operations like deleting, renaming, and more.</li><li>Common functions:</li><li><strong>os.remove(filename)</strong>: Deletes a file.</li><li><strong>os.rename(src, dst)</strong>: Renames a file or directory.</li><li><strong>os.mkdir(directory_name)</strong>: Creates a new directory.</li><li><strong>os.rmdir(directory_name)</strong>: Removes an empty directory.</li><li><strong>os.path.exists(path)</strong>: Checks if the path exists.</li></ul><p><strong>2. shutil Module</strong></p><ul><li>For high-level file operations like copying and moving files.</li><li>Common functions:</li><li><strong>shutil.copy(src, dst)</strong>: Copies a file.</li><li><strong>shutil.move(src, dst)</strong>: Moves a file or directory.</li><li><strong>shutil.rmtree(directory_name)</strong>: Removes a directory and all its contents.</li></ul><p><strong>3. pathlib Module</strong></p><ul><li>Introduced in Python 3.4, this module provides an object-oriented approach to file handling and path operations.</li><li>Useful classes and methods:</li><li><strong>Path()</strong>: Creates a Path object.</li><li><strong>Path.exists()</strong>: Checks if the path exists.</li><li><strong>Path.is_file()</strong>: Checks if the path is a file.</li><li><strong>Path.is_dir()</strong>: Checks if the path is a directory.</li><li><strong>Path.open(mode)</strong>: Opens the file with the specified mode.</li><li><strong>Path.mkdir()</strong>: Creates a directory.</li></ul><p><strong>4. tempfile Module</strong></p><ul><li>This module generates temporary files and directories.</li><li>Common functions:</li><li><strong>tempfile.TemporaryFile()</strong>: Creates a temporary file that will be deleted once it is closed.</li><li><strong>tempfile.NamedTemporaryFile()</strong>: Similar to TemporaryFile, but the file has a visible name in the file system.</li><li><strong>tempfile.TemporaryDirectory()</strong>: Creates a temporary directory that will be deleted when it is no longer needed.</li></ul><p><strong>5. pickle Module</strong></p><ul><li>Used for serializing and deserializing Python objects (object serialization).</li><li>Useful when you want to save Python objects to a file and retrieve them later.</li></ul><pre>import pickle<br><br># Saving an object<br>with open(&#39;data.pkl&#39;, &#39;wb&#39;) as file:<br>    pickle.dump(my_object, file)<br><br># Loading an object<br>with open(&#39;data.pkl&#39;, &#39;rb&#39;) as file:<br>    my_object = pickle.load(file)</pre><h4>Example</h4><pre># Writing to a file<br>with open(&#39;example.txt&#39;, &#39;w&#39;) as file:<br>    file.write(&#39;Hello, World!\n&#39;)<br><br># Reading from a file<br>with open(&#39;example.txt&#39;, &#39;r&#39;) as file:<br>    content = file.read()<br>    print(content)<br><br># Appending to a file<br>with open(&#39;example.txt&#39;, &#39;a&#39;) as file:<br>    file.write(&#39;Appended text\n&#39;)<br><br># Using os to delete the file<br>import os<br>if os.path.exists(&#39;example.txt&#39;):<br>    os.remove(&#39;example.txt&#39;)</pre><h4>Best Practices</h4><ul><li>Always close files after you’re done using them (use with statements).</li><li>Handle exceptions when working with files to prevent data loss.</li><li>Use the appropriate mode (&#39;r&#39;, &#39;w&#39;, &#39;a&#39;, &#39;b&#39;) depending on your needs.</li><li>Consider using pathlib for a more modern and object-oriented approach to file handling.</li></ul><p>By using the built-in functions and additional libraries like os, shutil, pathlib, tempfile, and pickle, Python provides a robust set of tools for file handling.</p><h4>Real scenario:-</h4><p>suppose you have one folder(<strong>target folder</strong>)inside that you have multiple folder(inside this folder you have multiple file and folder) and file, <strong>first question</strong> is how you can delete everything inside that target folder without deleting target folder itself? and <strong>second question</strong> how you can delete everything inside that along with target folder?</p><h4>solution:-</h4><p><strong>1. Delete Everything Inside the Target Folder Without Deleting the Target Folder Itself</strong></p><p>To delete all files and subdirectories within a target folder but keep the target folder itself intact, you can use the following approach:</p><pre>import os<br>import shutil<br><br>def clear_target_folder_contents(target_folder):<br>    # Loop through all entries in the target folder<br>    for entry in os.listdir(target_folder):<br>        entry_path = os.path.join(target_folder, entry)<br>        if os.path.isdir(entry_path):<br>            shutil.rmtree(entry_path)  # Delete the directory and its contents<br>        elif os.path.isfile(entry_path):<br>            os.remove(entry_path)  # Delete the file<br><br># Specify the target folder<br>target_folder = &#39;/path/to/your/target_folder&#39;<br><br># Clear the contents of the target folder<br>clear_target_folder_contents(target_folder)</pre><p><strong>2. Delete Everything Inside the Target Folder Along with the Target Folder Itself</strong></p><p>To delete the target folder itself along with all its contents, you can use shutil.rmtree() directly on the target folder.</p><pre>import shutil<br><br># Specify the target folder<br>target_folder = &#39;/path/to/your/target_folder&#39;<br><br># Delete the target folder and all its contents<br>shutil.rmtree(target_folder)</pre><h3>Summary</h3><ol><li><strong>To delete only the contents inside the target folder without deleting the folder itself:</strong></li></ol><ul><li>Use os.listdir() to list all items.</li><li>Use os.path.join() to construct full paths.</li><li>Use shutil.rmtree() for subdirectories and os.remove() for files.</li></ul><p><strong>2. To delete the target folder and everything inside it:</strong></p><ul><li>Use shutil.rmtree() directly on the target folder.</li></ul><h4>Important Notes</h4><ul><li><strong>Be cautious with `shutil.rmtree()</strong>: It will delete everything in the specified directory tree. Always double-check the path to avoid accidental data loss.</li><li><strong>Test your scripts</strong>: Before running them on important directories, try them on test directories to ensure they work as expected.</li></ul><h3>Thank you for reading !!!</h3><p>If you enjoy this article and would like to <strong>Buy Me a Coffee, </strong><a href="https://ko-fi.com/ankushkunwar">please click here.</a></p><p>you can connect with me on <a href="https://www.linkedin.com/in/ankush-kunwar777/">Linkedin</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ccb38f96170" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multiprocessing vs multithreading with use case and Example:- Must Known Concept!!!]]></title>
            <link>https://ankushkunwar7777.medium.com/multiprocessing-vs-multithreading-with-use-case-and-example-must-known-concept-23dd0201d700?source=rss-5bfd1de25146------2</link>
            <guid isPermaLink="false">https://medium.com/p/23dd0201d700</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ankush kunwar]]></dc:creator>
            <pubDate>Sat, 10 Aug 2024 02:31:45 GMT</pubDate>
            <atom:updated>2024-08-10T02:31:45.602Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*3fyc55QFJmyHZvNvA05f8w.png" /></figure><p><strong>1. Understanding Multiprocessing and Multithreading:</strong></p><p><strong>Multiprocessing:</strong></p><ul><li><strong>Definition:</strong> Multiprocessing involves the use of two or more CPUs within a single computer system. In Python, this is achieved using the multiprocessing module, which allows multiple processes to run concurrently.</li><li><strong>How It Works:</strong> Each process runs independently, with its own memory space. This means that multiple processes can run in parallel on separate CPUs or cores, allowing for true parallelism.</li><li><strong>Use Case:</strong> Multiprocessing is particularly useful for CPU-bound tasks, such as mathematical computations, data processing, or any operation where the task needs significant CPU time.</li><li><strong>Example:</strong> If you’re running a computation-heavy program like <strong>processing large datasets</strong>, using multiprocessing can help distribute the <strong>workload across multiple processors, thereby speeding up execution.</strong></li></ul><p><strong>Multithreading:</strong></p><ul><li><strong>Definition:</strong> Multithreading involves running multiple threads (smaller units of a process) within a single process. Python supports multithreading through the threading module.</li><li><strong>How It Works:</strong> Threads share the same memory space but run concurrently. Due to Python’s Global Interpreter Lock (GIL), true parallelism isn’t achieved in multithreading; instead, threads take turns executing.</li><li><strong>Use Case:</strong> Multithreading is most effective for I/O-bound tasks, such as reading/writing files, network operations, or user interactions where the task involves waiting for an external resource.</li><li><strong>Example:</strong> When developing a web scraper that reads data from multiple websites, using multithreading allows one thread to wait for a network response while another thread processes data, leading to faster overall execution.</li></ul><p><strong>2. When to Use Multiprocessing vs. Multithreading:</strong></p><p><strong>Use Multiprocessing When:</strong></p><ul><li>The task is CPU-bound.</li><li>You need true parallelism.</li><li>The task can be divided into independent processes.</li><li>Example: Image processing, large-scale data computations.</li></ul><p><strong>Use Multithreading When:</strong></p><ul><li>The task is I/O-bound.</li><li>You are dealing with tasks that involve waiting (e.g., network requests).</li><li>The task requires shared resources or memory.</li><li>Example: Real-time applications, web servers, file I/O operations.</li></ul><p><strong>3. Code Examples:</strong></p><ul><li><strong>Multiprocessing Example:</strong></li></ul><pre>import multiprocessing<br><br>def compute_square(num):<br>    return num * num<br><br>if __name__ == &quot;__main__&quot;:<br>    numbers = [1, 2, 3, 4, 5]<br>    pool = multiprocessing.Pool(processes=4)<br>    result = pool.map(compute_square, numbers)<br>    print(result)</pre><ul><li><strong>Multithreading Example:</strong></li></ul><pre>import threading<br><br>def print_square(num):<br>    print(f&quot;Square: {num * num}&quot;)<br><br>if __name__ == &quot;__main__&quot;:<br>    threads = []<br>    for i in range(5):<br>        thread = threading.Thread(target=print_square, args=(i,))<br>        threads.append(thread)<br>        thread.start()<br><br>    for thread in threads:<br>        thread.join()</pre><p><strong>Lets deep dive more</strong></p><h4><strong>real world scenario</strong></h4><p><strong>suppose you are getting list of id from api and each it have 3000 or more document in dB and you have to move all document from one place to another how you can do efficiently ? <em>(so many solution we have but here i will tell just one using multithreading)</em></strong></p><h4><strong>Solution:</strong>-</h4><p>To efficiently handle the task of moving 3000 documents for each ID retrieved from an API, you can use a combination of <strong>multithreading</strong> and <strong>batch processing</strong>. The approach involves the following steps:</p><ol><li><strong>Fetch IDs from the API</strong>: Retrieve the list of IDs from the API.</li><li><strong>Fetch Document Paths</strong>: For each ID, retrieve or generate the list of document paths to be moved.</li><li><strong>Use Multithreading to Move Documents</strong>: Move the documents concurrently using multithreading.</li></ol><h4>Implementation Steps</h4><ol><li><strong>Fetching IDs and Document Paths</strong>:</li></ol><ul><li>Make an API call to retrieve the list of IDs.</li><li>For each ID, retrieve the corresponding document paths that need to be moved.</li></ul><p><strong>2. Moving Documents with Multithreading</strong>:</p><ul><li>Use a thread pool to move documents in parallel.</li><li>Batch the document moves to optimize resource usage</li></ul><p><strong>Implementation</strong></p><p><strong>Python Code Example</strong> <strong><em>(this is one way you can do multiple way)</em></strong></p><pre>import requests<br>import os<br>import shutil<br>import threading<br>from queue import Queue<br><br># Step 1: Fetch IDs from API<br>def fetch_ids(api_url):<br>    response = requests.get(api_url)<br>    if response.status_code == 200:<br>        return response.json()  # Assuming the response is a JSON array of IDs<br>    else:<br>        response.raise_for_status()<br><br># Step 2: Fetch document paths for each ID<br>def fetch_document_paths(id):<br>    # This function should return a list of file paths for the given ID<br>    # Example:<br>    return [f&quot;/path_to_source_directory/{id}/doc_{i}.txt&quot; for i in range(3000)]<br><br># Step 3: Move files using multithreading<br>def move_file(file_path, destination_dir):<br>    try:<br>        shutil.move(file_path, destination_dir)<br>        print(f&quot;Moved: {file_path}&quot;)<br>    except Exception as e:<br>        print(f&quot;Error moving {file_path}: {e}&quot;)<br><br>def worker(queue, destination_dir):<br>    while not queue.empty():<br>        file_path = queue.get()<br>        move_file(file_path, destination_dir)<br>        queue.task_done()<br><br>def move_documents_for_id(id, destination_dir, num_threads=10):<br>    # Get the list of document paths for this ID<br>    document_paths = fetch_document_paths(id)<br>    <br>    # Create a thread-safe queue<br>    file_queue = Queue()<br>    <br>    # Add all document paths to the queue<br>    for file_path in document_paths:<br>        file_queue.put(file_path)<br>    <br>    # Create threads<br>    threads = []<br>    for _ in range(num_threads):<br>        thread = threading.Thread(target=worker, args=(file_queue, destination_dir))<br>        thread.start()<br>        threads.append(thread)<br>    <br>    # Wait for all threads to finish<br>    for thread in threads:<br>        thread.join()<br>    <br>    print(f&quot;All documents for ID {id} moved successfully!&quot;)<br><br># Main function to execute the full operation<br>def main(api_url, destination_dir):<br>    ids = fetch_ids(api_url)<br>    <br>    for id in ids:<br>        print(f&quot;Processing ID: {id}&quot;)<br>        move_documents_for_id(id, destination_dir)<br><br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    API_URL = &quot;https://api.example.com/get_ids&quot;  # Replace with your API endpoint<br>    DESTINATION_DIR = &quot;/path_to_destination_directory&quot;  # Replace with your destination directory<br><br>    main(API_URL, DESTINATION_DIR)</pre><h3>Thank you for reading !!!</h3><p>If you enjoy this article and would like to <strong>Buy Me a Coffee, </strong><a href="https://ko-fi.com/ankushkunwar">please click here.</a></p><p>you can connect with me on <a href="https://www.linkedin.com/in/ankush-kunwar777/">Linkedin</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23dd0201d700" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design:- Messaging Queue]]></title>
            <link>https://ankushkunwar7777.medium.com/system-design-messaging-queue-2b18b1cd9ff3?source=rss-5bfd1de25146------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b18b1cd9ff3</guid>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ankush kunwar]]></dc:creator>
            <pubDate>Fri, 09 Aug 2024 15:23:24 GMT</pubDate>
            <atom:updated>2024-08-09T15:23:24.904Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*hu15jRGd2UeRugxAG1-BVw.png" /></figure><h3>What is Messaging Queue?</h3><p>A <strong>messaging queue</strong> is a form of asynchronous service-to-service communication used in serverless and microservices architectures. In this model, message queues provide a buffer for data being transferred from one service to another. The queue acts as a temporary storage where messages (data) are stored until they are processed by the consuming service.</p><h3>Why Use a Messaging Queue?</h3><ol><li><strong>Decoupling</strong>: Messaging queues decouple the sender (producer) and receiver (consumer). This allows each component to operate independently, enhancing modularity and maintainability.</li><li><strong>Load Balancing</strong>: They distribute the workload across multiple consumers, which helps in balancing the load and improving system reliability and scalability.</li><li><strong>Reliability</strong>: They ensure that messages are not lost and can be processed even if the consumer is temporarily unavailable. Messages can be persisted until they are successfully processed.</li><li><strong>Asynchronous Processing</strong>: They allow tasks to be processed asynchronously, which can improve the responsiveness and performance of an application. For example, a web server can quickly respond to user requests and offload time-consuming tasks to a background worker.</li><li><strong>Scalability</strong>: As the system grows, messaging queues can help manage increased load by adding more consumers without significantly changing the architecture.</li></ol><h3>How Does a Messaging Queue Work?</h3><ol><li><strong>Producer</strong>: The producer is the entity that sends messages to the queue. It can be any part of the system that generates tasks or data that needs to be processed.</li><li><strong>Queue</strong>: The queue stores messages until they are processed. It acts as a buffer between the producer and the consumer. The queue can be hosted on various platforms like Redis, RabbitMQ, AWS SQS, etc.</li><li><strong>Consumer</strong>: The consumer reads messages from the queue and processes them. There can be one or multiple consumers processing messages concurrently.</li><li><strong>Processing</strong>: After processing, the consumer can either acknowledge the message (indicating successful processing) or requeue it (if processing failed).</li></ol><h3>Use Cases for Messaging Queues</h3><ol><li><strong>Order Processing in E-commerce</strong>:</li></ol><ul><li>When a user places an order, the order details are sent to a queue. Various services (inventory management, payment processing, shipping, etc.) consume the order details asynchronously, ensuring that the order is processed efficiently and the system remains responsive.</li></ul><p><strong>2. Log Aggregation</strong>:</p><ul><li>Logs from different parts of a system are sent to a queue. A logging service consumes these messages and stores them in a centralized log management system. This ensures that logging does not impact the performance of the primary application.</li></ul><p><strong>3. Task Scheduling</strong>:</p><ul><li>Background tasks like sending emails, generating reports, or processing images can be queued and processed by worker services. This ensures that the main application remains responsive to user interactions.</li></ul><p><strong>4. Microservices Communication</strong>:</p><ul><li>In a microservices architecture, services can communicate with each other via message queues. This decouples the services and ensures that they can scale independently.</li></ul><p><strong>5. Data Pipeline</strong>:</p><ul><li>In data processing pipelines, data from various sources (e.g., IoT devices) can be sent to a queue. Processing services consume this data, perform transformations, and store the results in a data warehouse.</li></ul><h3>Implement using Python</h3><h4>Steps:</h4><h4><strong>Install Redis and </strong><strong>redis-py</strong>.</h4><p>First, you need to have Redis installed and running on your machine. You can download and install Redis from Redis.io.</p><p>Next, install the redis-py library using pip:</p><pre>pip install redis</pre><h4><strong>Create the RedisQueue class</strong>.</h4><p>This class will handle basic queue operations using Redis.</p><pre>import redis<br><br>class RedisQueue:<br>    def __init__(self, name, namespace=&#39;queue&#39;, **redis_kwargs):<br>        self.__db = redis.Redis(**redis_kwargs)<br>        self.key = f&#39;{namespace}:{name}&#39;<br><br>    def qsize(self):<br>        &quot;&quot;&quot;Return the approximate size of the queue.&quot;&quot;&quot;<br>        return self.__db.llen(self.key)<br><br>    def is_empty(self):<br>        &quot;&quot;&quot;Return True if the queue is empty, False otherwise.&quot;&quot;&quot;<br>        return self.qsize() == 0<br><br>    def enqueue(self, item):<br>        &quot;&quot;&quot;Put item into the queue.&quot;&quot;&quot;<br>        self.__db.rpush(self.key, item)<br>        print(f&quot;Enqueued: {item}&quot;)<br><br>    def dequeue(self, block=True, timeout=None):<br>        &quot;&quot;&quot;Remove and return an item from the queue.<br><br>        If optional args block is true and timeout is None (the default), block<br>        if necessary until an item is available.&quot;&quot;&quot;<br>        if block:<br>            item = self.__db.blpop(self.key, timeout=timeout)<br>        else:<br>            item = self.__db.lpop(self.key)<br><br>        if item:<br>            item = item[1].decode(&#39;utf-8&#39;)<br>            print(f&quot;Dequeued: {item}&quot;)<br>            return item<br>        else:<br>            print(&quot;Queue is empty&quot;)<br>            return None<br><br>    def peek(self):<br>        &quot;&quot;&quot;Return the next item in the queue without removing it.&quot;&quot;&quot;<br>        item = self.__db.lindex(self.key, 0)<br>        if item:<br>            item = item.decode(&#39;utf-8&#39;)<br>            print(f&quot;Peeked: {item}&quot;)<br>            return item<br>        else:<br>            print(&quot;Queue is empty&quot;)<br>            return None</pre><h4><strong>Create a Producer class</strong>.</h4><p>This class will add messages to the queue.</p><pre>class Producer:<br>    def __init__(self, queue):<br>        self.queue = queue<br><br>    def produce(self, message):<br>        self.queue.enqueue(message)<br><br>if __name__ == &quot;__main__&quot;:<br>    queue = RedisQueue(&#39;test&#39;, host=&#39;localhost&#39;, port=6379, db=0)<br>    producer = Producer(queue)<br><br>    # Produce some messages<br>    producer.produce(&#39;task1&#39;)<br>    producer.produce(&#39;task2&#39;)<br>    producer.produce(&#39;task3&#39;)</pre><h4><strong>Create a Worker class</strong>.</h4><p>This class will consume messages from the queue and process them.</p><pre>import time<br><br>class Worker:<br>    def __init__(self, queue):<br>        self.queue = queue<br><br>    def process_message(self, message):<br>        # Process the message<br>        print(f&quot;Processing message: {message}&quot;)<br><br>    def run(self):<br>        while True:<br>            message = self.queue.dequeue()<br>            if message:<br>                self.process_message(message)<br>            else:<br>                time.sleep(1)<br><br>if __name__ == &quot;__main__&quot;:<br>    queue = RedisQueue(&#39;test&#39;, host=&#39;localhost&#39;, port=6379, db=0)<br>    worker = Worker(queue)<br>    worker.run()</pre><h4>Running the Example</h4><p><strong>Run the Producer</strong>:</p><ul><li>Run the producer.py to enqueue some messages</li></ul><pre>python producer.py</pre><p><strong>Run the Worker</strong>:</p><ul><li>Run the worker.py to start processing messages</li></ul><pre>python worker.py</pre><h3>Summary</h3><ul><li><strong>Messaging Queue</strong>: A system for asynchronous communication between services.</li><li><strong>Why Use It</strong>: For decoupling, load balancing, reliability, asynchronous processing, and scalability.</li><li><strong>How It Works</strong>: Producers enqueue messages, queues store them, and consumers dequeue and process them.</li><li><strong>Use Cases</strong>: Order processing, log aggregation, task scheduling, microservices communication, and data pipelines.</li></ul><p>This approach ensures a robust and scalable architecture suitable for a wide range of applications.</p><h3>Thank you for reading !!!</h3><p>If you enjoy this article and would like to <strong>Buy Me a Coffee, </strong><a href="https://ko-fi.com/ankushkunwar">please click here.</a></p><p>you can connect with me on <a href="https://www.linkedin.com/in/ankush-kunwar777/">Linkedin</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b18b1cd9ff3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design: Horizontal Scaling vs Vertical Scaling]]></title>
            <link>https://ankushkunwar7777.medium.com/system-design-horizontal-scaling-vs-vertical-scaling-833c8a5f159f?source=rss-5bfd1de25146------2</link>
            <guid isPermaLink="false">https://medium.com/p/833c8a5f159f</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ankush kunwar]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 08:31:43 GMT</pubDate>
            <atom:updated>2024-01-31T08:31:43.212Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JH4N7C199Gl3dhc2sh3xHQ.png" /></figure><p><strong>Horizontal scaling</strong> and <strong>vertical scaling</strong> are two strategies used to increase the capacity of a system to handle more load or users. Let’s explore these concepts in depth with real-world scenarios:</p><h3>Horizontal Scaling:</h3><p>Horizontal scaling, also known as scaling out, involves adding more instances or nodes to a system to distribute the load across multiple machines. Each instance operates independently, and requests can be routed to any available instance.</p><p><strong>Real-world scenario</strong>: Consider a popular e-commerce website experiencing a surge in traffic during holiday sales. To handle the increased load, the company decided to horizontally scale its web servers. Instead of relying on a single web server, they deploy multiple instances of their application across different servers or cloud instances. A load balancer distributes incoming requests across these instances, ensuring that no single server becomes overwhelmed. As traffic subsides after the holiday season, the company can scale back down by reducing the number of instances.</p><p>Key Characteristics:</p><ol><li><strong>Additive Capacity</strong>: Horizontal scaling involves adding more instances or nodes to the system.</li><li><strong>Decoupled Instances</strong>: Instances operate independently, and adding or removing instances does not affect the overall system architecture.</li><li><strong>Load Balancing</strong>: A load balancer distributes incoming requests across multiple instances, ensuring an even distribution of load.</li></ol><h3>Vertical Scaling:</h3><p>Vertical scaling, also known as scaling up, involves increasing the capacity of individual instances by adding more resources, such as CPU, memory, or storage, to existing machines.</p><p><strong>Real-world scenario</strong>: Imagine a database server running out of resources due to an increase in data volume and concurrent queries. Instead of adding more database servers, the company decides to vertically scale the existing server by upgrading its hardware. They add more CPU cores, increase RAM capacity, and switch to faster storage drives. This allows the database server to handle more concurrent connections and process queries more efficiently without the need for additional instances.</p><p>Key Characteristics:</p><ol><li><strong>Increased Resources</strong>: Vertical scaling involves upgrading the resources (CPU, memory, and storage) of existing instances.</li><li><strong>Limited Scalability</strong>: There’s a limit to how much an instance can be scaled vertically, depending on hardware limitations.</li><li><strong>Potential Downtime</strong>: Vertical scaling often requires downtime or maintenance windows to perform hardware upgrades.</li></ol><h3>Choosing Between Horizontal and Vertical Scaling:</h3><p><strong>Horizontal Scaling</strong>:</p><ul><li>Ideal for distributed architectures and stateless applications.</li><li>Provides better fault tolerance and scalability for handling unpredictable traffic spikes.</li><li>Can be more cost-effective by leveraging commodity hardware and cloud instances.</li><li>Requires effective load balancing and management of distributed systems.</li></ul><p><strong>Vertical Scaling</strong>:</p><ul><li>Suitable for applications with tightly coupled components or databases with high transactional workloads.</li><li>Offers simpler management and maintenance as there are fewer instances to manage.</li><li>May require a significant upfront investment in high-end hardware.</li><li>Can be limited by the scalability ceiling of individual instances.</li></ul><p>In practice, many organizations use a combination of horizontal and vertical scaling to achieve optimal performance, scalability, and cost efficiency for their systems. The choice between the two approaches depends on factors such as the nature of the workload, budget constraints, scalability requirements, and architectural considerations.</p><h3>Thank you for reading!!!</h3><p>If you enjoyed this article and would like to <strong>buy me a coffee, </strong><a href="https://ko-fi.com/ankushkunwar">please click here.</a></p><p>You can connect with me on <a href="https://www.linkedin.com/in/ankush-kunwar777/">Linkedin</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=833c8a5f159f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[System Design: Everything Thing About Load Balancer]]></title>
            <link>https://ankushkunwar7777.medium.com/system-design-everything-thing-about-load-balancer-527e95e83c3c?source=rss-5bfd1de25146------2</link>
            <guid isPermaLink="false">https://medium.com/p/527e95e83c3c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Ankush kunwar]]></dc:creator>
            <pubDate>Tue, 30 Jan 2024 08:31:38 GMT</pubDate>
            <atom:updated>2024-01-30T08:31:38.270Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*-bN42Y9qc-hfVMxD3isqXg.jpeg" /></figure><p>A load balancer is a critical component in modern distributed systems architecture, used to distribute incoming network traffic across multiple servers or resources to ensure optimal utilization, improve reliability, and enhance performance. Let’s delve into various aspects of load balancers:</p><h3>1. Purpose:</h3><ul><li>Traffic Distribution: Load balancers evenly distribute incoming traffic among multiple servers, preventing any single server from becoming overwhelmed.</li><li>Fault Tolerance: Load balancers can detect and redirect traffic away from failed or unhealthy servers, ensuring high availability.</li><li>Scalability: Load balancers facilitate horizontal scaling by allowing new servers to be added to the pool dynamically.</li></ul><h3>2. Types of load balancers:</h3><ul><li>Layer 4 (Transport Layer) Load Balancers: These operate at the transport layer (e.g., TCP/UDP) and make routing decisions based on network-level information such as IP addresses and ports.</li><li>Layer 7 (Application Layer) Load Balancers: These operate at the application layer (e.g., HTTP) and can make routing decisions based on application-level data such as HTTP headers, URLs, or session information.</li></ul><h3>3. Load Balancing Algorithms:</h3><ul><li><strong>Round Robin</strong>: Requests are distributed sequentially to each server in the pool.</li><li><strong>Least Connections</strong>: Requests are sent to the server with the fewest active connections.</li><li><strong>IP Hash</strong>: Uses the client’s IP address to determine which server receives the request.</li><li><strong>Weighted Round Robin</strong>: Assigns each server a weight, directing more traffic to servers with higher weights.</li></ul><h3>4. Health Checks:</h3><ul><li>Load balancers perform periodic health checks on backend servers to ensure they are responsive and able to handle requests.</li><li>Unhealthy servers are temporarily removed from the pool until they become healthy again.</li></ul><h3>5. Session Persistence:</h3><ul><li>Some applications require session persistence, ensuring that subsequent requests from the same client are directed to the same backend server.</li><li>Techniques like cookie-based affinity or IP-based affinity can be employed to achieve session persistence.</li></ul><h3>6. SSL Termination:</h3><ul><li>Load balancers can offload SSL/TLS decryption and encryption, relieving backend servers of this computational overhead.</li><li>This improves performance and simplifies the management of SSL certificates.</li></ul><h3>7. High Availability and Redundancy:</h3><ul><li>Load balancers themselves can be deployed in a redundant configuration to prevent single points of failure.</li><li>Techniques like active-passive failover or active-active clustering ensure continuous operation even in the event of load balancer failures.</li></ul><h3>8. Logging and Monitoring:</h3><ul><li>Load balancers often provide logging and monitoring capabilities to track traffic patterns, server health, and overall system performance.</li><li>Integrating with logging and monitoring solutions allows for proactive management and troubleshooting.</li></ul><h3>9. Cloud Load Balancers:</h3><ul><li>Cloud providers offer load-balancing services tailored to their platforms, such as AWS Elastic Load Balancing or Google Cloud Load Balancing.</li><li>These services are highly scalable, automatically provisioned, and integrated with other cloud services.</li></ul><h3>10. Security Considerations:</h3><ul><li>Load balancers can act as a security perimeter, providing features like access control, DDoS protection, and web application firewall (WAF) capabilities.</li><li>They can help mitigate attacks by distributing traffic and filtering malicious requests.</li></ul><h3>11. Performance Tuning:</h3><ul><li>Fine-tuning load balancer settings, such as connection timeouts, keep-alive intervals, and buffer sizes, can optimize performance and resource utilization.</li></ul><h3>12. Cost Considerations:</h3><ul><li>While load balancers improve system reliability and scalability, they also add costs, both in terms of hardware and software and operational overhead.</li><li>Understanding and optimizing cost factors such as traffic volume, bandwidth, and service tier selection are essential.</li></ul><h3>13. Integration with Auto-Scaling:</h3><ul><li>Load balancers seamlessly integrate with auto-scaling mechanisms to dynamically adjust server capacity based on workload demand.</li><li>This ensures that resources are scaled up or down automatically in response to changing traffic patterns.</li></ul><h3>14. Global Load Balancing:</h3><ul><li>For geographically distributed applications, global load balancers route traffic to the nearest available server location, optimizing latency and providing redundancy across regions.</li></ul><p>Load balancers play a crucial role in ensuring the reliability, scalability, and performance of modern distributed systems, making them a foundational component in cloud-native architectures and high-traffic web applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=527e95e83c3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>