<?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 Lekhana R on Medium]]></title>
        <description><![CDATA[Stories by Lekhana R on Medium]]></description>
        <link>https://medium.com/@lekhanar939?source=rss-75ee563cd5ff------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aQ1Rx0fOuqNp3z3hjtYq3g@2x.jpeg</url>
            <title>Stories by Lekhana R on Medium</title>
            <link>https://medium.com/@lekhanar939?source=rss-75ee563cd5ff------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 11:51:50 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lekhanar939/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[Leaky Bucket Rate Limiting: Smoothing Traffic Like Water Flow]]></title>
            <link>https://medium.com/@lekhanar939/leaky-bucket-rate-limiting-smoothing-traffic-like-water-flow-2d411fcd5e35?source=rss-75ee563cd5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d411fcd5e35</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[rest-api]]></category>
            <dc:creator><![CDATA[Lekhana R]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 15:48:42 GMT</pubDate>
            <atom:updated>2026-07-01T15:48:42.549Z</atom:updated>
            <content:encoded><![CDATA[<p>How Leaky Bucket protects your backend from sudden traffic spikes by processing requests at a constant rate.</p><h3>Introduction</h3><p>In the previous article, we explored the <strong>Token Bucket</strong> algorithm, one of the most widely used rate-limiting techniques in modern backend systems.</p><p>Unlike window-based algorithms, Token Bucket allows applications to handle <strong>short bursts of traffic</strong> while maintaining a controlled long-term request rate.</p><p>For example, imagine opening your favorite social media app. Within a second, your phone may request your profile, notifications, feed, messages, recommendations, and advertisements — all at once. Token Bucket handles this scenario gracefully by allowing the application to use tokens that have accumulated during idle time.</p><p>But here’s an interesting question.</p><p><strong>What if our backend cannot handle bursts at all?</strong></p><p>Consider a payment processing system.</p><pre>💳 Payment Transactions<br><br>or<br><br>📧 Email Notifications</pre><p>Would you want 500 payment requests to hit your payment gateway in the same second?</p><p>Probably not.</p><p>Even if the requests are legitimate, processing them all at once could overload downstream services, increase database contention, or degrade response times.</p><p>Instead of allowing bursts, what if we could process requests at a <strong>steady, predictable rate</strong>?</p><p>This is exactly the problem the <strong>Leaky Bucket</strong> algorithm solves.</p><h3>Understanding the Problem</h3><p>Imagine you’re filling a sink with water.</p><p>You pour water into the sink very quickly.</p><p>However, the drain at the bottom only allows water to leave at a fixed speed.</p><p>No matter how fast you pour water, the water always exits at the same rate.</p><pre>      Water<br>💧💧💧💧💧💧💧<br>        │<br>        ▼<br>   ┌─────────┐<br>   │         │<br>   │  Bucket │<br>   │         │<br>   └────┬────┘<br>        │<br>      💧<br>      💧<br>      💧<br><br>Constant Leak</pre><p>This is exactly how the Leaky Bucket algorithm behaves.</p><h3>The Core Idea</h3><pre>Instead of immediately processing every incoming request:<br>Request 1<br>Request 2<br>Request 3<br>Request 4<br>Request 5<br><br>the requests are placed inside a queue.<br>┌──────────────────────┐<br>│ R1 │ R2 │ R3 │ R4 │ R5 │<br>└──────────────────────┘<br><br>The system then processes them one by one at a fixed speed.<br>example:<br>Processing Rate<br><br>1 Request / Second<br>Even if ten requests arrive simultaneously, they leave the bucket one at a time.<br><br><br><br>---------------------------------------------------------------------<br>//Arrival Rate<br>How Fast Requestes arrive<br>💥💥💥💥💥💥💥💥💥<br><br>This is outside our control.<br><br>//Processing Rate<br><br>How fast our application handles requests.<br>💧<br><br>💧<br><br>💧<br><br>💧<br><br>This is under our control.<br><br>Leaky Bucket ensures that the processing rate remains constant, regardless of how bursty the incoming traffic is.<br></pre><h3>Think of It Like a Queue</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PWTax-SR0uZuQCU-uAu3gw.png" /></figure><p>Imagine you’re standing in line at a coffee shop.</p><p>Ten customers walk in at the same time.</p><p>Does the barista prepare ten coffees simultaneously?</p><p>No.</p><p>Customers wait in a queue.</p><p>The barista prepares one coffee at a time.</p><p>The queue absorbs the burst, while the service rate remains constant.</p><p>The Leaky Bucket algorithm works in exactly the same way.</p><h3>Visual Example</h3><pre>//suppose<br>Bucket Capacity = 5 requests<br><br>Leak Rate = 1 request/sec<br><br>//initially<br>Queue<br><br>[ ]<br><br>//Five requests arrive instantly.<br>Queue<br><br>[R1][R2][R3][R4][R5]<br><br>The bucket is now full.<br><br>//One second later:<br>Processed : R1<br><br>Queue<br><br>[R2][R3][R4][R5]<br><br>//Another second later:<br>Processed : R2<br><br>Queue<br><br>[R3][R4][R5]<br><br>Traffic leaving the system is smooth and predictable.</pre><h4>What Happens When the Bucket Is Full?</h4><pre>Suppose the queue can hold only five requests.<br>//Current state:<br>[R1][R2][R3][R4][R5]<br><br>//A new request arrives.<br>R6<br><br>There is no space left.<br>The request is rejected immediately.<br><br>HTTP 429<br><br>Too Many Requests<br><br>//Unlike Token Bucket, Leaky Bucket does not allow unlimited bursts.<br>//Once the queue reaches its maximum capacity, excess requests are dropped.</pre><h3>How the Algorithm Works</h3><pre>Every incoming request follows these steps:<br><br>            Request<br>               │<br>               ▼<br>     Is Queue Full?<br>        /        \<br>      No          Yes<br>      │            │<br>      ▼            ▼<br> Add Request    Reject (429)<br>      │<br>      ▼<br>Wait for Processing<br>      │<br>      ▼<br>Process at Fixed Rate<br><br>-----------------------------------------------<br><br>Notice something important:<br><br>The arrival rate can be unpredictable.<br><br>The processing rate is always constant.<br><br>That is the defining characteristic of the Leaky Bucket algorithm.</pre><h4>Java Implementation</h4><pre>import java.util.Queue;<br>import java.util.concurrent.ConcurrentLinkedQueue;<br><br>public class LeakyBucket {<br><br>    private final int capacity;<br>    private final Queue&lt;String&gt; queue = new ConcurrentLinkedQueue&lt;&gt;();<br><br>    public LeakyBucket(int capacity) {<br>        this.capacity = capacity;<br>    }<br><br>    public boolean allowRequest(String requestId) {<br><br>        if (queue.size() &gt;= capacity) {<br>            return false;<br>        }<br><br>        queue.offer(requestId);<br>        return true;<br>    }<br><br>    public void processRequest() {<br><br>        String request = queue.poll();<br><br>        if (request != null) {<br>            System.out.println(&quot;Processing &quot; + request);<br>        }<br>    }<br>}<br>//In a real application, processRequest() would typically be executed by a scheduled task running at a fixed interval.</pre><h4>Dry Run</h4><pre>//configuration :<br><br>Capacity = 5<br><br>Leak Rate = 1 request/sec<br><br>//Time = 0 seconds<br>Queue<br><br>[ ]<br><br>//Five requests arrive.<br>[R1][R2][R3][R4][R5]<br><br>//Time = 1 second<br>Process R1<br><br>Queue<br><br>[R2][R3][R4][R5]<br><br>//Time = 2 seconds<br><br>Process R2<br><br>Queue<br><br>[R3][R4][R5]<br><br>//Time = 3 seconds<br><br>Process R3<br><br>Queue<br><br>[R4][R5]<br><br>Every second, exactly one request leaves the bucket.</pre><h4>Time Complexity</h4><p>Enqueue request: O(1)</p><p>Process request :O(1)</p><p>Memory :O(bucket capacity)</p><h4>Leaky Bucket vs Token Bucket</h4><pre>| Feature                | Token Bucket | Leaky Bucket                                           |<br>| ---------------------- | ------------ | ------------------------------------------------------ |<br>| Allows bursts          | ✅ Yes        | ❌ No                                                   |<br>| Smooth output traffic  | ❌ No         | ✅ Yes                                                  |<br>| Stores tokens          | ✅ Yes        | ❌ No                                                   |<br>| Stores queued requests | ❌ No         | ✅ Yes                                                  |<br>| Best for               | Public APIs  | Payment systems, message queues, downstream protection |</pre><h3>Real-World Use Cases</h3><p>Leaky Bucket is a great fit when downstream systems have a fixed processing capacity, such as:</p><ul><li>Payment gateways</li><li>Database write queues</li><li>Email sending services</li><li>SMS delivery systems</li><li>Job schedulers</li><li>Message brokers</li><li>IoT event processing</li></ul><p>The goal is not just to limit requests — but to <strong>smooth traffic</strong> so that dependent systems remain stable.</p><h3>When Should You Choose Leaky Bucket?</h3><p>Choose Leaky Bucket when:</p><ul><li>You need predictable processing rates.</li><li>Bursts should be absorbed, not executed immediately.</li><li>Downstream services are sensitive to traffic spikes.</li><li>A queue is acceptable, and slight delays are preferable to overload.</li></ul><p>Choose Token Bucket when:</p><ul><li>Short bursts are expected and acceptable.</li><li>You want to improve user experience during brief periods of high activity.</li><li>Immediate processing is more important than perfectly smooth traffic.</li></ul><h3>Conclusion</h3><p>Throughout this series, we’ve gradually improved our approach to rate limiting:</p><ul><li><strong>Fixed Window Counter</strong> introduced the concept of counting requests but suffered from the boundary problem.</li><li><strong>Sliding Window Log</strong> solved that issue by tracking every request, at the cost of higher memory usage.</li><li><strong>Sliding Window Counter</strong> reduced memory consumption while maintaining good accuracy through weighted estimation.</li><li><strong>Token Bucket</strong> embraced bursty traffic, allowing users to consume accumulated tokens while enforcing a long-term average rate.</li><li><strong>Leaky Bucket</strong> takes a different approach: instead of allowing bursts, it smooths traffic into a steady flow, protecting downstream systems from sudden spikes.</li></ul><blockquote>The key takeaway is that <strong>there is no single “best” rate-limiting algorithm</strong>. Each one is designed to solve a different problem.</blockquote><p>A well-designed backend chooses the algorithm based on the behavior it wants to encourage — whether that’s strict fairness, memory efficiency, burst tolerance, or smooth, predictable traffic.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d411fcd5e35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Token Bucket: The Rate Limiting Algorithm Used in Production Systems]]></title>
            <link>https://medium.com/@lekhanar939/token-bucket-the-rate-limiting-algorithm-used-in-production-systems-415b2905425d?source=rss-75ee563cd5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/415b2905425d</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Lekhana R]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 16:05:12 GMT</pubDate>
            <atom:updated>2026-06-30T16:05:12.713Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In our previous articles, we explored three popular rate-limiting algorithms.</p><p>We started with the <strong>Fixed Window Counter</strong>, which is simple to implement but suffers from the boundary problem.</p><p>We then improved accuracy using <strong>Sliding Window Log</strong>, which stores every request timestamp. While highly accurate, it consumes significant memory under heavy traffic.</p><p>Next, we introduced <strong>Sliding Window Counter</strong>, which reduces memory usage by estimating requests using weighted counters instead of storing every timestamp.</p><p>Although Sliding Window Counter offers an excellent balance between accuracy and memory, it still has one limitation.</p><p>It assumes requests are evenly distributed throughout the time window.</p><p>Real-world traffic rarely behaves that way.</p><p>Users don’t send requests at a perfectly constant rate.</p><p>Instead, traffic is bursty.</p><p>For example:</p><pre>User Activity<br><br>No requests for 20 seconds<br>↓<br><br>Suddenly 30 requests in 2 seconds<br><br>↓<br><br>No requests again</pre><p>Modern applications should allow these short bursts while still enforcing a long-term request rate.</p><p>This is exactly what the <strong>Token Bucket</strong> algorithm is designed to do.</p><h4>Why Do We Need Another Algorithm?</h4><p>Imagine an image upload API.</p><p>Suppose we configure:</p><pre>100 requests per minute</pre><p>A user opens the application after being inactive for a while.</p><p>The application immediately makes:</p><pre>Load Profile<br>Load Images<br>Load Notifications<br>Load Friends<br>Load Messages<br>Load Settings<br>...</pre><p>Maybe:</p><pre>30 requests</pre><p>within one second.</p><p>Should we reject them?</p><p>Probably not.</p><p>The user wasn’t abusing the API.</p><p>They were simply inactive and then became active.</p><p>Traditional window-based algorithms often struggle with these bursty traffic patterns.</p><p>Token Bucket solves this elegantly.</p><h3>Understanding the Core Idea</h3><pre>//Imagine a bucket filled with tokens.<br><br>        _________<br>       /         \<br>      | ● ● ● ● ● |<br>      | ● ● ● ● ● |<br>      |___________|<br><br>      Capacity = 10 <br><br>//Each incoming request needs one token.<br><br>Request<br>   ↓<br><br>Take one token<br><br>↓<br><br>If token exists<br>    Allow<br><br>Else<br>    Reject<br><br>//Instead of counting requests, we count available tokens.<br><br><br>--------------------------------------------------------------------<br><br>HOW TOKENS ARE GENERATED<br><br>//The bucket is automatically refilled over time.<br><br>Capacity = 10 tokens<br><br>Refill Rate = 2 tokens/sec<br><br>//Initially:<br>Bucket<br><br>🟢🟢🟢🟢🟢🟢🟢🟢🟢🟢<br><br>10 Tokens<br><br>//A user sends:<br><br>6 requests<br><br>//Remaining:<br><br>🟢🟢🟢🟢<br><br>4 Tokens<br><br>The user becomes inactive.<br><br>//After:<br><br>3 seconds<br><br>//New tokens arrive.<br><br>2 × 3 = 6 tokens<br><br>//Bucket becomes:<br>4 + 6 = 10<br><br>(Max capacity reached)<br><br>Notice something important.<br><br>The bucket never exceeds its capacity.</pre><h4>Why Bucket Capacity Matters</h4><pre>//suppose<br>Capacity = 10<br><br>//Even if the application remains idle for:<br>5 minutes<br><br>//The bucket is still:<br>10 Tokens<br><br>//not<br>600 Tokens<br><br>This prevents unlimited bursts</pre><h4>Request Flow</h4><pre>          Request<br>             │<br>             ▼<br>     Refill bucket<br>             │<br>             ▼<br>    Tokens Available?<br>        /         \<br>      Yes         No<br>      │            │<br>Consume Token   Reject (429)<br>      │<br>      ▼<br>Allow Request</pre><h4>Real Example</h4><pre>//configuration<br><br>Capacity = 5<br><br>Refill = 1 token/sec<br><br>//Initial state:<br><br>★★★★★<br><br>5 Tokens<br><br>Time = 0 sec-&gt;user sends -&gt;3 Request<br><br>//tokens<br>★★★★★<br><br>↓<br><br>★★-&gt;2 tokens remaining<br><br>Time = 2 sec-&gt;Buket refills -&gt; 2 token added<br><br>Bucket :<br>★★★★<br><br>User Sends 4 Requests<br><br>★★★★<br><br>↓<br><br>None<br><br>allowed -&gt;4request <br><br>//Another Request Immediately<br><br>Bucket -&gt; Empty -&gt; no token-&gt; result -&gt; HTTP 429<br><br>Too Many Requests<br><br></pre><h4>The Mathematics Behind Token Bucket</h4><pre>Every request starts by calculating how many new tokens should be added.<br><br>elapsedTime = currentTime - lastRefillTime<br><br><br>-------------------------------------------------------------------------<br><br>then<br>tokensToAdd<br><br>=<br><br>elapsedTime<br><br>×<br><br>refillRate<br><br>----------------------------------------------------------------------------<br>finally<br><br>currentTokens<br><br>=<br><br>min(<br><br>capacity,<br><br>currentTokens + tokensToAdd<br><br>)<br><br>This single calculation keeps the bucket synchronized with time.</pre><h4>Data Structure</h4><pre>Unlike Sliding Window Log:<br><br>-&gt;Store Every Timestamp<br><br><br>Token Bucket stores only four values.<br>-&gt;<br>class TokenBucket {<br><br>    int capacity;<br><br>    double tokens;<br><br>    double refillRate;<br><br>    long lastRefillTime;<br>}<br><br>-&gt;Memory: O(1) per user</pre><h4>Java Implementation (From Scratch)</h4><pre>public class TokenBucket {<br><br>    private final int capacity;<br>    private final double refillRate;<br><br>    private double tokens;<br>    private long lastRefillTimestamp;<br><br>    public TokenBucket(int capacity, double refillRate) {<br>        this.capacity = capacity;<br>        this.refillRate = refillRate;<br>        this.tokens = capacity;<br>        this.lastRefillTimestamp = System.currentTimeMillis();<br>    }<br><br>    public synchronized boolean allowRequest() {<br><br>        refill();<br><br>        if (tokens &gt;= 1) {<br>            tokens--;<br>            return true;<br>        }<br><br>        return false;<br>    }<br><br>    private void refill() {<br><br>        long now = System.currentTimeMillis();<br><br>        double elapsedSeconds =<br>                (now - lastRefillTimestamp) / 1000.0;<br><br>        double newTokens =<br>                elapsedSeconds * refillRate;<br><br>        tokens =<br>                Math.min(capacity, tokens + newTokens);<br><br>        lastRefillTimestamp = now;<br>    }<br>}<br><br>----------------------------------------------------------------<br><br>//Dry run :<br>Capacity = 5<br>Refill = 1 token/sec<br><br>initally <br>tokens =5<br><br>Request 1-&gt;tokens 5 -&gt; 1 consumed -&gt; 4 remaining<br><br>Allowed<br><br><br>Request 2-&gt;tokens 4 -&gt;2 consumed -&gt;2 remaining<br><br>Allowed<br><br><br>5 request later -&gt; token 0 -&gt;Rejected <br><br><br>Wait 3 seconds<br><br>Bucket -&gt; 0+3 tokens= 3<br><br>User can immediately send: 3 request </pre><h4>Complexity</h4><p>Time Complexity -&gt;O(1)</p><p>Memory -&gt; O(1)</p><p>No queues.No timestamps.No iteration.</p><h3>Advantages</h3><p>✅ Allows short traffic bursts</p><p>✅ Constant memory</p><p>✅ Constant time</p><p>✅ Easy to distribute</p><p>✅ Used by cloud providers</p><p>✅ Perfect for APIs</p><h3>Limitations</h3><p>❌ Less precise than Sliding Window Log</p><p>❌ Requires careful tuning of capacity and refill rate</p><p>❌ Slightly more complex than window-based counters</p><h4>Where Is Token Bucket Used?</h4><p>This algorithm powers many production systems, including:</p><ul><li>API gateways</li><li>Cloud services (AWS API Gateway uses a token bucket model)</li><li>NGINX rate limiting (conceptually similar burst control)</li><li>Kubernetes ingress controllers</li><li>Payment gateways</li><li>Authentication services</li><li>Microservices</li></ul><p>It is especially useful when applications need to <strong>allow occasional bursts while maintaining a predictable long-term request rate</strong>.</p><h4>Sliding Window Counter vs Token Bucket</h4><pre>| Feature        | Sliding Window Counter | Token Bucket             |<br>| -------------- | ---------------------- | ------------------------ |<br>| Allows bursts  | Limited                | ✅ Excellent              |<br>| Memory         | O(1)                   | O(1)                     |<br>| Time           | O(1)                   | O(1)                     |<br>| Accuracy       | High                   | High                     |<br>| Best For       | Strict request limits  | APIs with bursty traffic |<br>| Industry Usage | Moderate               | ⭐ Very High              |</pre><h3>Conclusion</h3><p>If Fixed Window Counter taught us <strong>how to count requests</strong>, and Sliding Window Log taught us <strong>how to measure requests accurately</strong>, then Token Bucket teaches us something even more important:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-0shd3dS31bPAWpbmgXjQ.png" /></figure><blockquote><strong><em>Not all traffic is malicious.</em></strong></blockquote><p>Real users don’t interact with applications at a constant pace. They pause, browse, refresh pages, upload files, and perform actions in bursts.</p><p>Token Bucket embraces this behavior by allowing controlled bursts while ensuring that the average request rate remains within the configured limits.</p><p>This combination of <strong>fairness, efficiency, and scalability</strong> is why Token Bucket has become one of the most widely adopted rate-limiting algorithms in modern backend systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=415b2905425d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sliding Window Counter: Achieving Accuracy Without Storing Every Request]]></title>
            <link>https://medium.com/@lekhanar939/sliding-window-counter-achieving-accuracy-without-storing-every-request-7b42b20c4037?source=rss-75ee563cd5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b42b20c4037</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[rate-limiting]]></category>
            <dc:creator><![CDATA[Lekhana R]]></dc:creator>
            <pubDate>Wed, 24 Jun 2026 15:45:18 GMT</pubDate>
            <atom:updated>2026-06-24T15:45:18.728Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the previous article, we explored the <strong>Sliding Window Log</strong> algorithm and saw how it solves the boundary problem present in the Fixed Window Counter approach.</p><p>Instead of maintaining a simple counter, Sliding Window Log stores the timestamp of every request and evaluates only the requests that fall within the active time window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qgpdl9O19nedrtvB.jpg" /></figure><p>This provides highly accurate rate limiting because decisions are based on actual request history rather than fixed time buckets.</p><p>However, that accuracy comes at a cost.</p><p>For every request, we must store:</p><pre>Request Timestamp<br><br>//100 per min<br>[10:00:01]<br>[10:00:05]<br>[10:00:10]<br>...<br>[10:00:59]</pre><p>The rate limiter must retain all timestamps until they expire from the active window.</p><p>At small scale this is manageable.</p><p>At large scale, memory consumption becomes a significant concern.</p><p>The challenge becomes:</p><blockquote><em>Can we keep most of the accuracy of Sliding Window Log without storing every individual request?</em></blockquote><p>This question leads us to the next evolution of rate limiting:</p><h3>Sliding Window Counter</h3><h4><strong>Core Idea</strong></h4><pre>Instead of storing every request timestamp:<br>10:00:01<br>10:00:05<br>10:00:10<br>10:00:15<br>...<br><br>We store only two counters:<br>Current Window Count<br>Previous Window Count</pre><p>and estimate how many requests belong to the active sliding window.</p><p>This dramatically reduces memory consumption while still avoiding the major boundary issues of Fixed Window Counter.</p><h4>Revisiting the Boundary Problem</h4><pre>Consider a rate limit of:100 requests/minute<br><br>Fixed Window divides time into:<br>12:00:00 - 12:01:00<br>12:01:00 - 12:02:00<br><br>A user can send:<br>99 requests at 12:00:59<br>99 requests at 12:01:01<br><br>Result:198 requests in 2 seconds</pre><p>Sliding Window Log solves this perfectly by storing every timestamp.</p><p>Sliding Window Counter takes a different approach.</p><p>Rather than storing all timestamps, it estimates how much of the previous window still overlaps with the current moment.</p><h4>The Key Observation</h4><pre>suppose<br>Current Time = 12:01:15<br><br>The active 60-second window is:<br>12:00:15 → 12:01:15<br><br>Notice something interesting.<br>the active window overlaps:<br>75% Current Window<br>25% Previous Window<br><br>Therefore:<br>Estimated Count<br>=<br>Current Window Requests<br>+<br>(Previous Window Requests × Overlap Percentage)</pre><p>This weighted calculation gives a close approximation of a true sliding window without storing every request timestamp.</p><h3>What We’ll Build</h3><p>In this article, we’ll explore:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uuWEMxYkYMrnOiCl" /></figure><ul><li>How Sliding Window Counter works</li><li>The weighted counter formula</li><li>Window overlap calculations</li><li>Java implementation from scratch</li><li>Time and memory complexity</li><li>Accuracy trade-offs</li><li>Distributed implementation using Redis</li></ul><p>By the end, you’ll understand why Sliding Window Counter is often considered the sweet spot between:</p><pre>Fixed Window Counter<br>(Simple but inaccurate)<br><br>and<br><br>Sliding Window Log<br>(Accurate but memory-heavy)</pre><h3>Example :</h3><p>The Formula</p><pre>Estimated Count<br><br>=<br>Current Window Count<br><br>+<br><br>(Previous Window Count × Weight)<br><br>-------------------------------<br><br>Weight<br>=<br>Remaining Time in Previous Window<br>/<br>Window Size</pre><p>Example 1:</p><pre>100 requests/minute<br><br>//current time :<br>12:01:15<br><br>//count<br>Previous Window = 80<br>Current Window = 20<br><br>//Window overlap:<br>45 sec<br><br>//Weight:<br>45/60 =0.75<br><br>//Estimated Count:<br>20 + (80 × 0.75)<br><br>20 + 60<br><br>80<br>//Result :<br>80&lt;100<br><br>Request allowed<br><br>if it was greater than 100 -&gt;then request would be rejected.</pre><h3>Data We Need to Store</h3><pre>class WindowCounter {<br><br>    long currentWindowStart;<br><br>    int currentCount;<br><br>    int previousCount;<br>}<br><br>//Memory usage becomes:O(1) per user instead of number of requests</pre><h3>Algorithm</h3><pre>1. Determine current window<br>2. Update counters if window changed<br>3. Calculate overlap percentage<br>4. Calculate estimated count<br>5. Compare against limit<br>6. Allow or reject request<br><br>//Pseudo-code:<br>estimatedCount<br><br>=<br>currentCount<br><br>+<br><br>(previousCount × weight)<br><br>if estimatedCount &gt;= limit<br><br>    reject<br><br>else<br><br>    currentCount++<br><br>    allow</pre><h3>Java Implementation</h3><pre>import java.util.concurrent.ConcurrentHashMap;<br><br>public class SlidingWindowCounterRateLimiter {<br><br>    private final int limit;<br>    private final long windowSizeMillis;<br><br>    private final ConcurrentHashMap&lt;String, Window&gt;<br>            windows = new ConcurrentHashMap&lt;&gt;();<br><br>    public SlidingWindowCounterRateLimiter(<br>            int limit,<br>            long windowSizeMillis) {<br><br>        this.limit = limit;<br>        this.windowSizeMillis = windowSizeMillis;<br>    }<br><br>    public boolean allowRequest(String userId) {<br><br>        long now = System.currentTimeMillis();<br><br>        Window window = windows.computeIfAbsent(<br>                userId,<br>                k -&gt; new Window(now));<br><br>        synchronized (window) {<br><br>            long currentWindow =<br>                    now / windowSizeMillis;<br><br>            long storedWindow =<br>                    window.windowStart<br>                    / windowSizeMillis;<br><br>            if (currentWindow &gt; storedWindow) {<br><br>                window.previousCount =<br>                        window.currentCount;<br><br>                window.currentCount = 0;<br><br>                window.windowStart = now;<br>            }<br><br>            double elapsed =<br>                    now - window.windowStart;<br><br>            double weight =<br>                    (windowSizeMillis - elapsed)<br>                    / windowSizeMillis;<br><br>            double estimatedCount =<br>                    window.currentCount<br>                    +<br>                    (window.previousCount * weight);<br><br>            if (estimatedCount &gt;= limit) {<br>                return false;<br>            }<br><br>            window.currentCount++;<br><br>            return true;<br>        }<br>    }<br><br>    static class Window {<br><br>        long windowStart;<br><br>        int currentCount;<br><br>        int previousCount;<br><br>        Window(long windowStart) {<br>            this.windowStart = windowStart;<br>        }<br>    }<br>}</pre><blockquote>Conclusion</blockquote><blockquote>Sliding Window Counter is the natural evolution of Sliding Window Log.</blockquote><blockquote>Sliding Window Log gives us accuracy by storing every request timestamp. Sliding Window Counter asks a different question:</blockquote><blockquote><em>Can we achieve nearly the same accuracy using only a few counters?</em></blockquote><blockquote>By combining the current window count with a weighted portion of the previous window, we get a rate limiter that is:</blockquote><blockquote>Much more memory efficient</blockquote><blockquote>Constant-time per request</blockquote><blockquote>Easy to distribute across multiple servers</blockquote><blockquote>Accurate enough for most production systems</blockquote><blockquote>This makes Sliding Window Counter one of the most practical rate-limiting algorithms for modern backend systems and a bridge between simple counters and advanced algorithms such as Token Bucket.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b42b20c4037" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sliding Window Log Rate Limiter: A Deep Dive for Backend Engineers | Solving the Boundary Problem]]></title>
            <link>https://medium.com/@lekhanar939/sliding-window-log-rate-limiter-a-deep-dive-for-backend-engineers-solving-the-boundary-problem-23e670bd12e3?source=rss-75ee563cd5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/23e670bd12e3</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Lekhana R]]></dc:creator>
            <pubDate>Tue, 23 Jun 2026 16:01:51 GMT</pubDate>
            <atom:updated>2026-06-23T16:01:51.255Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>Introduction</blockquote><p>In the previous article, we implemented a Fixed Window Counter rate limiter. While simple and efficient, it suffers from a critical flaw known as the <strong>boundary problem</strong>.</p><p>Consider a rate limit of:</p><pre>100 requests per minute</pre><p>A client can send:</p><pre>99 requests at 12:00:59<br>99 requests at 12:01:01</pre><p>Even though only two seconds have passed, the system allows:</p><pre>198 requests in 2 seconds</pre><p>because the counter resets when a new minute begins.</p><p>To solve this issue, we need a rate limiter that looks at the <strong>last 60 seconds from the current moment</strong>, rather than relying on fixed time buckets.</p><p>This is where the <strong>Sliding Window Log</strong> algorithm comes in.</p><h3>The Core Idea</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tjjBxuu3_lbqFCQ2Kp3HZg.png" /></figure><p>Instead of storing a counter, we store the timestamp of every request.</p><pre>User A<br><br>[<br>  10:00:05,<br>  10:00:15,<br>  10:00:25,<br>  10:00:35<br>]</pre><p>Whenever a new request arrives:</p><ol><li>Remove timestamps outside the window.</li><li>Count the remaining timestamps.</li><li>If the count is below the limit, allow the request.</li><li>Otherwise reject it.</li></ol><p>The window continuously moves forward with time.</p><p>Hence the name:</p><blockquote><em>Sliding Window Log</em></blockquote><h4>Visualizing the Sliding Window</h4><pre>//Suppose we allow:<br>5 requests per minute<br><br>//Current request history:<br>10:00:05<br>10:00:10<br>10:00:20<br>10:00:30<br>10:00:40<br><br>//Current time:<br>10:00:50<br><br>//The window covers:<br>09:59:50 → 10:00:50<br>//All five requests fall within the window.<br><br>count= 5<br>limit=5<br>//A new request is rejected.<br><br><br>------------------------------------------------<br><br>//Now time advances.<br>//Current time:<br>10:01:06<br><br>//The window becomes:<br>10:00:06 → 10:01:06<br><br>//The request at:<br>10:00:05<br>//falls outside the window and is removed.<br><br>Remaining timestamps:<br>10:00:10<br>10:00:20<br>10:00:30<br>10:00:40<br><br>//Count becomes:<br>4<br><br>//The new request is now accepted.<br><br></pre><h3>Designing the Data Structure</h3><p>The algorithm constantly performs three operations:</p><ol><li>Remove oldest request</li></ol><pre>removeFirst()</pre><p>2. Check oldest request</p><pre>peekFirst()</pre><p>3. Add latest request</p><pre>addLast()</pre><p>A queue-like structure is ideal.</p><p>In Java:</p><pre>Deque&lt;Long&gt;<br>or<br>ArrayDeque&lt;Long&gt;<br>or <br>LinkedList&lt;Long&gt;</pre><h3>Algorithm</h3><p>For every incoming request:</p><pre>1. Get current timestamp<br>2. Remove expired timestamps<br>3. Check current request count<br>4. Reject if limit reached<br>5. Otherwise store timestamp<br>6. Allow request</pre><p>Pseudocode:</p><pre>allowRequest()<br><br>currentTime = now()<br><br>remove timestamps older than window<br><br>if requestCount &gt;= limit<br>    reject<br><br>add currentTime<br><br>allow</pre><h3>Java Implementation</h3><pre>import java.util.*;<br><br>public class SlidingWindowLogRateLimiter {<br><br>    private final int limit;<br>    private final long windowSizeMillis;<br><br>    private final Map&lt;String, Deque&lt;Long&gt;&gt; requestLogs =<br>            new HashMap&lt;&gt;();<br><br>    public SlidingWindowLogRateLimiter(<br>            int limit,<br>            long windowSizeMillis) {<br><br>        this.limit = limit;<br>        this.windowSizeMillis = windowSizeMillis;<br>    }<br><br>    public synchronized boolean allowRequest(<br>            String userId) {<br><br>        long now = System.currentTimeMillis();<br><br>        requestLogs.putIfAbsent(<br>                userId,<br>                new ArrayDeque&lt;&gt;());<br><br>        Deque&lt;Long&gt; requests =<br>                requestLogs.get(userId);<br><br>        while (!requests.isEmpty()<br>                &amp;&amp; now - requests.peekFirst()<br>                &gt;= windowSizeMillis) {<br><br>            requests.removeFirst();<br>        }<br><br>        if (requests.size() &gt;= limit) {<br>            return false;<br>        }<br><br>        requests.addLast(now);<br><br>        return true;<br>    }<br>}</pre><h3>Dry Run</h3><pre>limit = 3<br>window = 60 seconds<br><br>//timestamp<br><br>10 sec<br>20 sec<br>30 sec<br><br>//store log<br><br>[10,20,30]<br><br>//request at <br>40 sec<br><br>//Current count:<br>3 -&gt;limit reached -&gt;reject<br><br><br>//Now current time becomes:<br>71 sec<br><br>//Window:<br>11 sec -&gt;71 sec<br><br>//Timestamp:<br>10sec -&gt;remove/expires<br><br>//Log becomes:<br>[20,30]<br><br>//New request:<br>71 sec -&gt;Allowed <br><br>//Final log:<br>[20,30,71]</pre><h3>Time Complexity Analysis</h3><pre>//Removing expired entries<br><br>while(..)<br><br>worst case -&gt; O(n)<br><br>//Insert request<br><br>O(1)<br><br>//Count check<br><br>O(1)<br><br>//Overall:<br><br>O(n)<br><br>where n is the number of requests in the current window.<br></pre><h3>The Biggest Trade-off: Memory</h3><p>Sliding Window Log achieves excellent accuracy by storing every request.</p><pre>suppose<br>1 million users<br><br>Ecah user:<br>100 user per min<br><br>stored timestamps:<br>100 million entries<br><br>Memory consumption becomes significant.<br><br>This is the primary reason large-scale systems often avoid pure Sliding Window Log implementations.</pre><h3>Distributed Systems Challenge</h3><p>consider</p><pre>          Load Balancer<br>                 |<br>      ---------------------<br>      |         |         |<br>   Server1   Server2   Server3<br><br>If each server maintains its own logs:<br><br>User → 50 requests on Server1<br>User → 50 requests on Server2<br>User → 50 requests on Server3<br><br>Each server sees:<br>50 Requests<br><br>total:<br>150 request<br>even if the limit is only 100.</pre><h3>Redis-Based Sliding Window Log</h3><p>In distributed environments, timestamps are stored centrally.</p><p>A common approach is using Redis Sorted Sets.</p><pre>//key<br>rate_limit:user123<br><br>Commands:<br>//Remove expired timestamps<br>ZREMRANGEBYSCORE<br><br>//Count active requests<br>ZCARD<br><br>//Insert new request<br>ZADD<br><br>This allows all application instances to share the same request history.</pre><h3>Advantages</h3><p>✅ Eliminates the boundary problem</p><p>✅ Highly accurate</p><p>✅ Easy to reason about</p><p>✅ Perfect for security-sensitive endpoints</p><h3>Disadvantages</h3><p>❌ Memory-intensive</p><p>❌ Stores every request</p><p>❌ Doesn’t scale efficiently for high-traffic systems</p><p>❌ Redis storage can grow rapidly</p><h3>When Should You Use Sliding Window Log?</h3><p>A good fit for:</p><ul><li>Login APIs</li><li>OTP generation</li><li>Password reset endpoints</li><li>Account recovery workflows</li><li>Admin APIs</li></ul><p>Where precision matters more than memory efficiency.</p><blockquote>Conclusion:</blockquote><blockquote>Sliding Window Log improves upon Fixed Window Counter by tracking actual request timestamps rather than relying on fixed time buckets.</blockquote><blockquote>This eliminates the boundary problem and provides highly accurate rate limiting. The trade-off, however, is increased memory usage because every request must be stored until it falls outside the active window.</blockquote><blockquote>For small to medium traffic systems where correctness is critical, Sliding Window Log is an excellent choice. For large-scale systems, it often serves as a stepping stone toward more memory-efficient approaches such as Sliding Window Counter or Token Bucket.</blockquote><blockquote>This format reads naturally as a standalone Medium article and smoothly connects from your previous Fixed Window Counter post.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23e670bd12e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Exactly Is Rate Limiting?]]></title>
            <link>https://medium.com/@lekhanar939/what-exactly-is-rate-limiting-f509517dfebc?source=rss-75ee563cd5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/f509517dfebc</guid>
            <category><![CDATA[rate-limiting]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Lekhana R]]></dc:creator>
            <pubDate>Mon, 22 Jun 2026 15:39:13 GMT</pubDate>
            <atom:updated>2026-06-22T15:39:13.999Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/474/0*_lTwWaXVqJuDbRje" /></figure><p>Rate limiting answers one question:<em>“Should I allow this request right now?”</em></p><p>Example &gt;</p><p>Given : <strong><em>User A → 100 requests/minute</em></strong></p><p>Every incoming request must be evaluated:</p><pre>boolean allowRequest(String userId);</pre><p>returns:</p><pre>true  -&gt; process request<br>false -&gt; return HTTP 429</pre><p><strong>Problem Statement:</strong></p><p>Suppose your login endpoint receives: <em>10,000 requests/sec</em></p><p>Without rate limiting:</p><pre>CPU = 100%<br>Memory = Exhausted<br>Database = Overloaded</pre><p>Users experience:</p><pre>503 Service Unavailable</pre><blockquote>Rate limiting acts as a gatekeeper.</blockquote><h3>1.Fixed Window Counter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/0*oO-WPwBmuMzpd0cE" /></figure><pre>User -&gt; Request Count<br><br>//example :<br>Window = 1 minute<br>Limit = 5<br><br>//timeline:<br>10:00:01 Request #1<br>10:00:05 Request #2<br>10:00:20 Request #3<br>10:00:30 Request #4<br>10:00:50 Request #5<br><br>Allowed.<br><br>//Next request:<br><br>10:00:55 Request #6<br><br>Rejected.</pre><h4>Data Structure</h4><pre>class UserWindow {<br>    long windowStart;<br>    int count;<br>}</pre><p>stores:</p><pre>Map&lt;String, UserWindow&gt;</pre><p>Java Implementation</p><pre>import java.util.concurrent.ConcurrentHashMap;<br><br>public class FixedWindowRateLimiter {<br><br>    private final int limit;<br>    private final long windowSizeMillis;<br><br>    private final ConcurrentHashMap&lt;String, Window&gt; users =<br>            new ConcurrentHashMap&lt;&gt;();<br><br>    public FixedWindowRateLimiter(int limit,<br>                                  long windowSizeMillis) {<br>        this.limit = limit;<br>        this.windowSizeMillis = windowSizeMillis;<br>    }<br><br>    public boolean allowRequest(String userId) {<br><br>        long currentTime = System.currentTimeMillis();<br><br>        Window window = users.computeIfAbsent(<br>                userId,<br>                k -&gt; new Window(currentTime, 0)<br>        );<br><br>        synchronized (window) {<br><br>            if(currentTime - window.startTime<br>                    &gt;= windowSizeMillis) {<br><br>                window.startTime = currentTime;<br>                window.count = 0;<br>            }<br><br>            if(window.count &gt;= limit) {<br>                return false;<br>            }<br><br>            window.count++;<br><br>            return true;<br>        }<br>    }<br><br>    static class Window {<br>        long startTime;<br>        int count;<br><br>        Window(long startTime,<br>               int count) {<br>            this.startTime = startTime;<br>            this.count = count;<br>        }<br>    }<br>}</pre><h4>Why Fixed Window Is Bad</h4><p>consider :</p><pre>Limit = 100/minute</pre><p>user sends:</p><pre>99 requests at 12:00:59<br>99 requests at 12:01:01</pre><p>total :</p><pre>198 requests in 2 seconds</pre><p>System still allows them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zqWYBBFVaK3j4G7hWAohtg.png" /></figure><p>This is called the <strong>boundary problem</strong>.</p><blockquote>to be continued …</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/313/0*To8lZuAqaoAVKCpg" /></figure><blockquote>Please check previous blogs and stay tunned for upcoming blogs ,</blockquote><blockquote>make sure to like it!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f509517dfebc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Complete Docker Guide (End-to-End) — With Q&A]]></title>
            <link>https://medium.com/@lekhanar939/complete-docker-guide-end-to-end-with-q-a-ee786ee699a2?source=rss-75ee563cd5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee786ee699a2</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Lekhana R]]></dc:creator>
            <pubDate>Tue, 07 Apr 2026 06:27:22 GMT</pubDate>
            <atom:updated>2026-04-07T06:27:22.007Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧭 Introduction</h3><p>Docker is a containerization platform that allows developers to package applications along with all dependencies into a single unit called a <strong>container</strong>.</p><p>👉 Why Docker?</p><ul><li>Works on any environment (dev, test, prod)</li><li>Eliminates “works on my machine” issue</li><li>Lightweight compared to VMs</li></ul><h3>🖼️ Docker vs Virtual Machine</h3><pre>[ Virtual Machine ]<br>App → Guest OS → Hypervisor → Host OS</pre><pre>[ Docker Container ]<br>App → Docker Engine → Host OS</pre><p>👉 Containers are lightweight because they don’t need a full OS.</p><h3>🔥 CORE CONCEPTS (Q&amp;A)</h3><h3>❓ What is Docker Image?</h3><p>👉 A read-only blueprint used to create containers.</p><p>Example:</p><pre>openjdk:17<br>node:18</pre><h3>❓ What is Docker Container?</h3><p>👉 A running instance of an image.</p><h3>❓ Difference: Image vs Container</h3><ul><li>Image = Blueprint</li><li>Container = Running app</li></ul><h3>❓ What is Dockerfile?</h3><p>👉 A script with instructions to build an image.</p><h3>🖼️ Docker Workflow</h3><pre>Dockerfile → Build → Image → Run → Container</pre><h3>🛠️ DOCKER INSTALLATION (Brief)</h3><ul><li>Install Docker Desktop</li><li>Verify:</li></ul><pre>docker --version</pre><h3>⚙️ BASIC COMMANDS (Q&amp;A)</h3><h3>❓ List images</h3><pre>docker images</pre><h3>❓ Run container</h3><pre>docker run -p 8080:8080 myapp</pre><h3>❓ Stop container</h3><pre>docker stop &lt;id&gt;</pre><h3>❓ Remove container</h3><pre>docker rm &lt;id&gt;</pre><h3>🧱 DOCKERFILE (DEEP UNDERSTANDING)</h3><h3>Example Dockerfile (Spring Boot)</h3><pre>FROM openjdk:17-jdk-slim<br>WORKDIR /app<br>COPY target/app.jar app.jar<br>ENTRYPOINT [&quot;java&quot;, &quot;-jar&quot;, &quot;app.jar&quot;]</pre><h3>❓ Explanation:</h3><ul><li>FROM → base image</li><li>WORKDIR → working directory</li><li>COPY → copy files</li><li>ENTRYPOINT → run app</li></ul><h3>🖼️ Docker Build Process</h3><pre>Dockerfile → Layers → Image → Container</pre><p>👉 Each instruction creates a layer.</p><h3>🔥 ADVANCED QUESTIONS</h3><h3>❓ What are Docker layers?</h3><p>👉 Each instruction in Dockerfile creates a layer.</p><p>👉 Benefit:</p><ul><li>Faster builds (cache reuse)</li></ul><h3>❓ What is Docker volume?</h3><p>👉 Used for persistent storage.</p><p>Example:</p><pre>docker run -v /data:/app/data</pre><h3>❓ What is Docker network?</h3><p>👉 Enables communication between containers.</p><h3>🖼️ Visual: Multi-Container Communication</h3><pre>[App Container] ↔ [DB Container]</pre><h3>🐳 DOCKER COMPOSE</h3><h3>❓ What is Docker Compose?</h3><p>👉 Tool to run multiple containers together.</p><h3>Example:</h3><pre>version: &#39;3&#39;<br>services:<br>  app:<br>    build: .<br>    ports:<br>      - &quot;8080:8080&quot;<br>  db:<br>    image: postgres</pre><h3>☁️ DOCKER + DEVOPS</h3><h3>❓ How Docker is used in CI/CD?</h3><p>👉 Flow:</p><ul><li>Code → Git</li><li>Jenkins builds image</li><li>Push to registry</li><li>Deploy container</li></ul><h3>🖼️ CI/CD Pipeline</h3><pre>Git → Jenkins → Docker Build → Deploy</pre><h3>🚨 REAL-TIME SCENARIOS</h3><h3>❓ Container crashes — what to do?</h3><p>👉 Check logs:</p><pre>docker logs &lt;id&gt;</pre><h3>❓ App not accessible?</h3><p>👉 Check:</p><ul><li>Port mapping</li><li>Container running</li><li>Firewall</li></ul><h3>❓ High memory usage?</h3><p>👉 Optimize:</p><ul><li>Reduce image size</li><li>Use slim base image</li></ul><h3>🔐 BEST PRACTICES</h3><ul><li>Use small base images</li><li>Avoid root user</li><li>Use multi-stage builds</li><li>Keep images lightweight</li></ul><h3>🎯 INTERVIEW QUICK Q&amp;A</h3><h3>❓ CMD vs ENTRYPOINT?</h3><ul><li>CMD → override possible</li><li>ENTRYPOINT → fixed</li></ul><h3>❓ Why Docker over VM?</h3><ul><li>Lightweight</li><li>Faster startup</li></ul><h3>❓ What is registry?</h3><p>👉 Storage for images (Docker Hub)</p><h3>🏁 CONCLUSION</h3><p>Docker is essential for modern backend development. It simplifies deployment, improves consistency, and integrates well with cloud and DevOps tools.</p><p><strong>If you liked this, follow for more backend &amp; interview content 🚀</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee786ee699a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Spring Boot Series — Part 4: Core Annotations Deep Dive | Interview Tips]]></title>
            <link>https://medium.com/@lekhanar939/spring-boot-series-part-4-core-annotations-deep-dive-interview-tips-a2154501e8a7?source=rss-75ee563cd5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2154501e8a7</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring]]></category>
            <dc:creator><![CDATA[Lekhana R]]></dc:creator>
            <pubDate>Tue, 31 Mar 2026 10:14:37 GMT</pubDate>
            <atom:updated>2026-03-31T10:14:37.293Z</atom:updated>
            <content:encoded><![CDATA[<h3>🔷 1. @SpringBootApplication (Recap + Deep)</h3><pre>@SpringBootApplication</pre><p>👉 Internally:</p><pre>@Configuration<br>@EnableAutoConfiguration<br>@ComponentScan</pre><p>🔷 Flow</p><pre>@SpringBootApplication<br>        │<br>        ▼<br>@ComponentScan → Scans packages<br>        │<br>        ▼<br>Detects Beans (@Component etc.)<br>        │<br>        ▼<br>Registers in Spring Container</pre><h3>🔷 2. @Component Family (VERY IMPORTANT ⭐)</h3><p>🔹 @Component</p><pre>@Component // Generic bean<br>class A {} </pre><p>🔹 @Service</p><pre>@Service // Business logic layer<br>class UserService {}</pre><p>🔹 @Repository</p><pre>@Repository<br>class UserRepository {}</pre><p>👉 Database layer<br> 👉 Adds exception translation (important point!)</p><p>🔹 @Controller / @RestController</p><pre>@RestController<br>class UserController {}</pre><p>👉 Handles HTTP requests</p><h3>🔷 3. @Autowired (Dependency Injection)</h3><p>🔹 Field Injection ❌ (Not Recommended)</p><pre>@Autowired<br>UserService service;</pre><p>❌ Problems:</p><ul><li>Hard to test</li><li>Not immutable</li></ul><p>🔹 Constructor Injection ✅ (BEST PRACTICE)</p><pre>class UserController {<br><br>    private final UserService service;<br><br>    public UserController(UserService service) {<br>        this.service = service;<br>    }<br>}</pre><p>✅ Benefits:</p><ul><li>Immutable</li><li>Testable</li><li>Recommended by Spring</li></ul><p>🔷 Injection Flow</p><pre>Spring Container<br>     │<br>     ▼<br>Creates UserService Bean<br>     │<br>     ▼<br>Injects into Controller</pre><h3>🔷 4. @Bean vs @Component (Tricky ⭐)</h3><p>🔹 @Component</p><pre>@Component<br>class MyClass {}</pre><p>👉 Used when:</p><ul><li>You <strong>own the class</strong></li></ul><p>🔹 @Bean</p><pre>@Configuration<br>class AppConfig {<br><br>    @Bean<br>    public MyClass myClass() {<br>        return new MyClass();<br>    }<br>}</pre><p>👉 Used when:</p><ul><li>You <strong>don’t control the class</strong> (3rd party)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*dieXYWivdWPSQ1dgUKhyng.png" /></figure><h3>🔷 5. @Configuration</h3><pre>@Configuration<br>class AppConfig {}</pre><p>👉 Marks class as:</p><ul><li>Source of bean definitions</li></ul><h3>🔷 6. @Qualifier (Important Edge Case)</h3><pre>@Autowired<br>PaymentService service;</pre><p>👉 Multiple implementations → Error ❌</p><p>solution :</p><pre>@Autowired<br>@Qualifier(\&quot;upiService\&quot;)<br>PaymentService service;</pre><h3>🔷 7. @Primary</h3><pre>@Primary //👉 Default bean when multiple exist<br>class UpiService implements PaymentService {}</pre><h3>🔥 Real Flow Diagram (Full)</h3><pre>@ComponentScan<br>     │<br>     ▼<br>Find Classes (@Component, @Service...)<br>     │<br>     ▼<br>Create Beans in Container<br>     │<br>     ▼<br>@Autowired triggers injection<br>     │<br>     ▼<br>Application Runs 🚀</pre><h3>🔥 Interview Questions (Must Prepare)</h3><h3>1. Difference between @Component, @Service, @Repository?</h3><p>👉 Same base, different purpose</p><h3>2. Field vs Constructor Injection?</h3><p>👉 Constructor is better (immutability + testing)</p><h3>3. @Bean vs @Component?</h3><p>👉 Method vs class level</p><h3>4. What happens if multiple beans exist?</h3><p>👉 Error → use @Qualifier / @Primary</p><h3>5. What is @Configuration?</h3><p>👉 Defines beans manually</p><blockquote><em>“Annotations are not just shortcuts — they define how your entire Spring application behaves.”</em></blockquote><blockquote><em>Check out for upcoming series in a row .</em></blockquote><h3>🙌 Final Note</h3><p>I hope this article helped you learn something new! 🙃<br>If you ❤️ this article, consider sharing it so it reaches a wider audience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2154501e8a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Spring Boot Series — Part 3: Project Setup & Structure]]></title>
            <link>https://medium.com/@lekhanar939/spring-boot-series-part-3-project-setup-structure-3bfc2256fd53?source=rss-75ee563cd5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/3bfc2256fd53</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Lekhana R]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 14:33:27 GMT</pubDate>
            <atom:updated>2026-03-30T14:33:27.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oumfX4Vf9Hfm-TKYl2zcjQ.png" /></figure><h3>🔷 1. Creating Spring Boot Project</h3><h3>✅ Using Spring Initializr (Recommended)</h3><p>👉 Go to: <a href="https://start.spring.io/">https://start.spring.io</a></p><h3>Fill details:</h3><ul><li>Project: <strong>Maven / Gradle</strong></li><li>Language: <strong>Java</strong></li><li>Spring Boot Version: Latest stable</li><li>Dependencies:</li><li>Spring Web</li><li>Spring Data JPA</li><li>Lombok (optional)</li></ul><h4>🔷 Flow Diagram</h4><pre>Open Spring Initializr<br>        │<br>        ▼<br>Select Dependencies<br>        │<br>        ▼<br>Generate Project (ZIP)<br>        │<br>        ▼<br>Import into IDE (IntelliJ/Eclipse)<br>        │<br>        ▼<br>Run Application 🚀</pre><h3>🔷 2. Maven vs Gradle (Interview Favorite ⭐)</h3><p>🔹 Maven</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>&lt;/dependency&gt;</pre><ul><li>XML based</li><li>Easy to understand</li><li>Widely used</li></ul><p>🔹 Gradle</p><pre>implementation &#39;org.springframework.boot&#39;</pre><ul><li>Groovy/Kotlin based</li><li>Faster build</li><li>Less boilerplate</li></ul><p>👉 Interview line:<br> <strong>“Maven is simple, Gradle is powerful.”</strong></p><h3>🔷 3. Project Structure (VERY IMPORTANT ⭐⭐⭐)</h3><pre>src/main/java<br>    └── com.example.project<br>            ├── controller<br>            ├── service<br>            ├── repository<br>            ├── model (entity)<br>            └── Application.java<br><br>src/main/resources<br>    ├── application.properties<br>    ├── static<br>    └── templates<br><br>src/test/java</pre><p>🔷 Layered Architecture</p><p><em>Controller → Service → Repository → Database</em></p><p>👉 Explanation:</p><ul><li>Controller → Handles requests</li><li>Service → Business logic</li><li>Repository → DB interaction</li></ul><h3>🔷 4. application.properties vs application.yml</h3><p>🔹 application.properties</p><pre>server.port=8080<br>spring.datasource.url=jdbc:mysql://localhost:3306/db</pre><p>🔹 application.yml</p><pre>server:<br>  port: 8080<br><br>spring:<br>  datasource:<br>    url: jdbc:mysql://localhost:3306/db</pre><p>👉 Interview line:<br> <strong>“YAML is more readable for complex configs.</strong></p><h3>🔷 5. Main Class (Entry Point)</h3><pre>@SpringBootApplication<br>public class MyApp {<br>    public static void main(String[] args) {<br>        SpringApplication.run(MyApp.class, args);<br>    }<br>}</pre><p>🔷 Flow</p><pre>main()<br>   │<br>   ▼<br>SpringApplication.run()<br>   │<br>   ▼<br>Starts Spring Container<br>   │<br>   ▼<br>Auto Configuration<br>   │<br>   ▼<br>Application Ready 🚀</pre><h3>🔷 6. Running the Application</h3><h4>Option 1:</h4><ul><li>Run from IDE</li></ul><h4>Option 2:</h4><p>mvn spring-boot:run</p><h4>Option 3:</h4><p>java -jar app.jar</p><h3>🔥 Interview Questions</h3><h3>1. How do you create a Spring Boot project?</h3><p>👉 Using Spring Initializr / IDE</p><h3>2. Explain project structure</h3><p>👉 Controller → Service → Repository → DB</p><h3>3. Difference between Maven &amp; Gradle?</h3><p>👉 XML vs Groovy, speed difference</p><h3>4. What is application.properties?</h3><p>👉 Configuration file</p><h3>5. What is main class role?</h3><p>👉 Entry point + starts Spring container</p><h3>🔥 Real-Time Tip</h3><p>When asked:</p><p>👉 “Explain your project structure”</p><p>Say:</p><blockquote><em>“I follow layered architecture where controllers handle requests, services contain business logic, and repositories interact with the database. This separation improves maintainability and scalability.”</em></blockquote><p>“A well-structured Spring Boot project is not just clean — it’s interview-winning.”</p><blockquote><em>Check out for upcoming series in a row .</em></blockquote><h3>🙌 Final Note</h3><p>I hope this article helped you learn something new! 🙃<br>If you ❤️ this article, consider sharing it so it reaches a wider audience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3bfc2256fd53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Spring Boot Series — Part 2: Auto Configuration Deep Dive | Interview Tips]]></title>
            <link>https://medium.com/@lekhanar939/spring-boot-series-part-2-auto-configuration-deep-dive-interview-tips-1a46f169805b?source=rss-75ee563cd5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a46f169805b</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview]]></category>
            <dc:creator><![CDATA[Lekhana R]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 04:26:54 GMT</pubDate>
            <atom:updated>2026-03-26T04:26:54.725Z</atom:updated>
            <content:encoded><![CDATA[<h3>🔥 What is Auto Configuration?</h3><p>Auto Configuration is the feature in Spring Boot that <strong>automatically configures your application based on dependencies present in classpath</strong>.</p><p>📌 Real Example</p><p>If you add this dependency:</p><pre>&lt;dependency&gt;<br>    &lt;groupId&gt;spring-boot-starter-web&lt;/groupId&gt;<br>&lt;/dependency&gt;</pre><p>👉 Spring Boot automatically:</p><ul><li>Configures <strong>Tomcat server</strong></li><li>Sets up <strong>DispatcherServlet</strong></li><li>Enables <strong>Spring MVC</strong></li><li>Adds <strong>Jackson (JSON converter)</strong></li></ul><p>No manual setup needed ✅</p><h3>🔷 Core Working Diagram (Auto Configuration Flow)</h3><pre>Step 1: Add Dependency<br>        │<br>        ▼<br>Spring Boot Starts Application<br>        │<br>        ▼<br>@EnableAutoConfiguration Triggered<br>        │<br>        ▼<br>Spring scans classpath (dependencies)<br>        │<br>        ▼<br>Checks conditions (@Conditional)<br>        │<br>        ▼<br>Loads required configurations<br>        │<br>        ▼<br>Creates Beans Automatically<br>        │<br>        ▼<br>Application Ready 🚀</pre><h3>🔷 Internal Working (VERY IMPORTANT ⭐)</h3><pre>@SpringBootApplication<br>        │<br>        ▼<br>@EnableAutoConfiguration<br>        │<br>        ▼<br>SpringFactoriesLoader<br>        │<br>        ▼<br>META-INF/spring.factories<br>        │<br>        ▼<br>List of Auto Config Classes<br>        │<br>        ▼<br>@Configuration Classes Loaded</pre><h3>🔥 Key Concept: @SpringBootApplication</h3><pre>@SpringBootApplication<br><br>//internally<br>@Configuration<br>@EnableAutoConfiguration<br>@ComponentScan</pre><h3>🔥 How Spring Decides What to Configure?</h3><p>Using <strong>@Conditional annotations</strong></p><pre>@ConditionalOnClass(DataSource.class)</pre><p>👉 Meaning:</p><ul><li>If DataSource is present → configure DB</li><li>Else → skip</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*Twg0Agcr7vh-uzWTzWc-4w.png" /></figure><h3>🔷 Real Flow Example (Database)</h3><pre>You add MySQL dependency<br>        │<br>        ▼<br>Spring detects DataSource class<br>        │<br>        ▼<br>Applies DataSourceAutoConfiguration<br>        │<br>        ▼<br>Creates DataSource Bean<br>        │<br>        ▼<br>Connects to Database</pre><h3>🔷 Overriding Auto Configuration</h3><pre>@Bean<br>public DataSource dataSource() {<br>    return new CustomDataSource();<br>}</pre><p>👉 Spring will:</p><ul><li>Use your bean</li><li>Ignore default one</li></ul><h3>🔷 Disable Auto Configuration</h3><pre>@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})</pre><p>👉 Use when:</p><ul><li>You don’t need DB</li><li>You want custom config</li></ul><h3>🔷 Starter Dependencies (Important)</h3><p>👉 Starters = Predefined dependency bundles</p><p>Examples:</p><ul><li>spring-boot-starter-web</li><li>spring-boot-starter-data-jpa</li><li>spring-boot-starter-security</li></ul><p>👉 They trigger auto configuration</p><h3>🔥 Interview Questions (Must Prepare)</h3><h3>1. How does Spring Boot Auto Configuration work?</h3><p>👉 Answer:</p><ul><li>Uses @EnableAutoConfiguration</li><li>Reads spring.factories</li><li>Loads config classes</li><li>Applies conditions</li><li>Creates beans automatically</li></ul><h3>2. What is spring.factories?</h3><p>👉 File containing:</p><ul><li>List of auto configuration classes</li></ul><h3>3. How to disable auto configuration?</h3><pre>exclude = {ClassName.class} //using exclude</pre><h3>4. What are @Conditional annotations?</h3><p>👉 They decide <strong>when a configuration should be applied</strong></p><h3>5. What happens if two beans exist?</h3><p>👉 Spring throws:<br> <strong>NoUniqueBeanDefinitionException</strong></p><h3>🔥 Real-Time Interview Tip</h3><p>If interviewer asks:</p><p>👉 “How Spring Boot knows what to configure?”</p><p>Say this confidently:</p><blockquote><em>“Spring Boot checks the classpath, finds dependencies, and based on conditions defined in auto-configuration classes (from spring.factories), it creates only the required beans.”</em></blockquote><p>“<em>Auto Configuration is the magic of Spring Boot — but it’s not magic, it’s smart conditional configuration.”</em></p><blockquote><em>Check out for upcoming series in a row .</em></blockquote><h3>🙌 Final Note</h3><p>I hope this article helped you learn something new! 🙃<br>If you ❤️ this article, consider sharing it so it reaches a wider audience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a46f169805b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Spring Boot Mastery Series(Part 1: Basics Every Developer Must Know")]]></title>
            <link>https://medium.com/@lekhanar939/spring-boot-mastery-series-part-1-basics-every-developer-must-know-0b2d5225551f?source=rss-75ee563cd5ff------2</link>
            <guid isPermaLink="false">https://medium.com/p/0b2d5225551f</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Lekhana R]]></dc:creator>
            <pubDate>Wed, 25 Mar 2026 03:45:30 GMT</pubDate>
            <atom:updated>2026-03-25T03:45:30.112Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6dqYPEIqlZQfor_0EPEn0A.png" /></figure><h3>📌 What is Spring Framework?</h3><p>Spring is a powerful Java framework used to build enterprise applications. It helps developers write <strong>loosely coupled, maintainable, and testable code</strong>.</p><h3>❗ Problem Before Spring</h3><p>Earlier Java apps used:</p><ul><li>Tight coupling</li><li>Manual object creation</li><li>Complex configurations (XML heavy)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/943/1*TNW76oem_gcrRD1QimMGGQ.png" /><figcaption>Traditional Java vs Spring (Core Problem)</figcaption></figure><h4>💡 Solution: Dependency Injection (DI)</h4><p>Instead of creating objects manually, Spring <strong>injects dependencies automatically</strong>.</p><pre>class A {<br>    B b = new B(); // Tight coupling<br>}</pre><p>with Spring,</p><pre>@Component<br>class A {<br>    @Autowired<br>    B b; // Loosely coupled<br>}</pre><h3>🔁 Inversion of Control (IoC)</h3><p>Control is transferred from developer to Spring container.</p><p>👉 Spring manages:</p><ul><li>Object creation</li><li>Lifecycle</li><li>Dependencies</li></ul><h3>🚀 What is Spring Boot?</h3><p>Spring Boot is an extension of Spring that simplifies development by:</p><ul><li>Removing boilerplate configuration</li><li>Providing auto-configuration</li><li>Embedded servers (Tomcat)</li></ul><h3>⚡ Why Spring Boot?</h3><ul><li>Faster development</li><li>Less configuration</li><li>Production-ready features</li></ul><h3>🎯 Interview Ready Summary</h3><ul><li>Spring = Framework</li><li>Spring Boot = Tool to simplify Spring</li><li>IoC = Control given to container</li><li>DI = Injecting dependencies automatically</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TpklDQoBH52Vak3ivhIKAA.png" /><figcaption>summary</figcaption></figure><blockquote><em>Check out for upcoming series in a row .</em></blockquote><h3>🙌 Final Note</h3><p>I hope this article helped you learn something new! 🙃<br>If you ❤️ this article, consider sharing it so it reaches a wider audience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0b2d5225551f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>