<?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 Rajendra Bisoi on Medium]]></title>
        <description><![CDATA[Stories by Rajendra Bisoi on Medium]]></description>
        <link>https://medium.com/@coderraj07?source=rss-3ecd9ab4ad4d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6vL_O8DOoJKiFKqcWkoV9g.png</url>
            <title>Stories by Rajendra Bisoi on Medium</title>
            <link>https://medium.com/@coderraj07?source=rss-3ecd9ab4ad4d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 00:06:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@coderraj07/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[ContextVar in Python]]></title>
            <link>https://coderraj07.medium.com/contextvar-in-python-0e5121ef226b?source=rss-3ecd9ab4ad4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e5121ef226b</guid>
            <dc:creator><![CDATA[Rajendra Bisoi]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 15:16:05 GMT</pubDate>
            <atom:updated>2026-09-28T15:16:05.045Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s the simplest example showing <strong>why </strong><strong>ContextVar is useful when calling deeper functions</strong>.</p><h3>Without ContextVar</h3><p>You have to keep passing the value:</p><pre>def controller(request_id):<br>    service(request_id)</pre><pre>def service(request_id):<br>    database(request_id)</pre><pre>def database(request_id):<br>    print(&quot;Request:&quot;, request_id)<br></pre><pre>controller(&quot;ABC-123&quot;)</pre><p>The request_id travels through every function:</p><pre>controller<br>    ↓ request_id<br>service<br>    ↓ request_id<br>database</pre><h3>With ContextVar</h3><pre>from contextvars import ContextVar</pre><pre>request_id = ContextVar(&quot;request_id&quot;)<br></pre><pre>def controller():<br>    request_id.set(&quot;ABC-123&quot;)</pre><pre>    service()<br></pre><pre>def service():<br>    database()<br></pre><pre>def database():<br>    print(&quot;Request:&quot;, request_id.get())<br></pre><pre>controller()</pre><p>Output:</p><pre>Request: ABC-123</pre><p>Notice:</p><pre>controller()<br>    ↓<br>service()<br>    ↓<br>database()</pre><p>We <strong>never passed </strong><strong>request_id</strong>:</p><pre>service()       # no request_id<br>database()      # no request_id</pre><p>But database() can still access it:</p><pre>request_id.get()</pre><p>because all three functions are running in the <strong>same execution context</strong>.</p><h3>Visualize it</h3><pre>Context<br>┌─────────────────────────────┐<br>│ request_id = &quot;ABC-123&quot;      │<br>│                             │<br>│  controller()               │<br>│       ↓                     │<br>│  service()                  │<br>│       ↓                     │<br>│  database()                 │<br>│       ↓                     │<br>│  request_id.get()           │<br>│       ↓                     │<br>│  &quot;ABC-123&quot;                  │<br>└─────────────────────────────┘</pre><p>This is why it’s useful in backend applications for something like:</p><pre>HTTP Request<br>   ↓<br>Controller<br>   ↓<br>Service<br>   ↓<br>Repository<br>   ↓<br>Logger</pre><p>You can put the <strong>request ID / trace ID</strong> into a ContextVar once at the top, and your deeper functions can retrieve it without adding request_id to every function&#39;s parameters.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e5121ef226b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Context Manager and Yield in Python]]></title>
            <link>https://coderraj07.medium.com/context-manager-and-yield-c292b393bbfe?source=rss-3ecd9ab4ad4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c292b393bbfe</guid>
            <dc:creator><![CDATA[Rajendra Bisoi]]></dc:creator>
            <pubDate>Mon, 28 Sep 2026 15:10:44 GMT</pubDate>
            <atom:updated>2026-09-28T15:19:09.239Z</atom:updated>
            <content:encoded><![CDATA[<h3>1. Context manager with yield — NO value</h3><pre>from contextlib import contextmanager</pre><pre>@contextmanager<br>def my_context():<br>    print(&quot;Before&quot;)</pre><pre>    yield</pre><pre>    print(&quot;After&quot;)<br></pre><pre>with my_context():<br>    print(&quot;Inside&quot;)</pre><p>Output:</p><pre>Before<br>Inside<br>After</pre><p>Here, there is <strong>no </strong><strong>as</strong> because yield doesn&#39;t provide a value:</p><pre>yield</pre><p>Think:</p><pre>Before<br>  ↓<br>yield → pause<br>  ↓<br>with block runs<br>  ↓<br>resume<br>  ↓<br>After</pre><h3>2. Context manager with yield — VALUE</h3><p>Now let’s yield a value:</p><pre>from contextlib import contextmanager</pre><pre>@contextmanager<br>def my_context():<br>    value = 10</pre><pre>    print(&quot;Before&quot;)</pre><pre>    yield value</pre><pre>    print(&quot;After&quot;)<br></pre><pre>with my_context() as x:<br>    print(&quot;Inside:&quot;, x)</pre><p>Output:</p><pre>Before<br>Inside: 10<br>After</pre><p>Here:</p><pre>yield value</pre><p>gives 10 to:</p><pre>as x</pre><p>So:</p><pre>x = 10</pre><h3>3. Now let’s modify the value AFTER the yield</h3><p>This is where it becomes interesting:</p><pre>from contextlib import contextmanager</pre><pre>@contextmanager<br>def my_context():<br>    value = 10</pre><pre>    print(&quot;Before&quot;)</pre><pre>    yield value</pre><pre>    value = value * 2</pre><pre>    print(&quot;After:&quot;, value)<br></pre><pre>with my_context() as x:<br>    print(&quot;Inside:&quot;, x)</pre><p>Output:</p><pre>Before<br>Inside: 10<br>After: 20</pre><p>Notice:</p><pre>yield value</pre><p>gave 10 to x.</p><p>Then the with block finished.</p><p>Then Python continued here:</p><pre>value = value * 2</pre><p>So value became 20.</p><p><strong>But </strong><strong>x is still 10.</strong></p><pre>value inside context manager<br>       ↓<br>      10<br>       ↓<br>     yield<br>       ↓<br>   x receives 10<br>       ↓<br>  with block runs<br>       ↓<br> context manager resumes<br>       ↓<br>   value = 10 × 2<br>       ↓<br>      20</pre><p>The important thing is that <strong>yield is a pause/resume point, not a normal </strong><strong>return.</strong></p><p>return:</p><pre>return value</pre><p>➡️ function ends permanently.</p><p>yield:</p><pre>yield value</pre><p>➡️ function pauses → with block runs → function continues after yield.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c292b393bbfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Go Doesn’t Need async/await: Understanding Goroutines and the G-M-P Scheduler]]></title>
            <link>https://coderraj07.medium.com/why-go-doesnt-need-async-await-understanding-goroutines-and-the-g-m-p-scheduler-d93ce2858f80?source=rss-3ecd9ab4ad4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/d93ce2858f80</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[golang-tutorial]]></category>
            <category><![CDATA[design-pattern-in-golang]]></category>
            <category><![CDATA[golang-development]]></category>
            <dc:creator><![CDATA[Rajendra Bisoi]]></dc:creator>
            <pubDate>Tue, 21 Jul 2026 16:37:21 GMT</pubDate>
            <atom:updated>2026-07-21T16:40:31.951Z</atom:updated>
            <content:encoded><![CDATA[<p>Most developers coming from Python, JavaScript, or Java ask the same question when they first see Go code:</p><blockquote><em>“Where is async/await in Go?”</em></blockquote><p>The surprising answer is:</p><p><strong>Go doesn’t have it.</strong></p><p>Instead of forcing you to sprinkle async and await keywords across your codebase, Go handles concurrency at the runtime level. Its ultimate goal is simple:</p><p><strong>Never let a CPU sit idle when there is work to do.</strong></p><p>To understand how Go achieves this, we need to trace a journey from basic OS processes to the core engine of Go: the G-M-P Scheduler.</p><h3>1. The Core Problem: How Operating Systems Handle Tasks</h3><p>Before looking at Go, let’s understand how traditional operating systems run your code.</p><pre>Python / Java / C++<br><br>Process<br>    |<br>    +--- Thread<br>    +--- Thread<br>    +--- Thread<br><br><br>Go<br><br>Process<br>    |<br>    +--- Go Runtime<br>            |<br>            +--- Goroutine<br>            +--- Goroutine<br>            +--- Goroutine<br>                    |<br>             Few OS Threads</pre><h3>Crucial Reality Check:</h3><p>The operating system only knows about <strong>Processes</strong> and <strong>Threads.</strong> It has no idea what a goroutine is.</p><h3>The Building Blocks</h3><p><strong>Process:</strong> An independent running program (e.g., Chrome or Spotify) with its own isolated memory space.</p><p><strong>OS Thread:</strong> The smallest unit of execution inside a process managed directly by the OS kernel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*zP3clI-cay1FdwVnvFE_4A.png" /></figure><h3>The Bottleneck: The “100,000 Request” Problem</h3><p>Imagine you are building a web server that needs to handle <strong>100,000 requests simultaneously.</strong></p><p>If you create <strong>1 OS thread per request (the traditional model):</strong></p><p><strong>Memory Exhaustion:<br></strong>100,000 threads×1 MB stack=100 GB of RAM</p><p>just to keep threads alive!</p><p><strong>CPU Waste:</strong> The OS kernel spends more time context-switching between 100,000 threads than doing actual work.</p><h3>2. When to Use What: Processes, Threads, Async/Await, or Goroutines</h3><p>Choosing the wrong tool for the job causes major performance traps. Here is how to pick the right concurrency model:</p><pre>What type of work are you doing?<br>                                 │<br>         ┌───────────────────────┴───────────────────────┐<br>         ▼                                               ▼<br>   CPU-Bound Work                                  I/O-Bound Work<br>(Heavy Math, Image Processing,                (APIs, DBs, Sockets, Files)<br> Video Encoding, Machine Learning)                       │<br>         │                                               │<br>         ▼                                               ▼<br>  Are you in Python/Ruby?                          Language Choice?<br>   ├── YES ──► Use Processes (Multiprocessing)           ├── JS/Node/Python  ──► Use Async / Await<br>   └── NO  ──► Use Threads / C++ / Rust                  └── Go              ──► Use Goroutines                                                                  </pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*kuewDUHgg8LqFRJwKLSaXQ.png" /></figure><h3>3. How Languages Compare Code Side-by-Side</h3><p>Let’s see how you fetch data from three endpoints (DB, Redis, API) concurrently in Python, JavaScript, and Go:</p><h3>Go: Synchronous Look, Asynchronous Execution</h3><pre>// Sequential execution<br>func main() {<br>    fetchDB()<br>    fetchRedis()<br>    fetchAPI()<br>}<br><br>// Concurrent execution (Just prepend &#39;go&#39;!)<br>func main() {<br>    go fetchDB()<br>    go fetchRedis()<br>    go fetchAPI()<br>}</pre><h3>Python: Explicit Threading or Async/Await</h3><pre># Asyncio requires declaring functions with async/await keywords<br>await asyncio.gather(<br>    fetch_db(),<br>    fetch_redis(),<br>    fetch_api(),<br>)</pre><h3>JavaScript: Promises &amp; Event Loop</h3><pre>// Requires Promise wrapper and explicit await<br>await Promise.all([<br>    fetchDB(),<br>    fetchRedis(),<br>    fetchAPI(),<br>]);</pre><p><strong>Why Go is Different:</strong> In Python and JavaScript, you explicitly manage concurrency using keywords like async, await, or Promise.all(). In Go, you write plain, readable code and prepend the go keyword. The Go Runtime takes care of scheduling non-blocking calls behind the scenes.</p><h3>4. The Analogy: Packages, Drivers, and Trucks</h3><p>To understand how Go keeps the CPU busy without consuming gigabytes of memory, let’s use a delivery service analogy:</p><pre>[ Package ]  ────────►  Goroutine (G)           The work to be done (~2 KB stack)<br>[ Driver  ]  ────────►  Logical Processor (P)   The scheduler context (queues tasks)<br>[ Truck   ]  ────────►  OS Thread (M)           The physical execution vehicle</pre><p><strong>Goroutine (G) = Package:</strong> The code task you want to execute (e.g., go fetchDB()). Starts tiny (~2 KB stack).</p><p><strong>Logical Processor (P) = Driver:</strong> A logical software scheduling context inside the runtime that manages a queue of packages. (Important: Do not confuse P with a physical CPU processor chip on your motherboard!).</p><p><strong>OS Thread (M) = Truck:</strong> The heavy vehicle provided by the OS kernel that actually drives down the physical road (CPU core).</p><pre>                         Delivery Depot (Go Runtime)<br><br>              Package (G1)   Package (G2)   Package (G3)   Package (G4)<br>                                   │<br>                                   ▼<br>              +------------------------------------------+<br>              |           Driver / Processor (P1)        |<br>              |     Local Delivery Queue: [G2, G3, G4]   |<br>              +------------------------------------------+<br>                                   │<br>                                   ▼<br>                         Truck / OS Thread (M1)<br>                                   │<br>                                   ▼<br>                          CPU Core (Physical Road)</pre><p><strong>Goal of the System:</strong> Keep all Drivers (P) and Trucks (M) moving packages (G) continuously so the Road (CPU Core) is never empty!</p><h3>5. Deep Dive: The G-M-P Architecture</h3><p>The Go scheduler consists of three core components:</p><p><strong>G (Goroutine):</strong> Contains the execution stack, instruction pointer, and state (runnable, running, waiting).</p><p><strong>M (Machine):</strong> An OS thread managed by the kernel.</p><p><strong>P (Processor Context):</strong> A logical software processor created inside the Go runtime context. <strong>P is NOT a hardware CPU processor.</strong> Think of P as a token or resource needed to execute Go code. Without attaching to a P, an OS thread (M) cannot run goroutines.</p><h3>Visualizing GOMAXPROCS = 4</h3><p>If you have 4 CPU cores, the Go runtime spins up 4 Logical Processor contexts (P1 to P4):</p><pre>          P1        P2        P3        P4      (Logical Software Processors)<br>         / | \     / | \     / | \     / | \<br>         G G G     G G G     G G G     G G G    (Goroutines)<br>          |         |         |         |<br>          M1        M2        M3        M4      (OS Threads)<br>          |         |         |         |<br>         CPU       CPU       CPU       CPU      (Physical Hardware CPU Cores)</pre><h3>Local Queues vs. The Global Queue</h3><p>Where do the 100,000 packages (Goroutines) go?</p><p><strong>Local Run Queue (Bounded):</strong> Each Logical Processor (P) has a local queue that holds up to <strong>256 Goroutines</strong>.</p><p><strong>Global Run Queue (Unbounded):</strong> When a local queue overflows, half of its goroutines are moved to a shared Global Queue.</p><pre>Global Queue: [ G101, G102, G103 ... ]  (Overflow storage)<br>                   │<br>    ┌──────────────┴──────────────┐<br>    ▼                             ▼<br>+---------------------+     +---------------------+<br>|         P1          |     |         P2          |<br>| Local Queue (&lt;=256) |     | Local Queue (&lt;=256) |<br>+---------------------+     +---------------------+</pre><h3>6. How Go Keeps the CPU Working (Solving Obstacles)</h3><p>What happens when things go wrong during execution? Go uses three smart techniques to prevent CPU idling.</p><h3>1. Waiting for Network / Database (Non-blocking I/O)</h3><p><strong>Scenario:</strong> Package G1 needs data from a remote database. It will take 2 seconds to arrive.</p><p><strong>Traditional Problem:</strong> The Truck (M1) sits stopped on the side of the road waiting for 2 seconds. The CPU core goes idle!</p><p><strong>Go Solution:</strong> Driver (P1) sets G1 aside in a waiting area (called the <strong>Netpoller</strong>) and instantly loads package G2 into Truck M1.</p><pre>BEFORE I/O:<br>P1 ──► M1 ──► G1 (Waiting for Database)<br><br><br>AFTER I/O ATTEMPT:<br>G1 moved to Netpoller parking lot.<br>P1 immediately assigns G2 to keep Truck M1 moving.<br><br>P1 ──► M1 ──► G2 (Running on CPU)</pre><p>When the database finally responds, G1 is placed back into a Driver’s queue to finish its delivery.</p><h3>2. Slow Disk Read or System Call (Blocking I/O)</h3><p><strong>Scenario:</strong> Package G1 requires reading a file directly from local disk, forcing the Truck (M1) to freeze inside an OS kernel operation.</p><p><strong>Go Solution:</strong> Driver (P1) drops off Truck M1 and grabs a spare backup Truck (M2) to continue delivering the remaining packages!</p><pre>BEFORE BLOCKING:<br>P1 ──► M1 ──► G1 (Executes blocking OS disk call)<br><br>DRIVER DETACHMENT:<br>P1 leaves blocked M1 behind and grabs backup Truck M2.<br><br>M1 ──► G1 (Blocked in OS Kernel)<br><br>P1 ──► M2 ──► G2 (Continuing deliveries without stopping!)</pre><h3>3. Work Stealing (Preventing Idle Drivers)</h3><p><strong>Scenario:</strong> Driver P1 finishes all packages in its local queue, but Driver P2 still has a huge backlog.</p><pre>P1 Local Queue: [ Empty ]<br>P2 Local Queue: [ G4, G5, G6, G7 ]</pre><p><strong>WORK STEALING ACTION:</strong></p><p>P1 looks at P2 and steals <strong>HALF</strong> of P2’s packages!</p><pre>P1 Local Queue: [ G6, G7 ]<br>P2 Local Queue: [ G4, G5 ]</pre><p>By balancing packages across drivers, no CPU core sits idle while work remains in the system.</p><h3>7. Controlling Execution with GOMAXPROCS</h3><p>GOMAXPROCS determines how many Logical Processors (P) exist in your runtime:</p><pre>8 Physical CPU Cores<br>        │<br>        ▼<br>  GOMAXPROCS = 8<br>        │<br>        ▼<br>   8 Logical Processors (P)<br>        │<br>        ▼<br>Thousands of Goroutines (G)<br>        │<br>        ▼<br>Only 8 Goroutines execute Go code simultaneously in parallel</pre><p><strong>Takeaway:</strong> GOMAXPROCS doesn’t limit how many goroutines you can create. It limits how many logical processors (P) exist to execute Go code in true hardware parallelism at any given microsecond.</p><h3>8. Summary &amp; Key Takeaways</h3><h3>Choosing the Right Model:</h3><ul><li><strong>Use Processes</strong> for heavy CPU-bound tasks in interpreted languages (Python ML, video processing).</li><li><strong>Use Threads</strong> for native shared-memory parallel processing (C++, Rust).</li><li><strong>Use Async/Await</strong> for I/O-bound tasks in Node.js or Python.</li><li><strong>Use Goroutines</strong> for high-concurrency microservices, network servers, and clean synchronous syntax.</li></ul><h3>The G-M-P Model:</h3><p><strong>G (Goroutine):</strong><br>Ultra-lightweight task starting at ~2 KB.</p><p><strong>P (Processor):</strong><br>Software logical processor context managing local queues (up to 256 tasks). Not to be confused with a physical CPU chip.</p><p><strong>M (OS Thread):</strong><br>OS kernel thread carrying out execution on physical CPU cores.</p><h3>Zero Wasted CPU:</h3><p>Through <strong>Netpoller parking</strong>, <strong>Thread detachment</strong>, and <strong>Work Stealing</strong>, Go makes sure every available CPU core is constantly working.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d93ce2858f80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Concurrency in Temporal: Workers, Queues, and Thread Pools]]></title>
            <link>https://towardsdev.com/understanding-concurrency-in-temporal-workers-queues-and-thread-pools-9b6e659bf893?source=rss-3ecd9ab4ad4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b6e659bf893</guid>
            <category><![CDATA[temporal]]></category>
            <dc:creator><![CDATA[Rajendra Bisoi]]></dc:creator>
            <pubDate>Sat, 11 Jul 2026 21:06:00 GMT</pubDate>
            <atom:updated>2026-07-11T21:06:00.765Z</atom:updated>
            <content:encoded><![CDATA[<p>When I first started using Temporal, one question kept bothering me:</p><blockquote><strong><em>If Temporal already provides </em></strong><strong><em>max_concurrent_activities, why would I ever need </em></strong><strong><em>ThreadPoolExecutor, </em></strong><strong><em>ExecutorService, or Goroutines?</em></strong></blockquote><p>The answer is that <strong>they solve different layers of concurrency</strong>, not the same problem.</p><p>Once you understand these layers, designing scalable distributed systems becomes much easier.</p><h3>Layer 1: Distributed Concurrency (Temporal Task Queues)</h3><p>Suppose we’re building an RSS ingestion pipeline.</p><pre>                Workflow<br>                    │<br>                    ▼<br>      +--------------------------+<br>      |  Fetch Queue             |<br>      |  Parse Queue             |<br>      |  Summarize Queue         |<br>      +--------------------------+</pre><p>Instead of putting every activity into a single queue, each activity type has its own queue.</p><p>For example:</p><ul><li>Fetch Activity → Fetch Queue</li><li>Parse Activity → Parse Queue</li><li>Summarize Activity → Summarize Queue</li></ul><p>This gives us <strong>independent scaling</strong>.</p><p>If downloading RSS feeds becomes the bottleneck, we simply add more Fetch Workers without increasing Parse or Summarize workers.</p><h3>Layer 2: Horizontal Scaling with Multiple Workers</h3><p>Each queue can have multiple Temporal workers consuming from it.</p><pre>              Fetch Queue<br>                   │<br>      ┌────────────┼────────────┐<br>      ▼            ▼            ▼<br> Fetch Worker1  Fetch Worker2  Fetch Worker3</pre><p>Every worker is an independent process (or container).</p><p>Temporal automatically distributes activities among all available workers.</p><p>If traffic doubles, we don’t increase thread count forever.</p><p>Instead we simply deploy more workers.</p><p>For example:</p><pre>docker compose up --scale fetch-worker=10</pre><p>Now ten worker processes consume from the same queue.</p><p>This is called <strong>horizontal scaling</strong>.</p><h3>Layer 3: Worker-Level Concurrency</h3><p>Now comes the important configuration.</p><pre>Worker(<br>    task_queue=FETCH_QUEUE,<br>    activities=[fetch_url],<br>    max_concurrent_activities=20,<br>)</pre><p>This tells Temporal:</p><blockquote><em>This worker can execute at most </em><strong><em>20 activities simultaneously</em></strong><em>.</em></blockquote><p>Suppose we have</p><pre>5 Fetch Workers</pre><p>Each configured with</p><pre>max_concurrent_activities = 20</pre><p>Then</p><pre>5 Workers × 20 Activities<br>=<br>100 Concurrent Activities</pre><p>If 1 million activities are waiting,</p><p>only 100 execute simultaneously.</p><p>The remaining activities safely wait inside the Temporal task queue.</p><p>As soon as one finishes,</p><p>Temporal immediately schedules the next waiting activity.</p><p>This bounded concurrency keeps the worker stable and prevents resource exhaustion.</p><h3>Layer 4: Intra-Activity Concurrency (Optional)</h3><p>Now suppose one activity itself has multiple independent tasks.</p><p>For example,</p><pre>Summarize Activity<br>↓<br>100 Articles<br>↓<br>Generate Summary</pre><p>Each article is independent.</p><p>Now it makes sense to introduce another layer of concurrency.</p><p>For example:</p><ul><li>Python ThreadPoolExecutor</li><li>Java ExecutorService</li><li>Go Goroutines</li><li>ProcessPoolExecutor (for CPU-heavy work)</li></ul><p>Example:</p><pre>def summarize_activity(records):<br>    with ThreadPoolExecutor(max_workers=8) as pool:<br>        pool.map(generate_summary, records)</pre><p>Notice what’s happening here.</p><p>Temporal controls <strong>how many activities execute simultaneously</strong>.</p><p>The thread pool controls <strong>how work inside one activity is parallelized</strong>.</p><p>These are two completely different responsibilities.</p><h3>When NOT to use ThreadPoolExecutor</h3><p>Suppose your activity is simply</p><pre>fetch_https://medium.com/url(url)</pre><p>This activity downloads <strong>one</strong> RSS feed.</p><p>Using another thread pool inside it provides little value.</p><p>Even worse,</p><p>Suppose</p><pre>max_concurrent_activities = 20</pre><p>and inside every activity you create</p><pre>ThreadPoolExecutor(100)</pre><p>Now your machine may suddenly create</p><pre>20 Activities<br>×<br>100 Threads<br>=<br>2000 Threads</pre><p>You’ve completely defeated the purpose of limiting concurrency.</p><p>This often results in:</p><ul><li>High memory consumption</li><li>Excessive context switching</li><li>Database connection exhaustion</li><li>Lower throughput instead of higher throughput</li></ul><p>In this case, Temporal’s activity concurrency is sufficient.</p><h3>When SHOULD you use ThreadPoolExecutor?</h3><p>Use another concurrency mechanism only when <strong>one activity itself contains independent parallelizable work.</strong></p><p>Examples include:</p><ul><li>Processing 500 images</li><li>Generating embeddings for hundreds of documents</li><li>Running OCR on multiple pages</li><li>Compressing many files</li><li>CPU-heavy data transformations</li></ul><p>Here the activity is performing substantial work internally, so introducing another layer of parallelism is justified.</p><h3>Three Layers of Concurrency</h3><p>A useful mental model is:</p><pre>Temporal<br>                       │<br>        Decides which activity runs<br>                       │<br>                       ▼<br>             Multiple Worker Processes<br>                       │<br>      max_concurrent_activities controls<br>      activities per worker<br>                       │<br>                       ▼<br>              Activity Starts<br>                       │<br>      ┌────────────────┴──────────────┐<br>      │                               │<br> Simple Activity               Complex Activity<br>      │                               │<br> Execute Directly          ThreadPoolExecutor /<br>                           ExecutorService /<br>                           Goroutines /<br>                           ProcessPoolExecutor</pre><h3>Production Systems</h3><p>Large-scale systems rarely rely on a single concurrency mechanism.</p><p>Instead, they combine multiple layers:</p><ul><li><strong>Task Queues (Temporal, Kafka, RabbitMQ, SQS)</strong> store millions of pending jobs.</li><li><strong>Multiple Worker Processes</strong> consume jobs horizontally.</li><li><strong>max_concurrent_activities</strong> limits concurrent execution inside each worker.</li><li><strong>Thread pools, goroutines, or executors</strong> are introduced only when an individual activity contains additional parallelizable work.</li></ul><p>Each layer solves a different problem.</p><h3>Key Takeaways</h3><p>✅ Separate activity types into dedicated task queues.</p><p>✅ Scale by adding more workers instead of creating unlimited threads.</p><p>✅ Use max_concurrent_activities to control how many activities each worker executes simultaneously.</p><p>✅ Introduce ThreadPoolExecutor, ExecutorService, or Goroutines only when a <strong>single activity</strong> contains multiple independent subtasks.</p><p>✅ Don’t stack thread pools unnecessarily. Let Temporal orchestrate activity-level concurrency and use lower-level concurrency primitives only where they genuinely improve throughput.</p><p>Understanding these layers is what separates writing concurrent code from designing scalable distributed systems. Once each layer has a clear responsibility, your system remains efficient, predictable, and easy to scale horizontally.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b6e659bf893" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/understanding-concurrency-in-temporal-workers-queues-and-thread-pools-9b6e659bf893">Understanding Concurrency in Temporal: Workers, Queues, and Thread Pools</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving the N+1 Query Problem: A Practical Thumb Rule]]></title>
            <link>https://coderraj07.medium.com/solving-the-n-1-query-problem-a-practical-thumb-rule-0e8a7ec51a64?source=rss-3ecd9ab4ad4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e8a7ec51a64</guid>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Rajendra Bisoi]]></dc:creator>
            <pubDate>Thu, 09 Jul 2026 08:04:10 GMT</pubDate>
            <atom:updated>2026-07-09T08:04:10.871Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most common performance issues in backend applications is the <strong>N+1 Query Problem</strong>.</p><p>Many developers think the solution is always “use JOINs.”</p><p>That’s only partially true.</p><p>Modern ORMs like <strong>SQLAlchemy</strong>, <strong>Django ORM</strong>, and <strong>Hibernate</strong> actually provide <strong>two different strategies</strong>, and choosing the right one depends on the relationship between your entities.</p><h3>Rule of Thumb</h3><p>Whenever you encounter an N+1 problem, remember this simple rule:</p><blockquote><strong><em>Fetch parents once → Fetch children in batches → Assemble in memory</em></strong></blockquote><p>Then choose the loading strategy based on the relationship:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/324/1*znz8sJ-yhD-e4fSx3Ls1IQ.png" /></figure><p>This hybrid approach eliminates the N+1 problem while avoiding row explosion caused by large JOINs.</p><p>Let’s understand why.</p><h3>What is the N+1 Query Problem?</h3><p>Suppose we’re building an Order API.</p><p>Each order contains:</p><ul><li>Customer</li><li>Product</li><li>Shipping Details</li><li>Order Logs</li></ul><p>Our models look like this:</p><pre>Order<br> ├── User (Many-to-One)<br> ├── Product (Many-to-One)<br> ├── Logistics (One-to-One)<br> └── Logs (One-to-Many)</pre><p>A naïve implementation might look like this:</p><pre>orders = order_repository.get_recent_orders(limit=10)<br>response = []<br>for order in orders:<br>    user = user_repository.get(order.user_id)<br>    product = product_repository.get(order.product_id)<br>    logistics = logistics_repository.get_by_order(order.id)<br>    logs = log_repository.get_by_order(order.id)<br>    response.append({<br>        &quot;order&quot;: order,<br>        &quot;user&quot;: user,<br>        &quot;product&quot;: product,<br>        &quot;logistics&quot;: logistics,<br>        &quot;logs&quot;: logs<br>    })</pre><p>For just <strong>10 orders</strong>, this executes:</p><pre>1 Query  -&gt; Orders<br>10 Queries -&gt; Users<br>10 Queries -&gt; Products<br>10 Queries -&gt; Logistics<br>10 Queries -&gt; Logs<br>-------------------------<br>Total = 41 Queries</pre><p>Every query incurs:</p><ul><li>Network latency</li><li>Connection acquisition</li><li>SQL parsing</li><li>Execution planning</li><li>ORM object creation</li></ul><p>The database isn’t slow.</p><p>The application is repeatedly asking it the same kind of question.</p><p>This is called the <strong>N+1 Query Problem</strong>.</p><h3>The Thumb Rule</h3><p>Instead of memorizing “Always use JOINs,” remember these two rules.</p><h3>Rule 1</h3><blockquote><strong><em>Fetch parents once → Fetch children in batches → Assemble in memory</em></strong></blockquote><p>This immediately eliminates unnecessary database round trips.</p><h3>Rule 2</h3><p>Choose the loading strategy based on the relationship type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*_vpRZQzq7aG1ufBuCbHz1g.png" /></figure><p>Why?</p><p>Because JOINs are excellent when every parent has exactly one related record.</p><p>But when a parent has multiple child records, JOINs duplicate the parent data repeatedly, increasing network transfer and making pagination difficult.</p><h3>Case 1 — Many-to-One (Use JOIN)</h3><p>Every order belongs to exactly one customer.</p><pre>Order<br>   │<br>   ▼<br> User</pre><p>Using SQLAlchemy:</p><pre>from sqlalchemy.orm import joinedload<br><br>orders = (<br>    session.query(Order)<br>    .options(joinedload(Order.user))<br>    .all()<br>)</pre><p>Generated SQL:</p><pre>SELECT *<br>FROM orders<br>JOIN users<br>ON orders.user_id = users.id;</pre><p>Only one query.</p><p>No duplicated rows.</p><p>Perfect.</p><h3>Case 2 — One-to-One (Use JOIN)</h3><p>Suppose every order has one shipping record.</p><pre>Order<br>   │<br>   ▼<br>Logistics</pre><p>Again:</p><pre>orders = (<br>    session.query(Order)<br>    .options(joinedload(Order.logistics))<br>    .all()<br>)</pre><p>Generated SQL:</p><pre>SELECT *<br>FROM orders<br>LEFT JOIN logistics<br>ON orders.id = logistics.order_id;</pre><p>Still one query.</p><p>Still efficient.</p><h3>Case 3 — One-to-Many (Use Batch Fetch)</h3><p>Now suppose an order contains many logs.</p><pre>Order<br>   │<br>   ▼<br>OrderLogs</pre><p>Don’t JOIN.</p><p>Use batch loading.</p><pre>from sqlalchemy.orm import selectinload<br>orders = (<br>    session.query(Order)<br>    .options(selectinload(Order.logs))<br>    .all()<br>)</pre><p>SQLAlchemy executes:</p><pre>SELECT *<br>FROM orders;</pre><p>Then</p><pre>SELECT *<br>FROM order_logs<br>WHERE order_id IN (1,2,3,4,5...);</pre><p>Only two queries.</p><p>No row explosion.</p><h3>What Happens Internally?</h3><p>Suppose the second query returns</p><pre>Order 1 -&gt; Log A<br>Order 1 -&gt; Log B<br>Order 2 -&gt; Log C</pre><p>SQLAlchemy builds an in-memory lookup:</p><pre>{<br>    1: [LogA, LogB],<br>    2: [LogC]<br>}</pre><p>Then automatically attaches them.</p><pre>order.logs</pre><p>works exactly as if each log had been queried individually.</p><p>No additional database calls.</p><h3>Case 4 — Many-to-Many (Use Batch Fetch)</h3><p>Suppose</p><pre>Student<br>    │<br>    ▼<br>Enrollment<br>    │<br>    ▼<br>Course</pre><p>One student may have many courses.</p><p>One course may have many students.</p><p>Instead of one massive JOIN:</p><pre>students = (<br>    session.query(Student)<br>    .options(selectinload(Student.courses))<br>    .all()<br>)</pre><p>SQLAlchemy performs:</p><pre>SELECT *<br>FROM students;<br><br>SELECT *<br>FROM enrollments<br>WHERE student_id IN (...);<br><br>SELECT *<br>FROM courses<br>WHERE id IN (...);</pre><p>Efficient.</p><p>Scalable.</p><p>Easy to paginate.</p><h3>The Hybrid Strategy (Recommended)</h3><p>Most production APIs combine both strategies.</p><pre>from sqlalchemy.orm import joinedload, selectinload<br><br>orders = (<br>    session.query(Order)<br>    .options(<br>        joinedload(Order.user),<br>        joinedload(Order.product),<br>        joinedload(Order.logistics),<br>        selectinload(Order.logs),<br>        selectinload(Order.attachments),<br>        selectinload(Order.payments)<br>    )<br>    .all()<br>)</pre><p>Conceptually this becomes:</p><pre>Query 1<br>Orders<br>JOIN Users<br>JOIN Products<br>JOIN Logistics<br>--------------------<br>Query 2<br>Logs<br>WHERE order_id IN (...)<br>--------------------<br>Query 3<br>Payments<br>WHERE order_id IN (...)<br>--------------------<br>Query 4<br>Attachments<br>WHERE order_id IN (...)</pre><p>Few queries.</p><p>No N+1.</p><p>No row explosion.</p><p>Correct pagination.</p><h3>Why Not JOIN Everything?</h3><p>Imagine</p><pre>100 Orders<br>Each has<br>100 Logs</pre><p>A JOIN returns</p><pre>100 × 100</pre><pre>=</pre><pre>10,000 rows</pre><p>Every row repeats</p><ul><li>Order</li><li>User</li><li>Product</li></ul><p>100 times.</p><p>Most of the transferred data is duplicated.</p><p>Batch fetching avoids this by transferring parent rows once and child rows once, then linking them efficiently in memory.</p><h3>Final Takeaway</h3><p>Whenever you’re designing a query, don’t start by asking:</p><blockquote><strong><em>“Should I use a JOIN?”</em></strong></blockquote><p>Instead ask:</p><blockquote><strong><em>“Can I fetch the parents once, batch-fetch the children, and assemble everything in memory?”</em></strong></blockquote><p>Then apply the relationship rule:</p><ul><li>✅ <strong>Many-to-One</strong> → JOIN</li><li>✅ <strong>One-to-One</strong> → JOIN</li><li>✅ <strong>One-to-Many</strong> → Batch Fetch</li><li>✅ <strong>Many-to-Many</strong> → Batch Fetch</li></ul><p>Following these two simple rules helps you avoid both major performance pitfalls:</p><ul><li>❌ N+1 Queries</li><li>❌ Row Explosion</li></ul><p>This is the pattern used by modern ORMs like SQLAlchemy, Django ORM, Hibernate/JPA, and many high-scale production systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e8a7ec51a64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Temporal Workers to Process 10,000 Requests in 7 Minutes]]></title>
            <link>https://towardsdev.com/scaling-temporal-workers-to-process-10-000-requests-in-7-minutes-b2c29c22b0cb?source=rss-3ecd9ab4ad4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2c29c22b0cb</guid>
            <category><![CDATA[temporal]]></category>
            <dc:creator><![CDATA[Rajendra Bisoi]]></dc:creator>
            <pubDate>Wed, 08 Jul 2026 20:36:01 GMT</pubDate>
            <atom:updated>2026-07-08T20:36:01.164Z</atom:updated>
            <content:encoded><![CDATA[<h3>Problem Statement</h3><p>Suppose we need to process <strong>10,000 RSS/XML requests within 7 minutes</strong>.</p><p>Each request goes through three activities:</p><ol><li>Fetch RSS/XML</li><li>Parse XML</li><li>Generate Summary</li></ol><p>The challenge is determining:</p><ul><li>How many workers are needed?</li><li>How should workers be organized?</li><li>When should we use async, threads, or processes?</li><li>How many instances are required?</li><li>How can the workflow scale without hitting Temporal limitations?</li></ul><h3><strong>Solution</strong></h3><p><strong>Temporal Architecture</strong></p><p>Temporal allows:</p><ul><li>Multiple Task Queues</li><li>Multiple Workers per queue</li><li>Multiple Worker instances for horizontal scaling</li></ul><p>Example:</p><pre>Fetch Queue      -&gt; 5 workers<br>Parse Queue      -&gt; 5 workers<br>Summary Queue    -&gt; 5 workers</pre><h3>CPU vs IO</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*xCiawwwYCPknqXDAbr1-Tg.png" /></figure><p>So:</p><ul><li>IO-bound tasks → asyncio (await, asyncio.gather)</li><li>Blocking synchronous libraries → Threads</li><li>Heavy CPU-bound tasks → Processes</li></ul><h3>Threads</h3><p>If the summarizer uses a blocking library:</p><pre>await asyncio.to_thread(summarize)</pre><p>A worker can execute many thread jobs concurrently.</p><p>Python’s default thread pool size is approximately:</p><pre>min(32, os.cpu_count() + 4)</pre><p>(or it can be configured manually.)</p><h3>Worker Deployment</h3><p>A single machine can run multiple workers.</p><p>Example:</p><pre>Instance 1<br> ├── Fetch Worker<br> ├── Parser Worker<br> └── Summary Worker<br><br>Instance 2<br> ├── Fetch Worker<br> ├── Parser Worker<br> └── Summary Worker</pre><p>or</p><pre>Instance 1<br> └── Fetch Workers<br><br>Instance 2<br> └── Parser Workers<br><br>Instance 3<br> └── Summary Workers</pre><p>Additional instances are added when one machine cannot provide enough CPU, memory, or network throughput.</p><h3>Throughput Calculation</h3><p>Requirement:</p><ul><li>Process <strong>10,000 requests</strong></li><li>Within <strong>7 minutes</strong></li></ul><pre>7 minutes = 420 seconds<br><br>10000 / 420<br>≈ 23.8 req/sec<br>≈ 24 req/sec</pre><p>If each fetch or parse takes <strong>4 seconds</strong> on average:</p><p>Using Little’s Law:</p><pre>Concurrency<br>= Arrival Rate × Service Time<br>= 24 × 4<br>= 96</pre><p>So approximately <strong>96 concurrent fetches</strong> are required.</p><h3>Worker Count</h3><p>If one worker can handle:</p><pre>20 concurrent fetches</pre><p>Then:</p><pre>96 / 20<br>≈ 4.8</pre><p>Provisioning <strong>5 workers</strong> provides approximately <strong>100 concurrent fetches</strong>, satisfying the required concurrency.</p><h3>CPU Cores</h3><p>For CPU-bound activities:</p><pre>Worker 1 -&gt; CPU intensive<br>Worker 2 -&gt; CPU intensive<br>Worker 3 -&gt; CPU intensive<br>Worker 4 -&gt; CPU intensive</pre><p>Then:</p><pre>4 workers<br>≈ 4 CPU cores</pre><p>For IO-bound workers (HTTP requests, databases, S3, etc.), one CPU core is not required per concurrent job because workers spend most of their time waiting for I/O. A few CPU cores can support hundreds or even thousands of concurrent async operations depending on the workload.</p><h3>Final Architecture</h3><pre>Temporal<br><br>                  ┌────────────────────┐<br>                  │     Main Workflow  │<br>                  └─────────┬──────────┘<br>                            │<br>               ┌────────────┴────────────┐<br>               │                         │<br>         Child Workflow 1          Child Workflow 2<br>               │                         │<br>        ┌──────┼────────┐         ┌──────┼────────┐<br>        │      │        │         │      │        │<br>       Fetch   Parse   Summary   Fetch   Parse   Summary<br>      Queue   Queue    Queue     Queue   Queue    Queue<br>        │       │        │         │       │        │<br>     Async   Async   Threads    Async   Async   Threads</pre><p>Fetch Queue</p><ul><li>5 async workers</li><li>20 concurrent activities each</li><li>≈100 concurrent fetches</li></ul><p>Parser Queue</p><ul><li>5 async workers</li><li>20 concurrent activities each</li><li>≈100 concurrent parses</li></ul><p>Summary Queue</p><ul><li>5 workers</li><li>Blocking summarizer executed using asyncio.to_thread()</li><li>Thread pool ≈32 threads per worker</li><li>≈160 concurrent summaries</li></ul><p>Deploy workers across one or more instances based on CPU, memory, and network usage, and scale instances horizontally as resource utilization increases.</p><h3>Improvements for Production</h3><h3>1. Child Workflows</h3><p>Instead of processing all 10,000 requests in a single workflow, split them into batches using Child Workflows.</p><p>Example:</p><pre>Main Workflow<br>├── Child Workflow (1-1000)<br>├── Child Workflow (1001-2000)<br>├── Child Workflow (2001-3000)<br>...<br>├── Child Workflow (9001-10000)</pre><p>Benefits:</p><ul><li>Better parallelism</li><li>Smaller workflow histories</li><li>Easier retries</li><li>Better fault isolation</li></ul><h3>2. Continue-As-New</h3><p>Long-running workflows continuously accumulate history events.</p><p>Use <strong>Continue-As-New</strong> after processing a batch to start a fresh workflow execution while preserving progress.</p><p>Benefits:</p><ul><li>Prevents oversized workflow histories</li><li>Faster workflow replay</li><li>Lower Temporal server overhead</li><li>Improved long-running workflow performance</li></ul><h3>3. Store Large XML Payloads in Amazon S3</h3><p>RSS/XML documents can become large, and sending entire payloads through Temporal increases workflow history size.</p><p>Instead:</p><ol><li>Fetch the XML</li><li>Upload the XML to Amazon S3</li><li>Pass only the S3 object key or URL through the workflow</li><li>Download the XML inside activities when required</li></ol><p>Benefits:</p><ul><li>Keeps Temporal payloads small</li><li>Reduces workflow history growth</li><li>Avoids payload size limitations</li><li>Improves replay performance</li><li>Supports much larger datasets efficiently</li></ul><h3>Summary</h3><p>By combining:</p><ul><li>Multiple Task Queues</li><li>Dedicated Workers</li><li>Async IO for network-bound activities</li><li>Threads for blocking libraries</li><li>Processes for CPU-intensive work</li><li>Child Workflows</li><li>Continue-As-New</li><li>Amazon S3 for large payload storage</li></ul><p>Temporal workflows can efficiently scale to process <strong>10,000+ requests within minutes</strong> while remaining reliable, fault-tolerant, and production-ready.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2c29c22b0cb" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/scaling-temporal-workers-to-process-10-000-requests-in-7-minutes-b2c29c22b0cb">Scaling Temporal Workers to Process 10,000 Requests in 7 Minutes</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaling Databases: Replication, Sharding & Partitioning Explained]]></title>
            <link>https://towardsdev.com/scaling-databases-replication-sharding-partitioning-explained-cf6e4950cf16?source=rss-3ecd9ab4ad4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf6e4950cf16</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Rajendra Bisoi]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 21:21:00 GMT</pubDate>
            <atom:updated>2026-07-04T21:21:00.801Z</atom:updated>
            <content:encoded><![CDATA[<h3>Scaling Databases Without Losing Sleep: Replication, Sharding &amp; Partitioning Explained</h3><p>When your application starts growing, adding more CPU or RAM isn’t always enough.</p><p>Soon you’ll hear terms like <strong>Replication</strong>, <strong>Sharding</strong>, and <strong>Partitioning</strong>.</p><p>Many engineers confuse these concepts — even experienced ones.</p><p>Let’s break them down with real-world examples, diagrams, and production-ready SQL.</p><h3>1. Replication</h3><h3>What is Replication?</h3><p>Replication means:</p><blockquote><strong><em>Keeping multiple copies of the same database.</em></strong></blockquote><p>Every replica contains identical data.</p><pre>               Write<br>                 │<br>                 ▼<br>            Primary DB<br>           /     |      \<br>          /      |       \<br>    Replica A Replica B Replica C</pre><p>Users can read from replicas while writes go to the primary.</p><h3>Real-Life Example</h3><p>Think of <strong>Netflix</strong>.</p><p>Millions of users watch movies simultaneously.</p><p>If every user queried one database…</p><pre>Movie Details<br>Continue Watching<br>Recommendations<br>History</pre><p>…the database would become overloaded.</p><p>Instead:</p><pre>Primary<br>   │<br> ┌─┴──────────────┐<br> │                |<br>Replica          Replica</pre><p>Every movie lookup comes from replicas.</p><p>Only profile updates go to primary.</p><h3>Another Example</h3><p>Instagram</p><pre>Opening Profile<br>Scrolling Feed<br>Viewing Comments</pre><p>These are reads.</p><p>Changing password</p><p>Posting photo</p><p>Following someone</p><p>These are writes.</p><p>Reads → Replica</p><p>Writes → Primary</p><h3>Benefits</h3><p>✅ Handles massive read traffic</p><p>✅ High availability</p><p>✅ Backups become safer</p><p>✅ Faster analytics</p><h3>When to Use Replication</h3><p>Use replication if</p><ul><li>90%+ workload is reads</li><li>Heavy dashboards</li><li>Analytics</li><li>Public APIs</li><li>Search pages</li><li>Product catalogs</li></ul><p>Example</p><p>E-commerce</p><pre>Search products<br><br>View products<br><br>Read reviews</pre><p>These are read-heavy.</p><h3>When NOT to Use Replication</h3><p>Replication doesn’t increase write capacity.</p><p>If your bottleneck is</p><pre>INSERT<br><br>UPDATE<br><br>DELETE</pre><p>Replication won’t help.</p><p>Writes still hit one machine.</p><h3>PostgreSQL Streaming Replication (Concept)</h3><p>Primary</p><pre># postgresql.conf<br><br>wal_level = replica<br>max_wal_senders = 10<br>hot_standby = on</pre><p>Allow replica</p><pre># pg_hba.conf<br><br>host replication replicator 0.0.0.0/0 md5</pre><p>Create replication user</p><pre>CREATE ROLE replicator<br>LOGIN<br>REPLICATION<br>PASSWORD &#39;secret&#39;;</pre><p>Take base backup</p><pre>pg_basebackup \<br>-h primary-ip \<br>-D /var/lib/postgresql/data \<br>-U replicator \<br>-P \<br>-R</pre><p>Start PostgreSQL.</p><p>Replica begins streaming WAL logs automatically.</p><h3>Application Example</h3><p>Using Node.js</p><pre>const writePool = new Pool({<br>    host: &quot;primary-db&quot;<br>})<br><br>const readPool = new Pool({<br>    host: &quot;replica-db&quot;<br>})<br><br>// Reads<br><br>await readPool.query(<br>&quot;SELECT * FROM products&quot;<br>)<br><br>// Writes<br><br>await writePool.query(<br>&quot;INSERT INTO orders(...)&quot;<br>)</pre><h3>TemporaReplication Process</h3><p>When an update happens on the <strong>primary database</strong>, it is <strong>not copied instantly in the strict sense</strong>. Instead, the primary writes the change to its <strong>Write-Ahead Log (WAL)</strong> (in PostgreSQL), and replicas continuously replay those WAL records.</p><p>The timing depends on the replication mode.</p><h3>1. Asynchronous Replication (Most Common)</h3><pre>          Client<br>             │<br>             ▼<br>        Primary DB<br>             │<br>     Update committed ✔<br>             │<br>      WAL generated<br>             │<br>      (network transfer)<br>             │<br>     Read Replica<br>      Replays WAL</pre><p>Timeline:</p><pre>10:00:00.100  UPDATE users SET name=&#39;Raj&#39;;<br>10:00:00.105  Transaction COMMITTED on primary<br>10:00:00.120  WAL shipped<br>10:00:00.140  Replica replays WAL</pre><p>The primary <strong>does not wait</strong> for replicas.</p><p>The user gets success immediately after the primary commits.</p><p>Replicas may lag by:</p><ul><li>a few milliseconds</li><li>hundreds of milliseconds</li><li>seconds (under heavy load)</li><li>even minutes if replication falls behind</li></ul><p>This delay is called <strong>replication lag</strong>.</p><h3>Example Problem</h3><p>Imagine Amazon.</p><p>You update your delivery address.</p><p>Immediately afterwards your application reads from a replica.</p><pre>Update Address<br>        |<br>        ▼<br>    Primary ✔<br><br>Replica<br>(old address)</pre><p>You’ll briefly see the <strong>old address</strong> until the replica catches up.</p><p>This is called <strong>eventual consistency</strong>.</p><h3>2. Synchronous Replication</h3><pre>Client<br>   │<br>   ▼<br>Primary<br>   │<br>   ├────────► Replica<br>   │          WAL written<br>   │<br>Wait...<br>   │<br>Replica ACK<br>   │<br>Commit ✔</pre><p>Here the primary <strong>waits</strong> until one (or more) replicas acknowledge receiving the WAL before reporting success to the client.</p><p>Advantages:</p><ul><li>Stronger consistency</li><li>Lower chance of data loss during failover</li></ul><p>Disadvantages:</p><ul><li>Higher write latency</li><li>Slower if a replica is slow or unavailable</li></ul><h3>PostgreSQL Flow</h3><p>For an update like:</p><pre>UPDATE users<br>SET balance = balance - 500<br>WHERE id = 1;</pre><p>PostgreSQL performs:</p><ol><li>Execute the update.</li><li>Write the change to the <strong>WAL</strong>.</li><li>Commit the transaction.</li><li>Send the WAL records to replicas.</li><li>Replicas replay the WAL and apply the same update.</li></ol><p>The replica is <strong>replaying the transaction log</strong>, not receiving SQL statements.</p><h3>Which One Is Used in Production?</h3><p>Most production systems use <strong>asynchronous replication</strong> because it provides much better write performance.</p><p>Examples include:</p><ul><li>Social media feeds</li><li>E-commerce product catalogs</li><li>News websites</li><li>Most SaaS applications</li></ul><p>Synchronous replication is typically reserved for systems where losing even a single committed transaction is unacceptable, such as:</p><ul><li>Banking systems</li><li>Financial trading platforms</li><li>Critical payment infrastructure</li></ul><h3>Key takeaway</h3><p>A common misconception is that <strong>every write is immediately copied to replicas</strong>. In reality, with asynchronous replication (the default in many systems), the primary commits the transaction first and <strong>replicas catch up shortly afterward</strong> by streaming and replaying WAL records. That’s why applications using read replicas must be designed to tolerate brief periods of stale reads.</p><h3>2. Sharding</h3><p>Replication copies data.</p><p>Sharding <strong>splits</strong> data.</p><p>Instead of</p><pre>1 Huge Database</pre><p>we create</p><pre>Shard 1<br>Shard 2<br>Shard 3</pre><p>Each shard owns different data.</p><h3>Real-Life Example</h3><p>Imagine a food delivery company.</p><p>Instead of one kitchen serving India…</p><pre>Kitchen Delhi<br><br>Kitchen Mumbai<br><br>Kitchen Bangalore</pre><p>Each kitchen serves nearby customers.</p><p>Same concept.</p><h3>Example Schema</h3><p>Users</p><pre>User 1<br>User 2<br>User 3<br>...</pre><p>Instead of</p><pre>Single Database<br><br>Shard A<br>Users 1-1M<br><br>Shard B<br>Users 1M-2M<br><br>Shard C<br>Users 2M-3M</pre><h3>When to Use Sharding</h3><p>Use when</p><ul><li>Database storage becomes huge</li><li>Write throughput is maxed</li><li>One server cannot scale anymore</li><li>Multi-region deployment</li></ul><h3>When NOT to Use It</h3><p>Avoid sharding if</p><ul><li>Database &lt; few hundred GB</li><li>Traffic is moderate</li><li>JOIN-heavy application</li><li>Small startup</li></ul><p>Because sharding adds operational complexity.</p><h3>Choosing the Right Shard Key</h3><p>This is where most interviews begin.</p><p>A bad shard key destroys performance.</p><p>A good shard key evenly distributes data while matching query patterns.</p><h3>Example 1</h3><p>Orders</p><pre>Orders<br>-------<br>id<br>user_id<br>amount<br>status</pre><p>Queries</p><pre>SELECT *<br>FROM orders<br>WHERE user_id = ?</pre><p>Shard by</p><pre>user_id</pre><p>Every user’s orders remain together.</p><p>Excellent.</p><h3>Example 2</h3><p>Comments</p><pre>comments<br>---------<br>id<br>post_id<br>user_id<br>text</pre><p>Suppose UI loads</p><pre>All comments of a post</pre><p>Query</p><pre>SELECT *<br>FROM comments<br>WHERE post_id = 88;</pre><p>Shard by</p><pre>post_id</pre><p>Perfect.</p><h3>Example 3</h3><p>Social Media Timeline</p><p>Schema</p><pre>posts<br>-------<br>id<br>user_id<br>created_at</pre><pre>SELECT *<br>FROM posts<br>WHERE user_id=15<br>ORDER BY created_at DESC<br>LIMIT 20;</pre><p>Better shard key</p><pre>user_id</pre><p>because the application almost always fetches a user’s timeline.</p><p>Within each shard, index by (user_id, created_at DESC) for fast retrieval.</p><h3>Counter Example: Why post_id Isn&#39;t Always the Best Choice</h3><p>Suppose your application frequently executes:</p><pre>SELECT *<br>FROM posts<br>WHERE user_id = 42<br>ORDER BY created_at DESC;</pre><p>If you shard by post_id, a single user&#39;s posts are scattered across many shards because each post has a different post_id.</p><p>To build the user’s timeline, the application must:</p><ol><li>Query every shard.</li><li>Collect matching rows.</li><li>Merge and sort them.</li><li>Return the latest posts.</li></ol><p>This is known as a <strong>scatter-gather query</strong>, and it increases latency as the number of shards grows.</p><p>In contrast, sharding by user_id ensures all of a user&#39;s posts reside on the same shard, allowing the query to execute efficiently on a single database.</p><h3>Is the Shard Key Usually a Foreign Key?</h3><p><strong>Very often, yes — but not because it’s a foreign key.</strong></p><p>It’s because foreign keys such as:</p><ul><li>user_id</li><li>tenant_id</li><li>organization_id</li><li>customer_id</li></ul><p>are frequently used in application queries.</p><p>For example:</p><pre>WHERE tenant_id = ?<br>WHERE user_id = ?<br>WHERE organization_id = ?</pre><p>Since these predicates appear in most requests, using them as shard keys minimizes cross-shard lookups.</p><p>However, there are many valid shard keys that are <strong>not foreign keys</strong>:</p><ul><li>email_hash</li><li>country_code</li><li>device_id</li><li>region</li><li>created_month</li><li>order_number</li></ul><p>The real principle is:</p><blockquote><strong>Choose the column that appears most often in your application’s query predicates while providing an even distribution of data.</strong></blockquote><p>A shard key should be rooted in <strong>hw your application reads and writes data</strong>, not in whether a column is technically a foreign key.</p><h3>Routing Example</h3><pre>function getShard(userId) {<br>    return userId % 4;<br>}</pre><pre>User 21<br>21 % 4<br>Shard 1</pre><h3>3. Partitioning (Database Partitioning)</h3><blockquote><strong><em>Not to be confused with Window function (partition by) in SQL.</em></strong></blockquote><h3>Database Partitioning</h3><p>Database partitioning splits <strong>one table</strong> into multiple physical pieces while presenting them as a single logical table to your application.</p><pre>orders<br>-------<br>↓<br>orders_2024<br>orders_2025<br>orders_2026</pre><p>Applications still query:</p><pre>SELECT *<br>FROM orders;</pre><p>The database automatically reads only the relevant partition when possible.</p><h3>Real-Life Example</h3><p>An audit table</p><pre>2 Billion Rows</pre><p>Every query asks</p><pre>Last 30 days</pre><p>Without partitioning</p><pre>Scan 2 Billion Rows</pre><p>With partitioning</p><pre>orders_2026</pre><p>Only one partition is scanned.</p><h3>Benefits</h3><ul><li>Faster queries through partition pruning</li><li>Faster archival and deletion</li><li>Reduced index size per partition</li><li>Easier maintenance (vacuum, reindex)</li><li>Better performance for time-series workloads</li></ul><h3>PostgreSQL Range Partitioning</h3><p>Parent table</p><pre>CREATE TABLE orders (<br>    id BIGSERIAL,<br>    user_id BIGINT,<br>    amount NUMERIC,<br>    created_at DATE<br>)<br>PARTITION BY RANGE (created_at);</pre><p>Create partitions</p><pre>CREATE TABLE orders_2025<br>PARTITION OF orders<br>FOR VALUES FROM (&#39;2025-01-01&#39;)<br>TO (&#39;2026-01-01&#39;);<br><br>CREATE TABLE orders_2026<br>PARTITION OF orders<br>FOR VALUES FROM (&#39;2026-01-01&#39;)<br>TO (&#39;2027-01-01&#39;);</pre><p>Insert</p><pre>INSERT INTO orders (<br>    user_id,<br>    amount,<br>    created_at<br>)<br>VALUES<br>(1,100,&#39;2026-06-12&#39;);</pre><p>PostgreSQL automatically routes the row into orders_2026.</p><h3>Migrating an Existing Table to a Partitioned Table</h3><p>Assume you already have a table named orders.</p><h3>1. Rename the old table</h3><pre>ALTER TABLE orders RENAME TO orders_old;</pre><h3>2. Create the partitioned parent</h3><pre>CREATE TABLE orders (<br>    id BIGINT,<br>    user_id BIGINT,<br>    amount NUMERIC,<br>    created_at DATE<br>)<br>PARTITION BY RANGE (created_at);</pre><h3>3. Create partitions</h3><pre>CREATE TABLE orders_2025<br>PARTITION OF orders<br>FOR VALUES FROM (&#39;2025-01-01&#39;)<br>TO (&#39;2026-01-01&#39;);<br><br>CREATE TABLE orders_2026<br>PARTITION OF orders<br>FOR VALUES FROM (&#39;2026-01-01&#39;)<br>TO (&#39;2027-01-01&#39;);</pre><h3>4. Copy the existing data</h3><pre>INSERT INTO orders<br>SELECT *<br>FROM orders_old;</pre><p>PostgreSQL automatically routes each row into the correct partition based on created_at.</p><h3>5. Recreate indexes</h3><pre>CREATE INDEX idx_orders_created_at<br>ON orders (created_at);<br><br>CREATE INDEX idx_orders_user_created<br>ON orders (user_id, created_at);</pre><h3>6. Verify the migration</h3><pre>SELECT tableoid::regclass AS partition_name, count(*)<br>FROM orders<br>GROUP BY partition_name;</pre><h3>7. Drop the old table (after verification)</h3><pre>DROP TABLE orders_old;</pre><h3>Replication vs Sharding vs Partitioning</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*EoAQkARqMGSXMuNJvpjyqg.png" /></figure><h3>Final Takeaways</h3><ul><li><strong>Replication</strong> creates multiple copies of the same database to scale reads and improve availability.</li><li><strong>Sharding</strong> distributes data across multiple databases to scale storage and write throughput.</li><li><strong>Partitioning</strong> divides a large table into smaller pieces inside the same database to improve query performance and maintenance.</li><li><strong>Choose your shard key based on your application’s most common access patterns</strong>, ensuring both even data distribution and minimal cross-shard queries. A foreign key is often a good candidate because it’s frequently queried, but it’s the query pattern — not the foreign key relationship itself — that makes it a good shard key.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf6e4950cf16" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/scaling-databases-replication-sharding-partitioning-explained-cf6e4950cf16">Scaling Databases: Replication, Sharding &amp; Partitioning Explained</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[async/await vs ThreadPoolExecutor vs ProcessPoolExecutor: The 30-Second Rule]]></title>
            <link>https://coderraj07.medium.com/async-await-vs-threadpoolexecutor-vs-processpoolexecutor-the-30-second-rule-48509182ba52?source=rss-3ecd9ab4ad4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/48509182ba52</guid>
            <dc:creator><![CDATA[Rajendra Bisoi]]></dc:creator>
            <pubDate>Sat, 04 Jul 2026 03:27:59 GMT</pubDate>
            <atom:updated>2026-07-04T03:27:59.944Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most confusing topics in Python concurrency is deciding <strong>when to use </strong><strong>async/await, </strong><strong>ThreadPoolExecutor, or </strong><strong>ProcessPoolExecutor.</strong></p><p>Here’s the simplest way to remember it.</p><h3>Step 1: Is your program mostly waiting?</h3><p>Examples:</p><ul><li>Database queries</li><li>HTTP API calls</li><li>Redis</li><li>S3 uploads/downloads</li><li>WebSockets</li></ul><p>✅ Use <strong>async/await</strong></p><p><strong>Reason:</strong> While one task is waiting for I/O, Python can execute another task without blocking the thread.</p><h3>Step 2: Is your program doing heavy computation?</h3><p>Examples:</p><ul><li>Image processing</li><li>Video encoding</li><li>Compression</li><li>Encryption</li><li>Local ML inference</li></ul><p>✅ Use <strong>ProcessPoolExecutor</strong></p><p><strong>Reason:</strong> CPU-bound tasks need multiple CPU cores. Separate processes bypass Python’s GIL and run truly in parallel.</p><h3>Step 3: Is the library synchronous and blocking?</h3><p>Examples:</p><ul><li>requests.get()</li><li>open()</li><li>pandas.read_csv()</li><li>Legacy SDKs without async support</li></ul><p>✅ Use <strong>ThreadPoolExecutor</strong></p><p><strong>Reason:</strong> Threads keep your application responsive by moving blocking work off the main thread, even though they don’t speed up CPU-intensive Python code.</p><h3>How many should you use?</h3><p>async/await:Hundreds or thousands of tasks (limited by DB connections, memory, or API rate limits)</p><p>ThreadPoolExecutor:Usually 10–100 threads, then tune based on workload</p><p>ProcessPoolExecutorApproximately equal to the number of CPU cores</p><h3>The 10-Second Interview Answer</h3><ul><li>⏳ <strong>Waiting?</strong> → async/await</li><li>🧠 <strong>Heavy CPU work?</strong> → ProcessPoolExecutor</li><li>🚧 <strong>Blocking synchronous code?</strong> → ThreadPoolExecutor</li></ul><h3>The golden rule:</h3><blockquote><strong><em>Wait → async, Block → ThreadPool, Compute → ProcessPool.</em></strong></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48509182ba52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SDE Sheet Revision Set 6]]></title>
            <link>https://coderraj07.medium.com/sde-sheet-revision-set-6-643bbea9386f?source=rss-3ecd9ab4ad4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/643bbea9386f</guid>
            <category><![CDATA[data-structure-algorithm]]></category>
            <dc:creator><![CDATA[Rajendra Bisoi]]></dc:creator>
            <pubDate>Fri, 26 Jun 2026 05:52:37 GMT</pubDate>
            <atom:updated>2026-06-26T06:23:29.840Z</atom:updated>
            <content:encoded><![CDATA[<ul><li>✅ <strong>Real interview questions</strong></li><li>🧠 <strong>Optimized approach</strong></li><li>🐍 <strong>Clean, interview-ready Python solution</strong></li></ul><p>No fluff, no over-explanation — perfect for last-mile revision for <strong><em>Unthinkable Solutions</em></strong>.</p><h3>1. Swap Two Numbers</h3><pre>def swap(a, b):<br>    a, b = b, a<br>    return a, b<br><br>a, b = map(int, input().split())<br>a, b = swap(a, b)<br>print(a, b)</pre><p><strong>TC:</strong> O(1) <strong>SC:</strong> O(1)</p><h3>2. Sum Without Arithmetic Operators</h3><pre>def get_sum(a, b):<br>    while b != 0:<br>        carry = a &amp; b<br>        a = a ^ b<br>        b = carry &lt;&lt; 1<br>    return a</pre><pre>a, b = map(int, input().split())<br>print(get_sum(a, b))</pre><p><strong>TC:</strong> O(1) (fixed integer size)</p><h3>3. Reverse String</h3><pre>def reverse_string(s):<br>    return s[::-1]<br><br>s = input()<br>print(reverse_string(s))</pre><p>Manual:</p><pre>def reverse_string(s):<br>    res = &quot;&quot;<br>    for ch in s:<br>        res = ch + res<br>    return res</pre><p><strong>TC:</strong> O(n)</p><h3>4. Largest Rectangle in Histogram</h3><pre>def largestRectangleArea(heights):<br>    stack = []<br>    ans = 0<br>    for i, h in enumerate(heights):<br>        while stack and heights[stack[-1]] &gt; h:<br>            height = heights[stack.pop()]<br>            width = i if not stack else i - stack[-1] - 1<br>            ans = max(ans, height * width)<br>        stack.append(i)<br><br>    n = len(heights)<br>    while stack:<br>        height = heights[stack.pop()]<br>        width = n if not stack else n - stack[-1] - 1<br>        ans = max(ans, height * width)<br>    return ans<br><br>arr = list(map(int, input().split()))<br>print(largestRectangleArea(arr))</pre><p><strong>TC:</strong> O(n)</p><h3>5. Minimum Effort to Reach End (Leetcode 1631)</h3><pre>from heapq import *<br>def minimumEffortPath(heights):<br>    m, n = len(heights), len(heights[0])<br>    dist = [[float(&#39;inf&#39;)] * n for _ in range(m)]<br>    dist[0][0] = 0<br>    pq = [(0, 0, 0)]<br>    dirs = [(1,0),(-1,0),(0,1),(0,-1)]<br>    while pq:<br>        effort, x, y = heappop(pq)<br>        if x == m - 1 and y == n - 1:<br>            return effort<br>        for dx, dy in dirs:<br>            nx, ny = x + dx, y + dy<br>            if 0 &lt;= nx &lt; m and 0 &lt;= ny &lt; n:<br>                newEffort = max(effort, abs(heights[x][y] - heights[nx][ny]))<br>                if newEffort &lt; dist[nx][ny]:<br>                    dist[nx][ny] = newEffort<br>                    heappush(pq, (newEffort, nx, ny))</pre><p><strong>TC:</strong> O(mn log mn)</p><h3>6. Reverse Floating Point Number</h3><pre>def reverse_float(num):<br>    s = str(num)<br>    if &quot;.&quot; in s:<br>        left, right = s.split(&quot;.&quot;)<br>        return left[::-1] + &quot;.&quot; + right[::-1]<br>    return s[::-1]<br>print(reverse_float(input()))</pre><h3>7. Merge Intervals</h3><pre>def merge(intervals):<br>    intervals.sort()<br>    ans = []<br>    for start, end in intervals:<br>        if not ans or ans[-1][1] &lt; start:<br>            ans.append([start, end])<br>        else:<br>            ans[-1][1] = max(ans[-1][1], end)<br>    return ans<br><br>arr = [[1,3],[2,6],[8,10],[15,18]]<br>print(merge(arr))</pre><p><strong>TC:</strong> O(n log n)</p><h3>8. 3Sum</h3><pre>def threeSum(nums):<br>    nums.sort()<br>    ans = []<br>    n = len(nums)<br>    for i in range(n):<br>        if i &gt; 0 and nums[i] == nums[i-1]:<br>            continue<br>        l = i + 1<br>        r = n - 1<br>        while l &lt; r:<br>            s = nums[i] + nums[l] + nums[r]<br>            if s == 0:<br>                ans.append([nums[i], nums[l], nums[r]])<br>                l += 1<br>                r -= 1<br>                while l &lt; r and nums[l] == nums[l-1]:<br>                    l += 1<br>                while l &lt; r and nums[r] == nums[r+1]:<br>                    r -= 1<br>            elif s &lt; 0:<br>                l += 1<br>            else:<br>                r -= 1<br>    return ans<br>print(threeSum(list(map(int,input().split()))))</pre><p><strong>TC:</strong> O(n²)</p><h3>9. Longest Common Substring</h3><pre>def longestCommonSubstring(a, b):<br>    n = len(a)<br>    m = len(b)<br>    dp = [[0]*(m+1) for _ in range(n+1)]<br>    ans = 0<br>    for i in range(1, n+1):<br>        for j in range(1, m+1):<br>            if a[i-1] == b[j-1]:<br>                dp[i][j] = 1 + dp[i-1][j-1]<br>                ans = max(ans, dp[i][j])<br>    return ans<br><br>print(longestCommonSubstring(input(), input()))</pre><p><strong>TC:</strong> O(nm)</p><h3>10. Detect Cycle in Linked List</h3><pre>class ListNode:<br>    def __init__(self, val):<br>        self.val = val<br>        self.next = None<br><br>def hasCycle(head):<br>    slow = fast = head<br>    while fast and fast.next:<br>        slow = slow.next<br>        fast = fast.next.next<br>        if slow == fast:<br>            return True<br>    return False</pre><p><strong>TC:</strong> O(n)</p><h3>11. Character Frequency</h3><pre>def frequency(s):<br>    freq = {}<br>    for ch in s:<br>        freq[ch] = freq.get(ch, 0) + 1<br>    return freq<br>print(frequency(input()))</pre><p>Using Counter:</p><pre>from collections import Counter<br>print(Counter(input()))</pre><h3>12. Star Triangle</h3><pre>n = int(input())<br><br>for i in range(1, n+1):<br>    print(&quot;*&quot;*i)</pre><h3>13. Country Auto Suggestion</h3><pre>countries = [<br>    &quot;India&quot;,<br>    &quot;Indonesia&quot;,<br>    &quot;Ireland&quot;,<br>    &quot;Iran&quot;,<br>    &quot;Italy&quot;,<br>    &quot;Iceland&quot;<br>]<br><br>prefix = input().lower()<br><br>for country in countries:<br>    if country.lower().startswith(prefix):<br>        print(country)</pre><p>(Frontend interview expects React implementation.)</p><h3>14. Capitalize Every Word</h3><pre>def capitalize_sentence(s):<br>    return &quot; &quot;.join(word.capitalize() for word in s.split())<br><br>print(capitalize_sentence(input()))</pre><h3>15. INNER JOIN</h3><pre>SELECT e.name, d.department_name<br>FROM Employee e<br>INNER JOIN Department d<br>ON e.dept_id = d.id;</pre><p>Returns matching rows only.</p><h3>16. GROUP BY</h3><pre>SELECT department,<br>       COUNT(*) AS total<br>FROM Employee<br>GROUP BY department;</pre><p>Used with aggregate functions.</p><h3>17. Common JOIN Questions</h3><h3>LEFT JOIN</h3><pre>SELECT *<br>FROM A<br>LEFT JOIN B<br>ON A.id = B.id;</pre><h3>RIGHT JOIN</h3><pre>SELECT *<br>FROM A<br>RIGHT JOIN B<br>ON A.id = B.id;</pre><h3>FULL OUTER JOIN</h3><pre>SELECT *<br>FROM A<br>FULL OUTER JOIN B<br>ON A.id = B.id;</pre><h3>SELF JOIN</h3><pre>SELECT e.name,<br>       m.name AS manager<br>FROM Employee e<br>LEFT JOIN Employee m<br>ON e.manager_id = m.id;</pre><h3>18. Four Pillars of OOP (Python)</h3><pre># Encapsulation<br>class Bank:<br>    def __init__(self):<br>        self.__balance = 100<br>    def get_balance(self):<br>        return self.__balance</pre><pre># Inheritance<br>class Animal:<br>    def speak(self):<br>        print(&quot;Animal&quot;)<br><br>class Dog(Animal):<br>    pass<br><br>Dog().speak()</pre><pre># Polymorphism<br>class Cat:<br>    def sound(self):<br>        print(&quot;Meow&quot;)<br><br>class Dog:<br>    def sound(self):<br>        print(&quot;Bark&quot;)<br><br>for obj in [Cat(), Dog()]:<br>    obj.sound()</pre><pre># Abstraction<br>from abc import ABC, abstractmethod<br>class Shape(ABC):<br>    @abstractmethod<br>    def area(self):<br>        pass<br><br>class Circle(Shape):<br>    def area(self):<br>        return &quot;Area&quot;</pre><h3>19. Constructor Example (Python)</h3><pre>class Student:<br>    def __init__(self, name):<br>        self.name = name<br>    def display(self):<br>        print(self.name)<br>s = Student(&quot;Raj&quot;)<br>s.display()</pre><ul><li>__init__() is called automatically when an object is created.</li><li>A normal method must be called explicitly.</li></ul><h3>20. Circular Linked List</h3><pre>class Node:<br>    def __init__(self, val):<br>        self.val = val<br>        self.next = None<br><br>head = Node(1)<br>second = Node(2)<br>third = Node(3)<br>head.next = second<br>second.next = third<br>third.next = head      # Circular link<br>temp = head<br>for _ in range(6):     # print twice around the circle<br>    print(temp.val, end=&quot; &quot;)<br>    temp = temp.next</pre><p>Output:</p><pre>1 2 3 1 2 3</pre><p><strong>Properties:</strong></p><ul><li>Last node points back to the head.</li><li>No NULL at the end.</li><li>Traversal can start from any node.</li><li>Useful for round-robin scheduling, playlists, and circular queues.</li></ul><h3>21. Maximum Sum Circular Subarray (LeetCode 918)</h3><p><strong>Question</strong></p><p>Given a circular integer array nums, return the maximum possible sum of a non-empty subarray.</p><p><strong>LeetCode</strong></p><p><a href="https://leetcode.com/problems/maximum-sum-circular-subarray/">https://leetcode.com/problems/maximum-sum-circular-subarray/</a></p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/maximum-contiguous-circular-sum/">https://www.geeksforgeeks.org/maximum-contiguous-circular-sum/</a></p><pre>def maxSubarraySumCircular(nums):<br>    total = sum(nums)<br>    cur_max = max_sum = nums[0]<br>    cur_min = min_sum = nums[0]<br>    for x in nums[1:]:<br>        cur_max = max(x, cur_max + x)<br>        max_sum = max(max_sum, cur_max)<br>        cur_min = min(x, cur_min + x)<br>        min_sum = min(min_sum, cur_min)<br>    if max_sum &lt; 0:<br>        return max_sum<br>    return max(max_sum, total - min_sum)<br><br>nums = list(map(int, input().split()))<br>print(maxSubarraySumCircular(nums))</pre><p><strong>TC:</strong> O(n)</p><p><strong>SC:</strong> O(1)</p><h3>22. Rotate Array (LeetCode 189)</h3><p><strong>Question</strong></p><p>Given an array, rotate the array to the right by k steps.</p><p><strong>LeetCode</strong></p><p><a href="https://leetcode.com/problems/rotate-array/">https://leetcode.com/problems/rotate-array/</a></p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/array-rotation/">https://www.geeksforgeeks.org/array-rotation/</a></p><pre>def rotate(nums, k):<br>    n = len(nums)<br>    k %= n<br>    nums.reverse()<br>    nums[:k] = reversed(nums[:k])<br>    nums[k:] = reversed(nums[k:])<br>    return nums<br><br>nums = list(map(int, input().split()))<br>k = int(input())<br>print(rotate(nums, k))</pre><p><strong>TC:</strong> O(n)</p><p><strong>SC:</strong> O(1)</p><h3>23. Maximum Sum Subarray of Size K</h3><p><strong>Question</strong></p><p>Given an array of integers Arr of size N and a number K. Among all subarrays of size K, find the subarray whose sum is maximum.</p><p><strong>LeetCode</strong></p><p><a href="https://leetcode.com/problems/maximum-average-subarray-i/">https://leetcode.com/problems/maximum-average-subarray-i/</a></p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/find-maximum-minimum-sum-subarray-size-k/">https://www.geeksforgeeks.org/find-maximum-minimum-sum-subarray-size-k/</a></p><pre>def max_sum_subarray(arr, k):<br>    window = 0<br>    ans = float(&quot;-inf&quot;)<br>    i = 0<br>    for j in range(len(arr)):<br>        window += arr[j]<br>        if j - i + 1 == k:<br>            ans = max(ans, window)<br>            window -= arr[i]<br>            i += 1<br>    return ans<br><br>arr = list(map(int, input().split()))<br>k = int(input())<br>print(max_sum_subarray(arr, k))</pre><p><strong>TC:</strong> O(n)</p><p><strong>SC:</strong> O(1)</p><h3>24. LRU Cache (LeetCode 146)</h3><p><strong>Question</strong></p><p>Design and implement an LRU Cache.</p><p><strong>LeetCode</strong></p><p><a href="https://leetcode.com/problems/lru-cache/">https://leetcode.com/problems/lru-cache/</a></p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/lru-cache-implementation/">https://www.geeksforgeeks.org/lru-cache-implementation/</a></p><pre>from collections import OrderedDict<br>    class LRUCache:<br>    def __init__(self, capacity):<br>        self.cap = capacity<br>        self.cache = OrderedDict()<br>    def get(self, key):<br>        if key not in self.cache:<br>            return -1<br>        self.cache.move_to_end(key)<br>        return self.cache[key]<br>    def put(self, key, value):<br>        if key in self.cache:<br>            self.cache.move_to_end(key)<br>        self.cache[key] = value<br>        if len(self.cache) &gt; self.cap:<br>            self.cache.popitem(last=False)</pre><p><strong>TC:</strong> O(1)</p><p><strong>SC:</strong> O(capacity)</p><h3>25. Longest Substring Without Repeating Characters (LeetCode 3)</h3><p><strong>Question</strong></p><p>Find the length of the longest substring without repeating characters.</p><p><strong>LeetCode</strong></p><p><a href="https://leetcode.com/problems/longest-substring-without-repeating-characters/">https://leetcode.com/problems/longest-substring-without-repeating-characters/</a></p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/length-of-the-longest-substring-without-repeating-characters/">https://www.geeksforgeeks.org/length-of-the-longest-substring-without-repeating-characters/</a></p><pre>def lengthOfLongestSubstring(s):<br>    left = 0<br>    seen = {}<br>    ans = 0<br>    for right in range(len(s)):<br>        if s[right] in seen and seen[s[right]] &gt;= left:<br>            left = seen[s[right]] + 1<br>        seen[s[right]] = right<br>        ans = max(ans, right - left + 1)<br>    return ans<br><br>print(lengthOfLongestSubstring(input()))</pre><p><strong>TC:</strong> O(n)</p><p><strong>SC:</strong> O(256)</p><h3>26. Largest Rectangle in Histogram (LeetCode 84)</h3><p><strong>Question</strong></p><p>Given histogram heights, return the largest rectangle area.</p><p><strong>LeetCode</strong></p><p><a href="https://leetcode.com/problems/largest-rectangle-in-histogram/">https://leetcode.com/problems/largest-rectangle-in-histogram/</a></p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/largest-rectangular-area-in-a-histogram-using-stack/">https://www.geeksforgeeks.org/largest-rectangular-area-in-a-histogram-using-stack/</a></p><pre>def largestRectangleArea(heights):<br>    stack = []<br>    ans = 0<br>    for i, h in enumerate(heights):<br>        while stack and heights[stack[-1]] &gt; h:<br>            height = heights[stack.pop()]<br>            width = i if not stack else i - stack[-1] - 1<br>            ans = max(ans, height * width)<br>        stack.append(i)<br>    n = len(heights)<br>    while stack:<br>        height = heights[stack.pop()]<br>        width = n if not stack else n - stack[-1] - 1<br>        ans = max(ans, height * width)<br>    return ans<br><br>print(largestRectangleArea(list(map(int, input().split()))))</pre><p><strong>TC:</strong> O(n)</p><h3>27. Subarray Sum Equals K (LeetCode 560)</h3><p><strong>Question</strong></p><p>Return the total number of subarrays whose sum equals K.</p><p><strong>LeetCode</strong></p><p><a href="https://leetcode.com/problems/subarray-sum-equals-k/">https://leetcode.com/problems/subarray-sum-equals-k/</a></p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/number-subarrays-sum-exactly-equal-k/">https://www.geeksforgeeks.org/number-subarrays-sum-exactly-equal-k/</a></p><pre>from collections import defaultdict<br>def subarraySum(nums, k):<br>    prefix = defaultdict(int)<br>    prefix[0] = 1<br>    s = 0<br>    ans = 0<br>    for x in nums:<br>        s += x<br>        ans += prefix[s - k]<br>        prefix[s] += 1<br>    return ans<br><br>nums = list(map(int, input().split()))<br>k = int(input())<br>print(subarraySum(nums, k))</pre><p><strong>TC:</strong> O(n)</p><p><strong>SC:</strong> O(n)</p><h3>28. Longest Palindromic Substring (LeetCode 5)</h3><p><strong>Question</strong></p><p>Given a string, return the longest palindromic substring.</p><p><strong>LeetCode</strong></p><p><a href="https://leetcode.com/problems/longest-palindromic-substring/">https://leetcode.com/problems/longest-palindromic-substring/</a></p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/longest-palindromic-substring/">https://www.geeksforgeeks.org/longest-palindromic-substring/</a></p><pre>def longestPalindrome(s):<br>    ans = &quot;&quot;<br><br>    def expand(l, r):<br>        while l &gt;= 0 and r &lt; len(s) and s[l] == s[r]:<br>            l -= 1<br>            r += 1<br>        return s[l + 1:r]<br><br>    for i in range(len(s)):<br>        p1 = expand(i, i)<br>        if len(p1) &gt; len(ans):<br>            ans = p1<br>        p2 = expand(i, i + 1)<br>        if len(p2) &gt; len(ans):<br>            ans = p2<br>    return ans<br><br>print(longestPalindrome(input()))</pre><p><strong>TC:</strong> O(n²)</p><p><strong>SC:</strong> O(1)</p><h3>29. Stack Using Array</h3><p><strong>Question</strong></p><p>Implement Stack using an Array.</p><p><strong>LeetCode</strong></p><p>N/A</p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/implement-stack-using-array/">https://www.geeksforgeeks.org/implement-stack-using-array/</a></p><pre>class Stack:<br>    def __init__(self):<br>        self.arr = []<br>    def push(self, x):<br>        self.arr.append(x)<br>    def pop(self):<br>        if self.arr:<br>            return self.arr.pop()<br>        return -1<br>    def top(self):<br>        if self.arr:<br>            return self.arr[-1]<br>        return -1<br>    def empty(self):<br>        return len(self.arr) == 0</pre><h3>30. Frequency of Elements</h3><p><strong>Question</strong></p><p>Count frequency of every element in an array/string.</p><p><strong>LeetCode</strong></p><p><a href="https://leetcode.com/problems/top-k-frequent-elements/">https://leetcode.com/problems/top-k-frequent-elements/</a></p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/counting-frequencies-of-array-elements/">https://www.geeksforgeeks.org/counting-frequencies-of-array-elements/</a></p><pre>from collections import Counter<br>arr = list(map(int, input().split()))<br>freq = Counter(arr)<br>for k, v in freq.items():<br>    print(k, v)</pre><p><strong>TC:</strong> O(n)</p><p><strong>SC:</strong> O(n)</p><h3>31. Sort 0, 1, 2 (Dutch National Flag)</h3><p><strong>Question</strong></p><p>Given an array containing only 0, 1, and 2, sort it in-place.</p><p><strong>LeetCode</strong></p><p><a href="https://leetcode.com/problems/sort-colors/">https://leetcode.com/problems/sort-colors/</a></p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/">https://www.geeksforgeeks.org/sort-an-array-of-0s-1s-and-2s/</a></p><pre>def sortColors(nums):<br>    low = mid = 0<br>    high = len(nums) - 1<br>    while mid &lt;= high:<br>        if nums[mid] == 0:<br>            nums[low], nums[mid] = nums[mid], nums[low]<br>            low += 1<br>            mid += 1<br>        elif nums[mid] == 1:<br>            mid += 1<br>        else:<br>            nums[mid], nums[high] = nums[high], nums[mid]<br>            high -= 1<br>    return nums<br><br>nums = list(map(int, input().split()))<br>print(sortColors(nums))</pre><p><strong>TC:</strong> O(n)</p><p><strong>SC:</strong> O(1)</p><h3>32. Binary Search</h3><p><strong>Question</strong></p><p>Given a sorted array and a target, return its index if found, otherwise -1.</p><p><strong>LeetCode</strong></p><p><a href="https://leetcode.com/problems/binary-search/">https://leetcode.com/problems/binary-search/</a></p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/binary-search/">https://www.geeksforgeeks.org/binary-search/</a></p><pre>def binarySearch(arr, target):<br>    low = 0<br>    high = len(arr) - 1<br>    while low &lt;= high:<br>        mid = (low + high) // 2<br>        if arr[mid] == target:<br>            return mid<br>        elif arr[mid] &lt; target:<br>            low = mid + 1<br>        else:<br>            high = mid - 1<br>    return -1<br><br>arr = list(map(int, input().split()))<br>target = int(input())<br>print(binarySearch(arr, target))</pre><p><strong>TC:</strong> O(log n)</p><p><strong>SC:</strong> O(1)</p><h3>33. Climbing Stairs</h3><p><strong>Question</strong></p><p>You are climbing a staircase. Each time you can climb 1 or 2 steps. Find the number of distinct ways to reach the top.</p><p><strong>LeetCode</strong></p><p><a href="https://leetcode.com/problems/climbing-stairs/">https://leetcode.com/problems/climbing-stairs/</a></p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/count-ways-reach-nth-stair/">https://www.geeksforgeeks.org/count-ways-reach-nth-stair/</a></p><pre>def climbStairs(n):<br>    if n &lt;= 2:<br>        return n<br>    a = 1<br>    b = 2<br>    for _ in range(3, n + 1):<br>        a, b = b, a + b<br>    return b<br><br>print(climbStairs(int(input())))</pre><p><strong>TC:</strong> O(n)</p><p><strong>SC:</strong> O(1)</p><h3>34. Find Repeating Elements</h3><p><strong>Question</strong></p><p>Print all repeating elements in an array.</p><p><strong>LeetCode</strong></p><p>N/A</p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/find-duplicates-in-on-time-and-constant-extra-space/">https://www.geeksforgeeks.org/find-duplicates-in-on-time-and-constant-extra-space/</a></p><pre>from collections import Counter<br>arr = list(map(int, input().split()))<br>freq = Counter(arr)<br>for num in freq:<br>    if freq[num] &gt; 1:<br>        print(num)</pre><p><strong>TC:</strong> O(n)</p><p><strong>SC:</strong> O(n)</p><h3>35. Circular Linked List</h3><p><strong>Question</strong></p><p>Implement a Circular Linked List.</p><p><strong>LeetCode</strong></p><p>N/A</p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/circular-linked-list/">https://www.geeksforgeeks.org/circular-linked-list/</a></p><pre>class Node:<br>    def __init__(self, val):<br>        self.val = val<br>        self.next = None<br><br>head = Node(1)<br>second = Node(2)<br>third = Node(3)<br>head.next = second<br>second.next = third<br>third.next = head<br>temp = head<br>for _ in range(6):<br>    print(temp.val, end=&quot; &quot;)<br>    temp = temp.next</pre><p><strong>TC:</strong> O(n)</p><h3>36. Reverse Linked List</h3><p><strong>Question</strong></p><p>Reverse a singly linked list.</p><p><strong>LeetCode</strong></p><p><a href="https://leetcode.com/problems/reverse-linked-list/">https://leetcode.com/problems/reverse-linked-list/</a></p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/reverse-a-linked-list/">https://www.geeksforgeeks.org/reverse-a-linked-list/</a></p><pre>class ListNode:<br>    def __init__(self, val):<br>        self.val = val<br>        self.next = None<br><br>def reverse(head):<br>    prev = None<br>    curr = head<br>    while curr:<br>        nxt = curr.next<br>        curr.next = prev<br>        prev = curr<br>        curr = nxt<br>    return prev</pre><p><strong>TC:</strong> O(n)</p><p><strong>SC:</strong> O(1)</p><h3>37. Detect Cycle in Linked List</h3><p><strong>Question</strong></p><p>Determine whether a linked list contains a cycle.</p><p><strong>LeetCode</strong></p><p><a href="https://leetcode.com/problems/linked-list-cycle/">https://leetcode.com/problems/linked-list-cycle/</a></p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/detect-loop-in-a-linked-list/">https://www.geeksforgeeks.org/detect-loop-in-a-linked-list/</a></p><pre>def hasCycle(head):<br>    slow = fast = head<br>    while fast and fast.next:<br>        slow = slow.next<br>        fast = fast.next.next<br>        if slow == fast:<br>            return True<br>    return False</pre><p><strong>TC:</strong> O(n)</p><p><strong>SC:</strong> O(1)</p><h3>38. Second Highest Salary (SQL)</h3><p><strong>Question</strong></p><p>Write an SQL query to find the second highest salary from the Employee table.</p><p><strong>LeetCode</strong></p><p><a href="https://leetcode.com/problems/second-highest-salary/">https://leetcode.com/problems/second-highest-salary/</a></p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/sql-query-to-find-second-largest-value/">https://www.geeksforgeeks.org/sql-query-to-find-second-largest-value/</a></p><pre>SELECT MAX(salary)<br>FROM Employee<br>WHERE salary &lt; (<br>    SELECT MAX(salary)<br>    FROM Employee<br>);</pre><p>Alternative:</p><pre>SELECT DISTINCT salary<br>FROM Employee<br>ORDER BY salary DESC<br>LIMIT 1 OFFSET 1;</pre><h3>39. SQL JOIN</h3><p><strong>Question</strong></p><p>What is a JOIN? Explain different types.</p><p><strong>LeetCode</strong></p><p>N/A</p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/sql-join-set-1-inner-left-right-and-full-joins/">https://www.geeksforgeeks.org/sql-join-set-1-inner-left-right-and-full-joins/</a></p><h3>INNER JOIN</h3><pre>SELECT *<br>FROM Employee e<br>INNER JOIN Department d<br>ON e.dept_id = d.id;</pre><h3>LEFT JOIN</h3><pre>SELECT *<br>FROM Employee e<br>LEFT JOIN Department d<br>ON e.dept_id = d.id;</pre><h3>RIGHT JOIN</h3><pre>SELECT *<br>FROM Employee e<br>RIGHT JOIN Department d<br>ON e.dept_id = d.id;</pre><h3>FULL OUTER JOIN</h3><pre>SELECT *<br>FROM Employee e<br>FULL OUTER JOIN Department d<br>ON e.dept_id = d.id;</pre><h3>40. Two Sum</h3><p><strong>Question</strong></p><p>Given an array of integers and a target, return the indices of the two numbers such that they add up to the target.</p><p><strong>LeetCode</strong></p><p><a href="https://leetcode.com/problems/two-sum/">https://leetcode.com/problems/two-sum/</a></p><p><strong>GFG</strong></p><p><a href="https://www.geeksforgeeks.org/check-if-pair-with-given-sum-exists-in-array/">https://www.geeksforgeeks.org/check-if-pair-with-given-sum-exists-in-array/</a></p><pre>def twoSum(nums, target):<br>    mp = {}<br>    for i, num in enumerate(nums):<br>        if target - num in mp:<br>            return [mp[target - num], i]<br>        mp[num] = i<br>    return []<br><br>nums = list(map(int, input().split()))<br>target = int(input())<br>print(twoSum(nums, target))</pre><p><strong>TC:</strong> O(n)</p><p><strong>SC:</strong> O(n)</p><h3>Remaining interview topics (not tied to one exact coding problem)</h3><p>These appeared in experiences but were described generically rather than as a specific problem:</p><ol><li>Three easy array questions (Technical Interview)</li></ol><p>Practice:</p><ul><li>Two Sum</li><li>Best Time to Buy &amp; Sell Stock (LC 121)</li><li>Move Zeroes (LC 283)</li></ul><p>Three coding questions (Coding Test)</p><ul><li>Difficulty reported: 1 Easy + 2 Medium<br>Array / String / Two Pointer / Sliding Window</li><li>Contains Duplicate</li><li>Valid Anagram</li><li>Product of Array Except Self</li><li>Longest Repeating Character Replacement</li><li>Permutation in String</li><li>Minimum Window Substring</li><li>Kth Largest Element (LC 215)</li><li>Merge Intervals (LC 56)</li><li>Search in Rotated Sorted Array (LC 33)</li><li>Number of Islands (LC 200)</li><li>Course Schedule (LC 207)</li></ul><p>These cover the remaining generic interview experiences that did not specify a unique coding question.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=643bbea9386f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ubuntu 24.04 Microphone Works Everywhere Except Google Meet & Zoom Web? Here’s What Fixed It]]></title>
            <link>https://coderraj07.medium.com/ubuntu-24-04-microphone-works-everywhere-except-google-meet-zoom-web-heres-what-fixed-it-fd2dab75fa43?source=rss-3ecd9ab4ad4d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd2dab75fa43</guid>
            <category><![CDATA[ubuntu]]></category>
            <dc:creator><![CDATA[Rajendra Bisoi]]></dc:creator>
            <pubDate>Sat, 20 Jun 2026 17:56:56 GMT</pubDate>
            <atom:updated>2026-06-20T17:56:56.777Z</atom:updated>
            <content:encoded><![CDATA[<p>After installing Ubuntu 24.04, I ran into a frustrating issue on my Lenovo Ideapad 330.</p><p>The microphone was clearly working:</p><ul><li>Ubuntu detected it</li><li>Audio Recorder captured my voice</li><li>Sound Settings showed input levels</li><li>Wired headset audio worked</li></ul><p>Yet the microphone failed in browser-based applications:</p><p>❌ Google Meet</p><p>❌ Zoom Web</p><p>❌ Browser microphone test websites</p><p>After trying browser permissions, input device settings, and PipeWire troubleshooting, the actual fix turned out to be a Realtek audio codec configuration issue.</p><h3>My Setup</h3><ul><li>Laptop: Lenovo Ideapad 330–15IKB</li><li>OS: Ubuntu 24.04.4 LTS</li><li>Audio Codec: Realtek ALC236</li><li>Audio Controller: Intel Sunrise Point-LP HD Audio</li><li><strong>Audio Device: Wired Earphones with In-line Microphone (3.5mm jack)</strong></li></ul><h3>Symptoms</h3><p>The microphone appeared to work normally in Ubuntu, but browser applications could not use it.</p><p>My alsamixer settings screenshot is attached below</p><p>I experienced the issue in:</p><ul><li>Google Meet</li><li>Zoom Web</li><li>Browser microphone testing websites</li></ul><p>This made the problem confusing because the hardware itself was clearly being detected.</p><h3>The Fix</h3><p>Edit the ALSA configuration file:</p><pre>sudo nano /etc/modprobe.d/alsa-base.conf</pre><p>Add the following line at the end of the file:</p><pre>options snd-hda-intel model=dell-headset-multi</pre><p>Save the file and reboot:</p><pre>sudo reboot</pre><h3>ALSA Mixer Settings</h3><p>After rebooting, open:</p><pre>alsamixer</pre><p>Press <strong>F6</strong> and select:</p><pre>HDA Intel PCH</pre><p>Verify the following settings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TNEFB_xY2KHJxBTrMYbkDw.png" /></figure><p>I am using <strong>wired earphones </strong>and here is what I selected</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*Q6xY4t9fHZoQl735msl7gg.png" /></figure><h3>Result</h3><p>Immediately after reboot:</p><p>✅ Google Meet microphone working</p><p>✅ Zoom Web microphone working</p><p>✅ Browser microphone tests passing</p><p>✅ Wired headset microphone working correctly</p><h3>Why Does a “Dell” Option Fix a Lenovo Laptop?</h3><p>This confused me at first.</p><p>The option:</p><pre>model=dell-headset-multi</pre><p>does not mean you need a Dell laptop.</p><p>It is simply a predefined audio routing profile built into the Linux snd-hda-intel driver.</p><p>Forcing the Dell headset profile corrected the microphone routing and allowed browsers to access the microphone properly.</p><h3>Final Thoughts</h3><p>If your microphone works in Ubuntu applications but fails specifically in Google Meet, Zoom Web, or browser microphone tests, and your system uses a <strong>Realtek ALC236 codec</strong>, try:</p><pre>options snd-hda-intel model=dell-headset-multi</pre><p>It solved the issue instantly on my Lenovo Ideapad 330 running Ubuntu 24.04.4 LTS after weeks of troubleshooting.</p><p>Hopefully this saves someone else a few hours of frustration. 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd2dab75fa43" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>