<?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 Shubham Gupta on Medium]]></title>
        <description><![CDATA[Stories by Shubham Gupta on Medium]]></description>
        <link>https://medium.com/@shubham18p2?source=rss-6218d4a4752------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5UPGARoIPl71LAcpINc8vw.png</url>
            <title>Stories by Shubham Gupta on Medium</title>
            <link>https://medium.com/@shubham18p2?source=rss-6218d4a4752------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 06:30:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shubham18p2/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[Cracking Atlassian CodeCraft Interview: Designing a Clean & Optimal Max-Query Data Structure]]></title>
            <link>https://medium.com/@shubham18p2/cracking-atlassian-codecraft-interview-designing-a-clean-optimal-max-query-data-structure-1a0f3eea76aa?source=rss-6218d4a4752------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a0f3eea76aa</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[interview-preparation]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[atlassian]]></category>
            <dc:creator><![CDATA[Shubham Gupta]]></dc:creator>
            <pubDate>Tue, 02 Dec 2025 06:32:19 GMT</pubDate>
            <atom:updated>2025-12-02T06:32:19.992Z</atom:updated>
            <content:encoded><![CDATA[<h4>How I moved from a heap-based solution to an optimized TreeMap design during the interview</h4><p><em>A real interview walkthrough solving dynamic index updates and max queries using HashMaps, Heaps, and TreeMaps — with Java implementations and complexity analysis.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I99_J3IaMmCZ03RJZOAmVw.png" /><figcaption>Atlassian fullstack Craft interview round</figcaption></figure><h3>TL;DR</h3><ul><li>Faced a dynamic-update problem in Atlassian CodeCraft requiring <strong>fast updates</strong> and <strong>max-value queries</strong>.</li><li>Started with a <strong>Heap + HashMap</strong> solution using lazy deletion to handle overwrites efficiently.</li><li>Interviewer asked for a cleaner approach, leading to a <strong>HashMap + TreeMap</strong> solution that avoids stale entries.</li><li>Both approaches are implemented in <strong>Java</strong>, highlighting trade-offs between performance and simplicity.</li><li>This article explains <strong>full solution design, diagrams, complexity analysis</strong>, and interview insights.</li></ul><h3>Introduction</h3><p>During my Atlassian Fullstack CodeCraft round, I was asked to design a data structure supporting:</p><ol><li><strong>update(index, num)</strong> — Insert or update the value at an index</li><li><strong>getMax()</strong> — Retrieve the highest number seen so far</li></ol><p>The interviewer clarified:</p><ul><li>The solution need not be <em>perfectly optimal</em>,</li><li>But it must <strong>not</strong> be brute force.</li></ul><p>I started with a practical <strong>Heap + HashMap</strong> design and later improved it to a cleaner <strong>HashMap + TreeMap</strong> structure when optimization was requested.</p><p>This article breaks down both versions — including diagrams, Java code, complexities, and interview insights.</p><h3>📌 Problem Breakdown</h3><p>We receive continuous inputs in the form (index, num) where:</p><ul><li>index → position</li><li>num → value</li><li>We must support updates to any index at any time</li><li>At any moment, getMax() should return the highest number so far</li></ul><p>Brute force (scanning all values every time) is not allowed.</p><h3>Why this problem matters</h3><p>Interviewers typically ask this problem to evaluate:</p><ul><li>ability to design dynamic data structures</li><li>reasoning on trade-offs</li><li>handling constraints and scale</li><li>debugging and extending data structures</li></ul><h3>Solution 1: Max-Heap + HashMaps (Initial Approach)</h3><p><em>Practical, production-friendly, but includes lazy deletion.</em></p><h3>Data Structures</h3><pre>indexMap: index → num<br>numMap:   num → set of indexes<br>maxHeap:  max-heap of (num, index) pairs</pre><h3>Diagram: Heap + Map Flow</h3><pre>update(index, num)<br>                |<br>                v<br>     ┌──────────────────────────┐<br>     │        indexMap          │<br>     │  index → latest num      │<br>     └──────────────────────────┘<br>                |<br>                v<br>     ┌──────────────────────────┐<br>     │          numMap          │<br>     │   num → {indexes...}     │<br>     └──────────────────────────┘<br>                |<br>                v<br>     ┌──────────────────────────┐<br>     │         maxHeap          │<br>     │   stores (num, index)    │<br>     │   lazy delete stale      │<br>     └──────────────────────────┘<br>                |<br>                v<br>            getMax()</pre><h3>Java Code: Heap + HashMaps</h3><pre>import java.util.*;<br><br>public class MaxTrackerWithHeap {<br><br>    private final Map&lt;Integer, Integer&gt; indexMap = new HashMap&lt;&gt;();<br>    private final Map&lt;Integer, Set&lt;Integer&gt;&gt; numMap = new HashMap&lt;&gt;();<br><br>    private final PriorityQueue&lt;long[]&gt; maxHeap = new PriorityQueue&lt;&gt;(<br>        (a, b) -&gt; Long.compare(b[0], a[0])<br>    );<br><br>    public void update(int index, int num) {<br>        if (indexMap.containsKey(index)) {<br>            int old = indexMap.get(index);<br>            Set&lt;Integer&gt; set = numMap.get(old);<br>            if (set != null) {<br>                set.remove(index);<br>                if (set.isEmpty()) numMap.remove(old);<br>            }<br>        }<br>        indexMap.put(index, num);<br>        numMap.computeIfAbsent(num, k -&gt; new HashSet&lt;&gt;()).add(index);<br>        maxHeap.offer(new long[]{num, index});<br>    }<br><br>    public Integer getMax() {<br>        while (!maxHeap.isEmpty()) {<br>            long[] top = maxHeap.peek();<br>            int num = (int) top[0];<br>            int idx = (int) top[1];<br>            Integer current = indexMap.get(idx);<br>            if (current != null &amp;&amp; current == num &amp;&amp;<br>                numMap.containsKey(num) &amp;&amp;<br>                numMap.get(num).contains(idx)) {<br>                return num;<br>            }<br>            maxHeap.poll(); // stale entry<br>        }<br>        return null;<br>    }<br>}</pre><h3>Complexity</h3><p>Update - O(log n) due to heap push</p><p>GetMax - Amortized O(1), worst O(n) due to stale cleanup</p><h3>📌 Further Interview ask</h3><p>After I explained Solution 1, the interviewer said:</p><blockquote>“Good. But we still have more than 30 minutes left. Can you design something even more optimal? Something cleaner without stale heap entries?”</blockquote><p>This is where we moved toward a TreeMap solution</p><h3>Solution 2: HashMap + TreeMap (Optimized Approach)</h3><p><em>Cleaner, deterministic, and avoids stale heap entries.</em></p><h3>Data Structure</h3><pre>indexMap: index → num<br>freqMap:  num → count (sorted TreeMap)</pre><h3>Diagram: TreeMap Flow</h3><pre>update(index, num)<br>                |<br>                v<br>     ┌──────────────────────────┐<br>     │        indexMap          │<br>     └──────────────────────────┘<br>                |<br>                v<br>     ┌──────────────────────────┐<br>     │         freqMap          │<br>     │   num → frequency        │<br>     │  (TreeMap sorted keys)   │<br>     └──────────────────────────┘<br>                |<br>                v<br>          getMax() = lastKey()</pre><h3>Java Code: HashMap + TreeMap</h3><pre>import java.util.*;<br><br>public class MaxTrackerWithTreeMap {<br><br>    private final Map&lt;Integer, Integer&gt; indexMap = new HashMap&lt;&gt;();<br>    private final TreeMap&lt;Integer, Integer&gt; freqMap = new TreeMap&lt;&gt;();<br><br>    public void update(int index, int num) {<br>        if (indexMap.containsKey(index)) {<br>            int old = indexMap.get(index);<br>            decrementFreq(old);<br>        }<br>        indexMap.put(index, num);<br>        freqMap.put(num, freqMap.getOrDefault(num, 0) + 1);<br>    }<br>    public Integer getMax() {<br>        if (freqMap.isEmpty()) return null;<br>        return freqMap.lastKey();<br>    }<br>    private void decrementFreq(int num) {<br>        int count = freqMap.get(num);<br>        if (count == 1) freqMap.remove(num);<br>        else freqMap.put(num, count - 1);<br>    }<br>}</pre><h3>Complexity</h3><p>Update - O(log m) where m = distinct nums</p><p>GetMax - O(1) / O(log m) (TreeMap.lastKey)</p><h3>Why this is better</h3><ul><li>No lazy cleanup</li><li>Always consistent</li><li>Easy to reason about</li><li>Cleaner for interviews</li></ul><p>The interviewer confirmed this as the preferred optimized structure.</p><h3>Comparison</h3><p><strong>Soltion 1: Heap + HashMaps</strong><br> <strong>Pros:</strong> Fast max retrieval; common in real systems; no tree rebalancing on every update<br> <strong>Cons:</strong> Stale entries; extra cleanup logic</p><p><strong>Solution 2: HashMap + TreeMap</strong><br> <strong>Pros:</strong> Clean, deterministic, no stale state<br> <strong>Cons:</strong> high-frequency updates Solution 1.</p><p><strong>When Solution 1 (Heap + HashMaps) Is the Better Choice</strong></p><p>Heap + HashMaps may introduce stale entries, but the trade-off brings:</p><ul><li>richer data structures</li><li>easier extension</li><li>more powerful queries</li><li>better resilience in streaming systems</li></ul><p>This is why similar hybrid designs (HashMap + Heap) are common in production systems such as <strong>schedulers, caches, and event-driven services.</strong></p><h3>Interview Takeaways</h3><ul><li>Start with a solid working solution.</li><li>Optimize only when asked.</li><li>Explain trade-offs clearly.</li><li>Lazy deletion is a valid early-phase approach.</li><li>TreeMap is often the elegant follow-up optimization.</li></ul><p>This reflects exactly what Atlassian looks for in its Fullstack CodeCraft rounds: <em>clarity, reasoning, scalability, and iterative improvement</em>.</p><p>🔗 Follow Me on LinkedIn — <a href="https://www.linkedin.com/in/shubhamgupta-india/">https://www.linkedin.com/in/shubhamgupta-india/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a0f3eea76aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design Kafka — LLD Question in Sprinklr Interview]]></title>
            <link>https://medium.com/@shubham18p2/design-kafka-lld-question-in-sprinklr-interview-05105fc8e73a?source=rss-6218d4a4752------2</link>
            <guid isPermaLink="false">https://medium.com/p/05105fc8e73a</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[lld]]></category>
            <category><![CDATA[producer-consumer-problem]]></category>
            <dc:creator><![CDATA[Shubham Gupta]]></dc:creator>
            <pubDate>Thu, 27 Nov 2025 03:11:48 GMT</pubDate>
            <atom:updated>2025-11-27T04:20:48.382Z</atom:updated>
            <content:encoded><![CDATA[<h3>📡 Design Kafka — LLD Question in Sprinklr Interview</h3><p>How I built a <strong>mini-Kafka</strong> from scratch during a <strong>Lead Backend Engineer interview at Sprinklr</strong>. This is a powerful way to demonstrate your LLD skills — especially in senior backend interviews.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KQGk_Z7cbIJcz7U6K5NU1Q.png" /><figcaption>Kafka Event System</figcaption></figure><p>The interviewer asked:</p><blockquote><strong><em>“Design a producer–consumer architecture where events are mapped to consumers similar to Kafka topics.<br> No Kafka allowed.<br> Support multiple consumers reading the same topic.<br> Define producer capacity. ”</em></strong></blockquote><p>This article walks you through how I solved it — evolving from a simple queue-based model into a multi-topic Kafka-style system — exactly the kind of step-by-step thinking interviewers expect.</p><h3>Why This Question Is Asked</h3><p>The goal is not to recreate Kafka. The goal is to evaluate:</p><ul><li><strong>Threading and concurrency fundamentals</strong></li><li><strong>Queue-based system design</strong></li><li><strong>Producer–consumer backpressure handling</strong></li><li><strong>Topic-based segregation</strong></li><li><strong>Scalability and extensibility</strong></li><li>Ability to <strong>start simple and evolve the design</strong></li></ul><p>This is a classic LLD + distributed systems blend.</p><h3>Step 1 — Start With a Simple Producer–Consumer Model</h3><p>When given an underspecified problem, your first step should be to anchor the discussion with fundamentals.</p><p>I started with a simple setup:</p><ul><li>One queue</li><li>Two producers</li><li>Two consumers</li><li>A bounded LinkedBlockingQueue for backpressure</li></ul><p>This demonstrates you’re comfortable with real-world concurrency primitives.</p><h3>Code (Simplest Version)</h3><pre>import java.util.concurrent.BlockingQueue;<br>import java.util.concurrent.LinkedBlockingQueue;<br>import java.util.concurrent.ExecutorService;<br>import java.util.concurrent.Executors;<br><br>class Event {<br>    private final String message;<br>    public Event(String message) { this.message = message; }<br>    public String getMessage() { return message; }<br>}<br><br>class Producer implements Runnable {<br>    private final BlockingQueue&lt;Event&gt; queue;<br>    private final int id;<br>    public Producer(BlockingQueue&lt;Event&gt; queue, int id) {<br>        this.queue = queue;<br>        this.id = id;<br>    }<br>    @Override<br>    public void run() {<br>        try {<br>            for (int i = 0; i &lt; 10; i++) {<br>                Event event = new Event(&quot;Event &quot; + i + &quot; from Producer &quot; + id);<br>                queue.put(event);   // backpressure-aware<br>                System.out.println(&quot;Produced: &quot; + event.getMessage());<br>                Thread.sleep(200);<br>            }<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>}<br><br>class Consumer implements Runnable {<br>    private final BlockingQueue&lt;Event&gt; queue;<br>    private final int id;<br><br>    public Consumer(BlockingQueue&lt;Event&gt; queue, int id){<br>        this.queue = queue;<br>        this.id = id;<br>    }<br><br>    @Override<br>    public void run() {<br>        try {<br>            while(true){<br>                Event event = queue.take();<br>                System.out.println(&quot;Consumer &quot; + id + &quot; processed: &quot; + event.getMessage());<br>                Thread.sleep(100);<br>            }<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>}<br><br>public class KafkaSystemDriver {<br>    public static void main(String[] args) {<br>        BlockingQueue&lt;Event&gt; queue = new LinkedBlockingQueue&lt;&gt;(5);<br>        ExecutorService executor = Executors.newFixedThreadPool(4);<br>        executor.submit(new Producer(queue, 1));<br>        executor.submit(new Producer(queue, 2));<br>        executor.submit(new Consumer(queue, 1));<br>        executor.submit(new Consumer(queue, 2));<br>        executor.shutdown();<br>    }<br>}</pre><h3>Why this step is important</h3><p>This shows:</p><ul><li>You understand concurrency basics</li><li>You can build simple systems first</li><li>You don’t jump into complexity prematurely</li></ul><p>Once this foundation is set, you evolve the design into the requirements.</p><h3>Step 2 — Add Topics Like Kafka</h3><p>The interviewer now asked:</p><blockquote><em>“Imagine you have event types, like Kafka topics.<br> Each topic should have separate consumers.”</em></blockquote><p>This is where the architecture becomes more interesting.</p><p>I introduced:</p><ul><li>A <strong>map of eventType → BlockingQueue</strong></li><li>Each event now includes a type</li><li>Consumers subscribe to a specific topic queue</li><li>Many consumers can read from the same topic (consumer group style)</li></ul><h3>Event Now Has a Type</h3><pre>class Event {<br>    private final String message;<br>    private final String type;<br><br>public Event(String type, String message){<br>        this.message = message;<br>        this.type = type;<br>    }<br>    public String getMessage() {<br>        return message;<br>    }<br>}</pre><h3>Topic-Aware Producer</h3><pre>class Producer {<br><br>private final Map&lt;String, BlockingQueue&lt;Event&gt;&gt; queues;<br>    private final int id;<br><br>    public Producer(Map&lt;String, BlockingQueue&lt;Event&gt;&gt; queues, int id){<br>        this.queues = queues;<br>        this.id = id;<br>    }<br>    public void produce(String type, String message){<br>        Event event = new Event(type, message);<br>        BlockingQueue&lt;Event&gt; queue = queues.get(type);<br>        if(queue != null){<br>            try{<br>                queue.put(event);<br>                System.out.println(&quot;Produced event: &quot; + type + &quot; =&gt; &quot; + event.getMessage());<br>            } catch (InterruptedException e){<br>                Thread.currentThread().interrupt();<br>            }<br>        } else {<br>            System.out.println(&quot;No consumer for event type: &quot; + type);<br>        }<br>    }<br>}</pre><h3>Consumers for Each Topic</h3><pre>class Consumer implements Runnable {<br><br>    private final BlockingQueue&lt;Event&gt; queue;<br>    private final int id;<br><br>    public Consumer(BlockingQueue&lt;Event&gt; queue, int id){<br>        this.queue = queue;<br>        this.id = id;<br>    }<br>    @Override<br>    public void run() {<br>        try{<br>            while(true){<br>                Event event = queue.take();<br>                System.out.println(&quot;Consumer &quot; + id + &quot; processed: &quot; + event.getMessage());<br>                Thread.sleep(250);<br>            }<br>        } catch (InterruptedException e){<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>}</pre><h3>Step 3 — Multi-Topic, Multi-Consumer Setup (Kafka Lite)</h3><pre>public class Main {<br><br>public static void main(String[] args){<br><br>        Map&lt;String,BlockingQueue&lt;Event&gt;&gt; eventQueues = new HashMap&lt;&gt;();<br>        eventQueues.put(&quot;type1&quot;, new LinkedBlockingQueue&lt;&gt;(5));<br>        eventQueues.put(&quot;type2&quot;, new LinkedBlockingQueue&lt;&gt;(5));<br>        eventQueues.put(&quot;type3&quot;, new LinkedBlockingQueue&lt;&gt;(5));<br>        Producer producer = new Producer(eventQueues, 1);<br>        // Consumers for different topics<br>        new Thread(new Consumer(eventQueues.get(&quot;type1&quot;), 1)).start();<br>        new Thread(new Consumer(eventQueues.get(&quot;type1&quot;), 2)).start();<br>        new Thread(new Consumer(eventQueues.get(&quot;type2&quot;), 3)).start();<br>        new Thread(new Consumer(eventQueues.get(&quot;type3&quot;), 4)).start();<br>        int j = 1;<br>        // Produce events for each topic<br>        for (int i = 0; i &lt; 10; i++) producer.produce(&quot;type1&quot;, &quot;Event &quot;+ j++ +&quot; Type: type1&quot;);<br>        for (int i = 0; i &lt; 10; i++) producer.produce(&quot;type2&quot;, &quot;Event &quot;+ j++ +&quot; Type: type2&quot;);<br>        for (int i = 0; i &lt; 10; i++) producer.produce(&quot;type3&quot;, &quot;Event &quot;+ j++ +&quot; Type: type3&quot;);<br>        // Invalid topic handling<br>        producer.produce(&quot;type4&quot;, &quot;Event with no topic&quot;);<br>    }<br>}</pre><h3>🧪 Test: Multi-Consumer Delivery &amp; Producer Capacity</h3><p>To validate the design, the interviewer asked me to create tests for two scenarios. I kept things simple and built one test per requirement.</p><h3>1️⃣ Multi-Consumer Test (Competing Consumers)</h3><p>Set up <strong>one producer</strong> and <strong>two consumers</strong> listening to the same event type.<br> When the test runs, the output clearly shows that <strong>the two consumers share the load</strong> — each event is processed by <strong>exactly one</strong> consumer, validating competing-consumer behavior similar to Kafka partitions.</p><p>This proves that:</p><ul><li>Messages are not broadcast to all consumers</li><li>Each consumer receives a subset of events</li><li>Load is naturally distributed</li></ul><h3>2️⃣ Producer Capacity Test (Backpressure Simulation)</h3><p>For the second validation, configured a topic queue with a <strong>capacity of 5</strong>.</p><p>Then:</p><ul><li>Produced <strong>10 events</strong>, which exceeds the capacity</li><li>Intentionally added a delay before starting a consumer</li></ul><p>In the output, you’ll see that once the queue reaches capacity, <strong>additional produce attempts block or fail until a consumer frees space</strong>.<br> As soon as the consumer starts consuming, new events begin to flow again.</p><p>This demonstrates:</p><ul><li>Producer backpressure</li><li>Queue capacity enforcement</li><li>How slow consumers can throttle producers (just like Kafka’s internal behavior)</li></ul><h3>⭐ <strong>Full Simplified LLD Code (Clean + Interview Ready)</strong></h3><pre>import java.util.concurrent.BlockingQueue;<br>import java.util.concurrent.LinkedBlockingQueue;<br>import java.util.concurrent.ConcurrentHashMap;<br>import java.util.Map;<br><br>public class Kafka {<br><br>    public static void main(String[] args) throws InterruptedException {<br>        Broker broker = new Broker();<br><br>        // Create topics<br>        broker.createTopic(&quot;type1&quot;, 5);<br>        broker.createTopic(&quot;type2&quot;, 5);<br><br>        // Start consumers for type1<br>        new Thread(new Consumer(&quot;Consumer-A&quot;, broker, &quot;type1&quot;)).start();<br>        new Thread(new Consumer(&quot;Consumer-B&quot;, broker, &quot;type1&quot;)).start();<br><br>        // Start consumer for type2<br>        new Thread(new Consumer(&quot;Consumer-C&quot;, broker, &quot;type2&quot;)).start();<br><br>        Producer producer = new Producer(broker);<br><br>        // Produce events<br>        for (int i = 1; i &lt;= 10; i++) {<br>            boolean success = producer.send(&quot;type1&quot;, &quot;id-&quot; + i, &quot;Message &quot; + i);<br>            System.out.println(&quot;Produced type1 Event &quot; + i + &quot; success=&quot; + success);<br>        }<br><br>        for (int i = 1; i &lt;= 5; i++) {<br>            producer.send(&quot;type2&quot;, &quot;id-&quot; + i, &quot;Message &quot; + i);<br>        }<br><br>        Thread.sleep(5000); // wait for consumers<br>    }<br>}<br><br>// -------- Event ----------<br>class Event {<br>    private final String id;<br>    private final String type;<br>    private final String payload;<br><br>    public Event(String id, String type, String payload) {<br>        this.id = id;<br>        this.type = type;<br>        this.payload = payload;<br>    }<br><br>    public String getId() { return id; }<br>    public String getType() { return type; }<br>    public String getPayload() { return payload; }<br><br>    @Override<br>    public String toString() {<br>        return &quot;Event{&quot; + &quot;id=&#39;&quot; + id + &#39;\&#39;&#39; + &quot;, type=&#39;&quot; + type + &#39;\&#39;&#39; + &quot;, payload=&#39;&quot; + payload + &#39;\&#39;&#39; + &#39;}&#39;;<br>    }<br>}<br><br>// -------- Topic ----------<br> class Topic {<br>    private final String name;<br>    private final BlockingQueue&lt;Event&gt; queue;<br><br>    public Topic(String name, int capacity) {<br>        this.name = name;<br>        this.queue = new LinkedBlockingQueue&lt;&gt;(capacity);<br>    }<br><br>    // Producer publishes event<br>    public boolean publish(Event event) {<br>        return queue.offer(event); // returns false if queue is full<br>    }<br><br>    // Consumer polls event<br>    public Event poll() throws InterruptedException {<br>        return queue.take(); // blocking call<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br>}<br><br>// -------- Broker ----------<br> class Broker {<br>    private final Map&lt;String, Topic&gt; topics = new ConcurrentHashMap&lt;&gt;();<br><br>    // Create a topic with capacity<br>    public void createTopic(String name, int capacity) {<br>        topics.putIfAbsent(name, new Topic(name, capacity));<br>    }<br><br>    // Producer sends message to topic<br>    public boolean publish(String topicName, Event event) {<br>        Topic topic = topics.get(topicName);<br>        if (topic == null) {<br>            System.out.println(&quot;Topic not found: &quot; + topicName);<br>            return false;<br>        }<br>        return topic.publish(event);<br>    }<br><br>    // Consumer polls message from topic<br>    public Event poll(String topicName) throws InterruptedException {<br>        Topic topic = topics.get(topicName);<br>        if (topic == null) throw new IllegalArgumentException(&quot;Topic not found: &quot; + topicName);<br>        return topic.poll();<br>    }<br>}<br><br>// -------- Producer ----------<br> class Producer {<br>    private final Broker broker;<br><br>    public Producer(Broker broker) {<br>        this.broker = broker;<br>    }<br><br>    public boolean send(String topic, String id, String payload) {<br>        return broker.publish(topic, new Event(id, topic, payload));<br>    }<br>}<br><br>// -------- Consumer ----------<br> class Consumer implements Runnable {<br>    private final Broker broker;<br>    private final String topicName;<br>    private final String name;<br><br>    public Consumer(String name, Broker broker, String topicName) {<br>        this.broker = broker;<br>        this.topicName = topicName;<br>        this.name = name;<br>    }<br><br>    @Override<br>    public void run() {<br>        try {<br>            while (true) {<br>                Event event = broker.poll(topicName);<br>                System.out.println(name + &quot; processed: &quot; + event);<br>            }<br>        } catch (InterruptedException e) {<br>            Thread.currentThread().interrupt();<br>        }<br>    }<br>}</pre><h3>What This Architecture Achieves</h3><h3>✔ Topic-based isolation</h3><p>Each event type gets its own queue, exactly like Kafka topics.</p><h3>✔ Multiple consumers per topic</h3><p>Consumers compete for events → consumer group behavior.</p><h3>✔ Backpressure with queue capacity</h3><p>Bounded queues mimic Kafka partition capacities.</p><h3>✔ Graceful handling of unknown event types</h3><p>Producer logs when topic doesn’t exist.</p><h3>✔ Extensible backbone</h3><p>You can add:</p><ul><li>Dead-letter queues</li><li>Retry queues</li><li>Partitioning</li><li>Offset tracking</li><li>Acknowledgement logic</li><li>Delivery guarantees (at-least-once, at-most-once)</li></ul><p>This is where you can shine in the discussion.</p><h3>How to Explain This in an Interview</h3><p>Here is the script I used:</p><blockquote><em>“I started with a basic producer–consumer pipeline for clarity, then evolved it into a Kafka-style architecture by introducing:</em></blockquote><ul><li>topic-based event queues,</li><li>multiple consumers per topic,</li><li>backpressure via queue capacity,</li><li>graceful handling of missing topics.</li></ul><blockquote><em>The design supports horizontal scalability, consumer groups, and backpressure control — the core of any event streaming system.”</em></blockquote><p>Interviewers appreciate this layered thinking.</p><h3>Conclusion</h3><p>This LLD exercise is much more than just writing code — it’s about showing:</p><ul><li>Concurrency knowledge</li><li>System design intuition</li><li>Ability to break down a vague requirement</li><li>Incremental architectural evolution</li><li>Production-grade thinking</li><li>Real-world understanding of Kafka-like systems</li></ul><p>This approach helped me handle the question confidently and leave a strong impression.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05105fc8e73a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Receiving Love Feels Harder Than Giving It]]></title>
            <link>https://medium.com/@shubham18p2/when-receiving-love-feels-harder-than-giving-it-7080c6c62b02?source=rss-6218d4a4752------2</link>
            <guid isPermaLink="false">https://medium.com/p/7080c6c62b02</guid>
            <category><![CDATA[emotional-health]]></category>
            <category><![CDATA[recieving]]></category>
            <category><![CDATA[self-awareness]]></category>
            <category><![CDATA[birthday]]></category>
            <category><![CDATA[self-love]]></category>
            <dc:creator><![CDATA[Shubham Gupta]]></dc:creator>
            <pubDate>Tue, 08 Jul 2025 21:00:38 GMT</pubDate>
            <atom:updated>2025-07-08T21:00:38.368Z</atom:updated>
            <content:encoded><![CDATA[<p><em>It was my first real birthday celebration, and I felt something I couldn’t explain. Ten years later, I finally understand what that feeling was.</em></p><p>9 years ago, I celebrated my birthday for the first time in my life.</p><p>I was in my final year of college. My friend at the time surprised me with gifts, events, and a celebration I never expected. It was personal, emotional, and full of affection. And yet, I remember feeling… sad. And confused. It didn’t make sense.</p><p>Why would someone feel sadness on a day full of love and care — especially when it was their <em>first</em> time ever being celebrated?</p><h3>🎂 Before That Day</h3><p>The year before, I had celebrated with my college friends — just a bunch of boys, dancing, laughing, cutting cake. It was casual, fun, easy. Nothing too emotional.</p><p>But this birthday was different. It was more than a party — it was someone saying:</p><blockquote>“You matter. You deserve care. You’re worth celebrating.”</blockquote><p>And for the first time in my 20+ years of life… someone meant it.</p><h3>😶‍🌫️ But I Couldn’t Understand My Emotions</h3><p>I didn’t feel happy. I didn’t feel bad either. I just felt… off.</p><p>For years, this puzzled me.<br> Why was I sad? Why didn’t I feel the joy that everyone else saw?</p><h3>🧠 A Decade Later — I Finally Understand</h3><p>Now, with distance and reflection, I can finally name what I felt.</p><p>It wasn’t just sadness — it was <strong>emotional overload</strong>.</p><p>I had spent my entire life giving — giving attention, love, care — and never really receiving.<br>So when someone gave to me — genuinely, without asking — my system didn’t know how to handle it.</p><p>And layered under that was something else I hadn’t seen clearly until now:<br>It was my final year of college.</p><p>I had just eight months left in that world of friendship, youth, laughter, and belonging.<br>Maybe I knew — deep down — that days like this wouldn’t come again easily.<br>That the love I was receiving now might not be around forever.<br>That the people, the moments, the magic — would soon become memory.</p><h3>💔 The Emotion Was Bittersweetness — Giving vs. Receiving</h3><p>For most of my life, I was the giver — the one offering attention, care, love, and support to those around me. Giving felt natural; it was how I showed I mattered.</p><p>But receiving? That was different. Receiving care, love, and celebration was unfamiliar territory — almost uncomfortable. It stirred something inside me I didn’t know how to name.</p><p>That birthday was the first time someone gave <em>without asking</em> for anything in return. And it overwhelmed me.</p><p>I realized that giving and receiving aren’t just opposite actions — they’re different emotional languages. I spoke giving fluently, but receiving was a dialect I hadn’t learned.</p><p>That mix of joy, grief, vulnerability, fear, and nostalgia all came from this tension between those two.</p><h3>💡 Naming the Feeling — A Lift Off My Shoulders</h3><p>Reflecting on that moment and finally putting a name to the emotion was like unlocking a door I’d been knocking on for years.</p><p>Acknowledging it made me feel lighter — as if I’d been carrying a weight I didn’t realize was mine to carry.</p><p>I felt compassion for my younger self, who was confused and unsure.</p><p>And I felt a sense of peace, knowing that what once puzzled me was actually a sign of emotional growth — not weakness.</p><h3>💬 Why I’m Writing This</h3><p>Because if you’ve ever felt strangely sad in a happy moment — you’re not broken.</p><p>Sometimes, the heart needs time to understand what it’s going through.<br>Sometimes, joy brings up grief.<br>Sometimes, receiving love feels like letting go of years of quiet loneliness — and that’s a lot to process.</p><p>And sometimes, what looks like sadness is just <strong>your heart growing</strong>.</p><h3>💪 The Strength in Vulnerability</h3><p>For a long time, I thought feeling confused or overwhelmed by emotions was a sign of weakness — especially as a man, expected to be strong and steady. But I’ve come to realize that vulnerability is actually a form of strength. It takes courage to face feelings you don’t understand and to be honest with yourself about them. That courage is where true growth begins.</p><h3>🤝 An Invitation to Self-Compassion</h3><p>If you find yourself feeling emotional confusion or discomfort, I invite you to be gentle with yourself. Healing and understanding don’t happen overnight. It’s okay to sit with uncertainty, to ask questions, and to give yourself permission to feel without judgment. This kindness toward yourself is part of the journey.</p><h3>🌱 Still Learning to Receive</h3><p>Even now, years later, I’m still learning how to receive care and love fully. It sometimes feels a little alien — like a language I’m just starting to understand. But I’m trying. And every small step toward openness feels like progress.</p><h3>🕊️ To Anyone Who Needs to Hear This</h3><p>You’re allowed to feel conflicted during beautiful moments.<br>You’re allowed to be moved, overwhelmed, even confused.<br>Receiving love can be as emotionally intense as giving it.</p><p>And if you’ve ever felt something that didn’t make sense back then — maybe today is the day you finally understand it.</p><p>It took me 9 years to understand one birthday.</p><p><strong>Maybe this is your moment.</strong></p><p><em>– Shubham Gupta</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7080c6c62b02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Adobe Interview LLD: Designing a Carvaan-Style Music Player in Java]]></title>
            <link>https://medium.com/@shubham18p2/adobe-interview-lld-designing-a-carvaan-style-music-player-in-java-12ea87537fef?source=rss-6218d4a4752------2</link>
            <guid isPermaLink="false">https://medium.com/p/12ea87537fef</guid>
            <category><![CDATA[adobe]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[music-player]]></category>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[lld]]></category>
            <dc:creator><![CDATA[Shubham Gupta]]></dc:creator>
            <pubDate>Wed, 11 Jun 2025 22:47:58 GMT</pubDate>
            <atom:updated>2025-06-12T00:15:25.312Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This Low-Level Design (LLD) problem was asked in Adobe interview, making it a great example to understand system design fundamentals in a practical scenario.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PK4tDeeScaO4n4aHx5yaiQ.png" /></figure><p>Carvaan is a popular portable music player that gives users a nostalgic experience with preloaded songs and simple hardware controls. But what if you wanted to implement your own music player with features like <strong>playlist, playback controls</strong>, and <strong>various playback modes</strong> like <em>shuffle</em>, <em>loop</em>, and <em>sequential</em>?</p><p>In this blog, I’ll walk you through a <strong>low-level design (LLD)</strong> of a music player system that supports these features — and how you can make it scalable for future enhancements.</p><h3>🧠 Problem Statement</h3><p>Design a <strong>music player</strong> that:</p><p>Supports playback modes:</p><ul><li><strong>Sequential</strong> — Plays songs in order.</li><li><strong>Loop</strong> — Repeats the current song.</li><li><strong>Shuffle</strong> — Randomizes playback.</li><li>Has basic controls: <strong>Play, Pause , Stop, Play Next</strong></li><li>Supports a future enhancement: In Shuffle mode, songs should be played once before repeating previously played songs.</li></ul><h3>⚠️ Points to Remember: Carvaan vs. Modern Music Apps</h3><p>Before diving deeper, it’s important to clarify how <strong>Carvaan</strong> as a hardware device differs from popular digital music apps like <strong>Spotify</strong> or <strong>Apple Music</strong>, especially in how playback modes and playlists are managed.</p><h3>🎛 Playback Mode Scope</h3><ul><li><strong>Carvaan</strong> is a hardware music player where the <strong>playback mode is a global setting</strong> — it affects the entire device regardless of the playlist.</li><li>In contrast, <strong>Spotify, Apple Music, and other apps</strong> assign playback modes <strong>per playlist</strong>, allowing each playlist to have its own independent mode.</li></ul><h3>📁Playlist Management in Carvaan</h3><ul><li>The <strong>Carvaan box plays only one playlist at a time</strong> and doesn’t support multiple playlists directly.</li><li>Users create playlists via the <strong>Carvaan app</strong>, which sends the selected playlist to the device.</li><li>It offers a <strong>simple, fixed playlist experience</strong>, unlike dynamic app-based players.</li></ul><h3>🔄 How This Impacts Our Design</h3><ul><li>Our design assumes <strong>one playlist is active on the Player at a time</strong>, similar to how Carvaan operates.</li><li>For future features like <strong>adding songs to playlists or supporting multiple simultaneous playlists</strong>, the mode logic and playlist management would need refinement.</li></ul><h3>🧩 High-Level Components</h3><ul><li>Player: Handles playback operations like play, pause, stop, and switching modes.</li><li>Playlist: Holds a list of songs and manages which song is currently playing.</li><li>PlaybackMode Interface: Abstracts how the next song is determined.</li></ul><p>Mode Implementations:</p><ul><li>SequentialPlaybackMode</li><li>LoopPlaybackMode</li><li>ShufflePlaybackMode</li><li>ModeFactory: Provides the appropriate playback mode.</li><li>Song: Represents a song with metadata like name, album, and singers.</li></ul><h3>🎛 Playback Modes Strategy</h3><p>We use the <strong>Strategy Design Pattern</strong> to implement playback behavior dynamically. Each mode implements the PlaybackMode interface and returns the appropriate next song based on the playlist state.</p><pre>interface PlaybackMode {<br>  Song getNextSong(Playlist playlist);<br>}</pre><h3>🎶 Playlist Management</h3><p>Each playlist maintains a list of songs and tracks the currently playing song’s index. It exposes methods to:</p><ul><li>Play a specific song</li><li>Get the next song (in sequential mode)</li></ul><pre>public class Playlist {<br><br>  List&lt;Song&gt; songList = new ArrayList&lt;&gt;();<br>  int currentSongIndex = 0;<br><br>  // for testing purpose<br>  void addSong(Song newSong) {<br>    songList.add(newSong);<br>  }<br><br>  Song getSong(int index) {<br>    if (index &gt;= 0 &amp;&amp; index &lt; songList.size()) {<br>      return songList.get(index);<br>    }<br>    return null;<br>  }<br><br>  Song getCurrentSong() {<br>    return getSong(currentSongIndex);<br>  }<br><br>  Song getNextSequential() {<br>    if (songList.size() == 0) return null;<br>    int nextSequentialSongIndex = currentSongIndex == songList.size() ? 0 : currentSongIndex + 1;<br>    return getSong(nextSequentialSongIndex);<br>  }<br><br>  int getSize() {<br>    return songList.size();<br>  }<br><br>  // play song at index<br>  void play(int index) {<br>    if (index &gt;= 0 &amp;&amp; index &lt; songList.size()) {<br>      currentSongIndex = index;<br>    }<br>  }<br><br>  /**<br>   * Returns the index of the given song in the playlist.<br>   *<br>   * &lt;p&gt;Future enhancement: - Replace linear search with a Map&lt;Song, Integer&gt; for O(1) lookup -<br>   * Update map in addSong() and removeSong() methods accordingly<br>   */<br>  public int getIndexOfSong(Song song) {<br>    return songList.indexOf(song); // Linear search for now<br>  }<br>}</pre><h3>🧪 Mode Implementations</h3><h3>🔁 Loop Mode</h3><pre>class LoopPlaybackMode implements PlaybackMode {<br>  @Override<br>  public Song getNextSong(Playlist playlist) {<br>    return playlist.getCurrentSong();<br>  }<br>}</pre><h3>📀 Sequential Mode</h3><pre>class SequentialPlaybackMode implements PlaybackMode {<br>  @Override<br>  public Song getNextSong(Playlist playlist) {<br>    return playlist.getNextSequential();<br>  }<br>}</pre><h3>🎲 Shuffle Mode (with enhancement)</h3><p>To prevent repeating songs before all are played, we keep track of “unplayed” indices and reset them once all songs have been played.</p><pre>public class ShufflePlaybackMode implements PlaybackMode {<br>  private List&lt;Integer&gt; unplayed = new ArrayList&lt;&gt;();<br>  private final Random random = new Random();<br><br>  @Override<br>  public Song getNextSong(Playlist playlist) {<br>    // Initialize unplayed list if empty<br>    if (unplayed.isEmpty()) {<br>      unplayed = initIndexList(playlist.getSize());<br>    }<br><br>    int songIndex = popRandomIndex(unplayed);<br>    return playlist.getSong(songIndex);<br>  }<br><br>    // Utility methods below<br>  }<br>}</pre><pre>private List&lt;Integer&gt; initIndexList(int size) {<br>    List&lt;Integer&gt; indices = new ArrayList&lt;&gt;(size);<br>    for (int i = 0; i &lt; size; i++) {<br>      indices.add(i);<br>    }<br>    return indices;<br>  }<br><br>  private int popRandomIndex(List&lt;Integer&gt; unplayed) {<br>    // O(1) random pick and remove using swap-and-remove-last<br>    int randIdx = random.nextInt(unplayed.size());<br>    int lastIdx = unplayed.size() - 1;<br><br>    // swap random and last<br>    Collections.swap(unplayed, randIdx, lastIdx);<br><br>    // remove last in O(1)<br>    return unplayed.remove(lastIdx);</pre><p>This ensures an optimized and fair shuffling mechanism, similar to how Spotify shuffle works.</p><h3>🕹 Player Controls</h3><p>The Player class ties everything together:</p><ul><li>It manages the playlist, mode, and player state.</li><li>Calls getNextSong() to determine which song to play based on the current mode.</li><li>Can switch modes at runtime.</li></ul><pre>public class Player {<br><br>  private PlaybackMode currentPlaybackMode;<br>  private Playlist currentPlaylist;<br><br>  private PlayerState playerState;<br><br>  public Player(Playlist playlist, Modes mode) {<br>    this.currentPlaylist = playlist;<br>    this.currentPlaybackMode = ModeFactory.get(mode);<br>    this.playerState = PlayerState.STOPPED;<br>  }<br><br>  // methods are defined below for readability<br>}</pre><pre><br>  void playNextSong() {<br>    Song nextSong = currentPlaybackMode.getNextSong(currentPlaylist);<br>    if (nextSong != null) {<br>      play(nextSong);<br>    } else {<br>      System.out.println(&quot;No songs available to play.&quot;);<br>    }<br>  }<br><br>  void changeMode(Modes mode) {<br>    currentPlaybackMode = ModeFactory.get(mode);<br>  }<br><br>  void play(Song song) {<br>    int index = currentPlaylist.getIndexOfSong(song);<br>    if (index &gt;= 0) {<br>      currentPlaylist.play(index);<br>      playerState = PlayerState.PLAYING;<br>      System.out.println(&quot;Playing: &quot; + song.getName());<br>    } else {<br>      System.out.println(&quot;Song not found in playlist.&quot;);<br>    }<br>  }<br><br>  void pause() {<br>    playerState = PlayerState.PAUSED;<br>  }<br><br>  void stop() {<br>    playerState = PlayerState.STOPPED;<br>  }</pre><h3>📦 Future-Proofing the Design</h3><ul><li>✅ You can add new modes by implementing the PlaybackMode interface.</li><li>✅ Optimize playlist operations using a Map&lt;Song, Integer&gt; for O(1) lookup.</li><li>✅ Support adding/removing songs from playlists dynamically and update mode logic accordingly.</li></ul><h3>🧼 Clean Code Practices</h3><ul><li><strong>Strategy Pattern </strong>enables flexible playback via PlaybackMode interface.</li><li><strong>Factory Pattern</strong> for mode instantiation (ModeFactory)</li><li><strong>Single Responsibility</strong> in classes (Song, Playlist, Player)</li><li><strong>Encapsulation</strong> in handling playlist state</li></ul><h3>🏁 Final Thoughts</h3><p>This LLD mirrors a real-world music player while keeping the architecture <strong>modular</strong>, <strong>testable</strong>, and <strong>open to extension</strong>. You could integrate this design with an Android app, a web UI, or even simulate hardware buttons — without changing core logic.</p><p>Let me know how you’d enhance this design! Maybe add a favorites feature? Or a queue-based system?</p><p><strong>🔗 GitHub with the full code — </strong><a href="https://github.com/gshubhamCode/lld-examples/tree/main/src/main/java/org/lld/musicplayer">gshubhamCode/lld/musicplayer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12ea87537fef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Designing a Fair Customer Processing System — A Real LLD Interview Question at Intuit]]></title>
            <link>https://medium.com/@shubham18p2/designing-a-fair-customer-processing-system-a-real-lld-interview-question-at-intuit-8cfba4a45372?source=rss-6218d4a4752------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cfba4a45372</guid>
            <category><![CDATA[interview-questions]]></category>
            <category><![CDATA[intuit]]></category>
            <category><![CDATA[lld]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[queue]]></category>
            <dc:creator><![CDATA[Shubham Gupta]]></dc:creator>
            <pubDate>Wed, 04 Jun 2025 03:56:49 GMT</pubDate>
            <atom:updated>2025-06-04T07:26:50.185Z</atom:updated>
            <content:encoded><![CDATA[<h3>🚦 Designing a Fair Customer Processing System — A Real LLD Interview Question at Intuit</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*2PSOArzLq0HHZgKIDwV8uw.jpeg" /><figcaption>VIP or Regular, Waiting your turn, but make it fair 😎</figcaption></figure><p>In a recent interview at <strong>Intuit</strong> for a <strong>Senior Backend Engineer</strong> role, I was asked a thought-provoking low-level design (LLD) problem. It seemed deceptively simple at first, but had several nuanced constraints around fairness, ordering, and extensibility.</p><p>In this post, I’ll walk you through the problem statement, my design approach, key data structures used, and how it could apply to real-world systems.</p><h3>📜 The Problem Statement</h3><p>Design a system to process <strong>VIP</strong> and <strong>Regular</strong> customers based on their arrival order. You need to enforce a <strong>customizable processing ratio</strong>, e.g., process 2 VIPs for every 1 Regular customer.</p><h3>Methods to implement:</h3><ul><li>addCustomer() – Adds a customer (VIP or Regular) to the system.</li><li>getNextCustomer() – Returns the next customer to be processed based on the configured ratio.</li></ul><p>📝 <strong>Sample Run (2 VIP : 1 Regular)</strong></p><pre>addCustomer([A:r])<br>addCustomer([B:v])<br>addCustomer([C:r])<br>addCustomer([D:v])<br>addCustomer([E:v])<br>addCustomer([F:r])<br>addCustomer([G:r])<br>addCustomer([H:r])</pre><pre>getNextCustomer() -&gt; B VIP<br>getNextCustomer() -&gt; D VIP<br>getNextCustomer() -&gt; A REGULAR<br>getNextCustomer() -&gt; E VIP<br>getNextCustomer() -&gt; C REGULAR<br>getNextCustomer() -&gt; F REGULAR<br>getNextCustomer() -&gt; G REGULAR<br>getNextCustomer() -&gt; H REGULAR</pre><h3>💡 Key Constraints</h3><ul><li>VIPs and Regulars must be processed in <strong>FIFO</strong> (first-in-first-out) order <strong>within their type</strong>.</li><li>The ratio must be <strong>configurable</strong>, e.g., 2:1, 3:2, etc.</li><li>Assume a <strong>single-threaded environment</strong>.</li><li>All customers are added <strong>upfront</strong> — no dynamic additions during processing.</li></ul><h3>🧠 Design Approach</h3><p>To solve this, I split responsibilities into clearly defined components:</p><h3>1. Customer Type Abstraction</h3><pre>enum CustomerType { VIP, REGULAR }</pre><pre>abstract class Customer {<br>    private String name;<br><br>    abstract public CustomerType getType();<br><br>    Customer(String name) {<br>        this.name = name;<br>    }<br>}</pre><pre>class VIPCustomer extends Customer {<br><br>    VIPCustomer(String name) {<br>        super(name);<br>    }<br><br>    @Override<br>    public CustomerType getType() {<br>        return CustomerType.VIP;<br>    }<br>}<br><br>class RegularCustomer extends Customer {<br><br>    RegularCustomer(String name) {<br>        super(name);<br>    }<br><br>    @Override<br>    public CustomerType getType() {<br>        return CustomerType.REGULAR;<br>    }<br>}</pre><h3>2. Queue Management</h3><p>Two separate queues:</p><ul><li>Queue&lt;Customer&gt; vipCustomers</li><li>Queue&lt;Customer&gt; regularCustomers</li></ul><p>This helps us maintain strict FIFO ordering for each customer type.</p><h3>3. Ratio Rule Engine</h3><p>Encapsulated logic to enforce the ratio:</p><pre>interface Rule {<br>    CustomerType getNextCustomerType();<br>}</pre><pre>class RatioRule implements Rule {<br><br>    final int vipCustomersLimit;<br>    final int regularCustomersLimit;<br><br>    int vipCustomerServed = 0;<br>    int regularCustomerServed = 0;<br><br>    public RatioRule(int vipCustomersLimit, int regularCustomersLimit) {<br>        this.vipCustomersLimit = vipCustomersLimit;<br>        this.regularCustomersLimit = regularCustomersLimit;<br>    }<br>    <br>     // Returns the next expected customer type based on ratio<br>    @Override<br>    public CustomerType getNextCustomerType() {<br>        // Reset counters when one full cycle is done<br>        if (vipCustomerServed == vipCustomersLimit <br>                &amp;&amp; regularCustomerServed == regularCustomersLimit) {<br>            vipCustomerServed = 0;<br>            regularCustomerServed = 0;<br>        }<br><br>        if (vipCustomerServed &lt; vipCustomersLimit) {<br>            vipCustomerServed++;<br>            return CustomerType.VIP;<br>        }<br><br>        regularCustomerServed++;<br>        return CustomerType.REGULAR;<br>    }<br>}</pre><h3>4. Processing Logic</h3><pre>// Customer Handler to add and get next customers<br>class CustomerHandler {<br><br>    Queue&lt;Customer&gt; vipCustomers = new LinkedList&lt;&gt;();<br>    Queue&lt;Customer&gt; regularCustomers = new LinkedList&lt;&gt;();<br>    Rule rule;<br><br>    CustomerHandler(Rule rule) {<br>        this.rule = rule;<br>    }<br><br>    // Below methods should be here<br>    // for readability kept them separated<br>}</pre><pre>public void addCustomer(Customer customer) {<br>        if (customer.getType() == CustomerType.VIP) {<br>            vipCustomers.add(customer);<br>        } else {<br>            regularCustomers.add(customer);<br>        }<br>    }</pre><pre>public Customer getNextCustomer() {<br>    CustomerType nextType = rule.getNextCustomerType();<br>    <br>    // Try to return from the preferred queue<br>    if (nextType == CustomerType.VIP &amp;&amp; !vipCustomers.isEmpty()) {<br>        return vipCustomers.remove();<br>    }<br>    if (nextType == CustomerType.REGULAR &amp;&amp; !regularCustomers.isEmpty()) {<br>        return regularCustomers.remove();<br>    }<br>    // Fallback if one queue is empty<br>    if (!vipCustomers.isEmpty()) return vipCustomers.remove();<br>    if (!regularCustomers.isEmpty()) return regularCustomers.remove();<br>    return null;<br>}</pre><h3>✅ Why This Works Well</h3><ul><li><strong>Correct ordering</strong> is guaranteed within each type.</li><li><strong>Ratio logic</strong> is cleanly separated via Rule interface – making it extensible.</li><li>Handles edge cases gracefully: when one type of queue runs out, we fallback to the available queue.</li><li>Maintains <strong>separation of concerns</strong> and is easy to test or extend.</li></ul><h3>🔁 Real-World Implications</h3><p>This kind of ratio-based fairness is common in:</p><ul><li><strong>Job schedulers</strong> (e.g., priority queues)</li><li><strong>Resource allocators</strong> (VIP customers getting faster checkout)</li><li><strong>Rate-limited APIs</strong> (premium vs free users)</li></ul><p>It was a good reminder that <strong>even simple-looking problems require deep understanding</strong> of design principles — FIFO ordering, extensibility, and fail-safety.</p><h3>🔍 Point to Consider</h3><p>⚠️ The RatioRule isn&#39;t aware of queue states, so it may request a VIP or Regular customer even if the respective queue is empty. However, since all customers are added upfront and the environment is single-threaded, this mismatch is harmless — the fallback logic in getNextCustomer() ensures correctness.</p><h3>💬 What We Discussed Next (Multi-threaded Setup)</h3><p>Although the initial solution assumed a single-threaded model, the interviewer and I explored how it could scale in multi-threaded systems:</p><ul><li><strong>Protect shared queues</strong> using locks or replace them with LinkedBlockingQueue for thread-safe operations.</li><li><strong>Use </strong><strong>AtomicInteger counters</strong> to maintain ratio state without full method synchronization (though it may require backoff strategies to avoid contention).</li></ul><p>Another way to achieve multi threading, <strong>Decouple </strong><strong>getNextCustomer() from setup logic</strong> by precomputing customer order into a thread-safe <strong>manager queue</strong>, enabling:</p><ul><li>Clean separation of processing and coordination</li><li><strong>Multiple clients</strong> to safely call getNextCustomer() concurrently .This approach ensures <strong>consistent ratio enforcement</strong> and <strong>safe concurrent access</strong> without race conditions.</li></ul><h3>👨‍💻 Final Thoughts</h3><p>If you’re prepping for interviews, this is a great question to practice. And if you’re building real systems, think about how this simple pattern — separating queues and abstracting the rule logic — can help you write <strong>cleaner</strong>, more <strong>adaptable</strong> code.</p><p>I appreciated this question not just for the technical design, but for the <strong>architectural awareness</strong> it prompted — balance between performance, fairness, and simplicity.</p><p><em>“Simple code isn’t always easy — it’s a sign of clean thought.”</em></p><h3>🙌 Let’s Connect</h3><ul><li>Have thoughts or questions? Drop them in the comments.</li><li>Want to see the full code? <a href="https://github.com/gshubhamCode/lld-examples/tree/main/src/main/java/org/lld/customerqueue">https://github.com/gshubhamCode/lld-examples/tree/main/src/main/java/org/lld/customerqueue</a></li><li>You can also follow me here for more Real-world backend design questions, System design breakdowns and Clean coding practices</li></ul><p>Let’s build smart, scalable systems — one queue at a time. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cfba4a45372" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>