<?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 Karthik Sudhakar Kashyap on Medium]]></title>
        <description><![CDATA[Stories by Karthik Sudhakar Kashyap on Medium]]></description>
        <link>https://medium.com/@karthikkashyap_84962?source=rss-6fb94f92dcc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bOO18FsaNqlW0KUzv4pAmQ.jpeg</url>
            <title>Stories by Karthik Sudhakar Kashyap on Medium</title>
            <link>https://medium.com/@karthikkashyap_84962?source=rss-6fb94f92dcc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:48:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@karthikkashyap_84962/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[Final solution for macOS’ terrible window management]]></title>
            <link>https://medium.com/@karthikkashyap_84962/final-solution-for-macos-terrible-window-management-08018b63c32a?source=rss-6fb94f92dcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/08018b63c32a</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[unix]]></category>
            <dc:creator><![CDATA[Karthik Sudhakar Kashyap]]></dc:creator>
            <pubDate>Sun, 22 Dec 2024 17:11:55 GMT</pubDate>
            <atom:updated>2024-12-23T05:09:48.813Z</atom:updated>
            <content:encoded><![CDATA[<p>Coming from years of using Windows (since the XP days) and transitioning to i3wm on Debian 12, macOS’s window management felt like a significant downgrade. While macOS is undeniably polished, its default window management is clunky and inefficient. Windows get buried, app switching is cumbersome, and resizing feels restrictive. After a lot of trial and error with different tools and configurations, I’ve found a setup that works well…enough.</p><h3>The Problem with macOS Window Management</h3><p>Switching from i3wm, macOS’s window management was painful. By default, macOS relies on multiple desktops (“Spaces”) and Mission Control to manage windows, but it’s unintuitive and slow. Hunting for minimized windows in the dock or losing track of where an app lives is maddening. Resizing windows? Forget it.</p><h3>The Philosophy: A Better Way to Work</h3><p>When I used i3wm on Debian, everything was fast, efficient, and keyboard-driven. I knew where every window was, could split and resize them in seconds, and never wasted time hunting for buried apps. On macOS, it felt like I was constantly losing my flow. My goal was simple:</p><ul><li><strong>Never minimize windows.</strong></li><li><strong>Keep every app visible and accessible.</strong></li><li><strong>Know where every application is at any time.</strong></li><li><strong>Switch between apps with minimal effort.</strong></li><li><strong>Split and resize windows for multitasking.</strong></li><li><strong>Keep it aesthetic.</strong></li></ul><p>This is exactly what tiling window managers are built for.</p><h3>Finding the right tool</h3><p>I tried several popular tools:</p><ul><li><strong>Spectacle</strong>: Simple, but too limited.</li><li><strong>Amethyst</strong>: Decent tiling, but I found it buggy, and with some missing functionality.</li><li><strong>Yabai</strong>: Powerful, but required disabling SIP. A potential security concern, especially on work laptops.</li></ul><p>Despite these options, nothing came close to the seamless efficiency I was used to on i3wm.</p><p>After trying all these options, I needed something that aligned better with my workflow. That’s when I discovered <strong>Aerospace</strong>, a tool that mimics i3wm’s functionality on macOS. It’s not perfect, but it’s the closest I’ve come to i3wm’s experience.</p><h3>The Final Solution: Aerospace and SketchyBar</h3><h4>Aerospace: Bringing i3wm to macOS</h4><p><a href="https://github.com/nikitabobko/AeroSpace">Aerospace</a> transformed the way I interact with macOS. It has an <a href="https://nikitabobko.github.io/AeroSpace/goodies#i3-like-config">i3-like config</a>, which gave me most of the important features that I was used to on i3.</p><h4>My Workspace Layout</h4><p>Each workspace is dedicated to a specific task (more on this below). To keep things organized, I’ve divided my workflow across six workspaces:</p><ol><li><strong>Code:</strong> All my code editors and related tools live here.</li><li><strong>Terminal:</strong> For running commands and managing Podman (Docker Desktop alternative).</li><li><strong>Utilities:</strong> Apps like Postman and MongoDB Compass.</li><li><strong>Messaging:</strong> WhatsApp and Slack.</li><li><strong>Browser:</strong> Chrome or Safari for research and browsing.</li><li><strong>Notion:</strong> For note-taking and planning.</li></ol><h4>Switching between spaces</h4><p>Switching between these is a breeze. I use the Option key as my mod key, so:</p><ul><li>mod-1 jumps to Workspace 1.</li><li>mod-2 jumps to Workspace 2.</li><li>And so on.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Lhjw3teW39iSr45110Kd6g.gif" /><figcaption>Switching between spaces</figcaption></figure><h4>Moving windows between spaces</h4><p>Moving windows between workspaces is just as easy. Let’s say I need Chrome next to my code editor for debugging. I use mod + Shift + &lt;number&gt; to send the current window to the desired workspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*XxQmFmIgoKU4YQx9Q7x2PQ.gif" /><figcaption>Moving windows between spaces</figcaption></figure><p>In the GIF above, I move my Chrome window to my workspace 1 (next my code editor) by doing mod + Shift + 1. And then I move it back by doing mod + Shift + 5</p><h4>Resizing Windows</h4><p>One of my favorite features is quick window resizing. Imagine you’re debugging an app and need your terminal and code editor in a perfect split. Just enter resize mode - mod + r, then use j/l/k/; to resize. It’s fast and intuitive.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*b1peCWlOB7dceIjo1mmFtA.gif" /><figcaption>Window Resizing</figcaption></figure><h4>SketchyBar: Aesthetic and Functional Menubar</h4><p>To complement Aerospace, I added <strong>SketchyBar</strong>, a highly customizable menubar tool. It takes macOS’s functional (but boring) menubar and turns it into something genuinely useful. Here’s what I’ve done with it:</p><ul><li><strong>Workspace Indicators:</strong> Instantly see which workspace is active.</li><li><strong>Hardware Metrics:</strong> Monitor CPU, GPU, and RAM usage.</li><li><strong>Dynamic Features:</strong> Weather updates, stock tracking, and more.</li><li><strong>Minimalist Aesthetic:</strong> Clean and modern, without being distracting.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gLQNz_MkGDZFt3LGrthODQ.png" /></figure><h4>Automating the Setup</h4><p>Getting all this configured took a bit of effort, involving multiple tools and tweaks to macOS settings. But the results have been worth it. I’m currently working on automating this setup and will share a detailed guide soon. Stay tuned!</p><h3>Final Thoughts</h3><p>macOS’s default window management might be terrible, but with the right tools — Aerospace for i3wm-style management and SketchyBar for aesthetics — you can boost your productivity. My current setup is fast, efficient, and beautiful, and it finally makes macOS feel like home.</p><p>If you’ve struggled with macOS window management or have tips of your own, drop a comment below. Let’s fix this together!</p><h3>References</h3><ul><li>I first discovered Aerospace while browsing <a href="https://www.reddit.com/r/unixporn/">r/unixporn</a>, a gold-mine of beautiful setups</li><li>If you haven’t already, check out <a href="https://www.youtube.com/@joseanmartinez"><strong>Josean Martinez on YouTube</strong></a>. Most of my config is heavily inspired by his.</li><li>You can find my dotfiles on my <a href="https://github.com/karthikkashyap98/dotfiles">GitHub here.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=08018b63c32a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Pony Makes Concurrent Programming Safe by Design]]></title>
            <link>https://medium.com/@karthikkashyap_84962/how-pony-makes-concurrent-programming-safe-by-design-730d69921d0e?source=rss-6fb94f92dcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/730d69921d0e</guid>
            <category><![CDATA[pony]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[operating-systems]]></category>
            <category><![CDATA[actor-model]]></category>
            <dc:creator><![CDATA[Karthik Sudhakar Kashyap]]></dc:creator>
            <pubDate>Sat, 30 Nov 2024 05:46:24 GMT</pubDate>
            <atom:updated>2024-11-30T05:46:24.386Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KUvVdsYbWvIAgvoSYwyi5A.png" /><figcaption>PonyLang</figcaption></figure><blockquote>Pony is an open-source, object-oriented, actor-model, capabilities-secure, high-performance programming language.</blockquote><p>Pony is primarily built on the actor model, just like Erlang or Elixir, but takes a unique approach to concurrency safety. While all three languages use actors as their core building blocks for concurrent systems, Pony distinguishes itself by enforcing safety at compile time through its capability system. In this article, I will look at what Reference Capabilities<a href="https://tutorial.ponylang.io/reference-capabilities/reference-capabilities.html#reference-capabilities">¶</a> are and how they are used.</p><h3>Actor Model</h3><blockquote>An actor is like a class in object-oriented programming, but with an additional superpower: it’s also a unit of parallelism that can independently execute synchronous code.</blockquote><p>While regular classes share memory and require careful synchronization, actors run their code in isolation and communicate only through message-passing.</p><pre>actor Aardvark<br>  let name: String<br>  var _hunger_level: U64 = 0<br><br>  new create(name&#39;: String) =&gt;<br>    name = name&#39;<br><br>  be eat(amount: U64) =&gt;<br>    _hunger_level = _hunger_level - amount.min(_hunger_level)</pre><p>The be eat(amount: U64) block, which is a “behaviour” (similar to a function), runs concurrently. But any code you write within an actor’s behaviour runs synchronously. Actors in Pony can communicate with each other by invoking these <strong>behaviours.</strong></p><p>I won’t be going into the details of the Actor Model in this blog. Instead let’s look at the problems that arise due concurrent/parallel programming.</p><h3>Data-Races &amp; Dead Locks</h3><p>Let’s look at how the <strong>deposit</strong> function of a bank would work. (This is just a loose example)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*BqsC5ej2s57AUmIIg7VaCg.png" /></figure><p>Now imagine that it’s a shared bank account being updated by two users, almost at the same time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*7LiX3UYAncdmiDS44Z8yIQ.png" /></figure><p>Depending on who executes this the last, they end up overwriting the other’s update. This is a <strong>data-race.</strong></p><p>To avoid this, we can use a <a href="https://en.wikipedia.org/wiki/Lock_(computer_science)">lock</a> around the code that updates the balance. This ensures that only one thread can read, modify, and write the balance at any time. <strong>The goal is to allow many readers but have a single writer.</strong></p><p>However, improper use of locks can lead to deadlocks. For instance, consider two threads trying to transfer money between accounts:</p><p>Thread A: Transfer from Account 1 to Account 2<br>Thread B: Transfer from Account 2 to Account 1</p><p>If Thread A locks Account 1 and Thread B locks Account 2 simultaneously, then each thread will be stuck waiting for the other account to be unlocked. This results in a <strong>deadlock</strong>, where neither thread can proceed.</p><p>When writing this in C, even if the code compiles without errors, a programmer can inadvertently write code that leads to deadlocks at runtime. This occurs because the compiler cannot detect potential deadlocks or concurrency issues.</p><p>Pony introduces reference capabilities to solve this issue at compile time!</p><h3>Reference Capabilities</h3><blockquote>Reference capabilities allow the programmer to use the Pony type system to guarantee that you are safely handling data in your application. If you try to do something unsafe, your program won’t compile.</blockquote><p>When a variable alias is created, the developer must specify who has Read/Write access to the variable. As the program is written in a multi-actor environment, it is important to specify the read/write access limits of each of these variables to avoid data races.</p><p><strong>In Pony, reference capabilities (“refcaps”) offer a structured way to enforce these limits, ensuring that variables are accessed in a safe manner across multiple actors.</strong></p><pre>let list {refcap} = Array[U64] // The capability is defined as per requirement</pre><p>Reference capabilities (refcaps) in Pony define whether a variable is confined strictly to the actor that owns it or if it can be safely shared among multiple actors. As mentioned earlier, in Pony a unit of concurrency is an actor and not a thread.</p><h3>Actor-Confined Variables</h3><p>If you want to have aliases to variables that are strictly local to the actor and will <strong>never </strong>be shared, then you use a reference capability called <strong>ref</strong></p><pre>let point: Coordinates ref = Coordinates <br>let alias_point: Coordinates ref = point<br>point.y += 1<br>alias_point.x -=1</pre><p>You don’t need to worry about other actors concurrently updating these aliases. But with ref no other actor will be able to access these objects and will remain local to this actor.</p><h3>Message-Passing Variables</h3><p>For an actor to send messages to another actor, it needs a reference to that actor. These references are of the tag ref-type, and they are used exclusively to invoke the behaviours of the referenced actor.</p><p>Let’s look at how a <em>main </em>actor and a <em>computer </em>actor can exchange messages. The main actor first creates the computer actor and stores the instance of this actor in a variable of ref-type tag</p><pre>let computer_actor: Computer tag = Computer(this)<br>computer_actor.compute(250)</pre><p>Using the variable computer_actor, the main actor can invoke behaviours, compute(), on that instance of the Computer Actor.</p><p>The computer actor’s constructor takes in — this as a parameter. this is a tag to the main actor itself. (constructor shown below). A reference of this is stored on the computer actor to ensure that it can communicate back to the main actor.</p><pre>new create(main_actor&#39;: Main tag) =&gt; <br>    main_actor = main_actor&#39;<br><br>be compute(seed: U64) =&gt;<br>    // ...crunch numbers<br>    main_actor.notify_completion(&quot;Some result&quot;)</pre><h3>Sharing — Read only Variables</h3><p>Similar to sharing reference to actors using the this keyword, actors can also share read-only variables between each other, using the val ref-type.</p><pre>grader.request_marks(this)</pre><p>The main actor (say professor) sends a message to an instance of the grader actor by invoking request_marks , while sending a tag reference of itself.</p><pre>actor Grader<br>    ...<br>    be request_marks(prof: Professor) =&gt;<br>        prof.receive_marks(marks)</pre><p>The actor grader receives this message and sends a local alias of the marks array (immutable) by calling the receive_marks behaviour on the main (professor) actor.</p><pre>be receive_marks(marks: Array[U64] val) =&gt;<br>    // some action</pre><p>The professor actor receives this alias as a val ref-type and this reference is <strong>strictly read-only</strong> and the professor actor cannot write to it.</p><h3>Sharing — Mutable Variables</h3><p>Actors can also share mutable variables, with each other. But to enforce the “many reader, <strong>single writer</strong>” scenario, an <strong>actor must destroy its alias </strong>before passing it to another actor.</p><pre>actor Grader<br>    ...<br>    be request_marks(prof: Professor) =&gt;<br>        prof.receive_marks(consume marks)</pre><p>The grader actor must destroy its reference by using the consume keyword.</p><pre>be receive_marks(marks: Array[U64] iso) =&gt;<br>    // some action</pre><p>The professor receives this array as an iso meaning he is the only one with read/write access to this variable.</p><h3>Closing Thoughts</h3><p>To summarize, using these ref-caps, Pony can prove these restrictions at compile time, ensuring safe concurrent programming.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YvHSv1L_gZiQJV8JqrwMhg.png" /><figcaption>Pony Ref-Cap Cheat Sheet</figcaption></figure><p>While Pony may have a learning curve, the benefits it brings to concurrent programming make it a language worth exploring. Learn more about the other ref-caps on the official documentation.</p><p><strong>Credits &amp; References</strong></p><ul><li>The article draws insights from this tech-talk by <a href="https://youtu.be/u1JfYa413fY?si=3Gi9nR49Ny1gTvxp">John Mumm — Safely Sharing Data — Reference Capabilities in the Pony Programming Language</a>. I highly recommend watching this!</li><li><a href="https://www.ponylang.io/">https://www.ponylang.io/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=730d69921d0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MongoDB Query Optimization: A Developer’s Guide to Boosting Performance]]></title>
            <link>https://medium.com/@karthikkashyap_84962/mongodb-query-optimization-a-developers-guide-to-boosting-performance-3a0fd4c884c5?source=rss-6fb94f92dcc------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a0fd4c884c5</guid>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Karthik Sudhakar Kashyap]]></dc:creator>
            <pubDate>Mon, 04 Nov 2024 04:11:04 GMT</pubDate>
            <atom:updated>2024-11-04T04:11:04.875Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/0*GZOYpp4E7Gw-7zVp.png" /></figure><p>Optimizing MongoDB queries is crucial for keeping your database fast and efficient, especially as your data grows and your app scales. In this guide, we’ll break down some practical strategies for analyzing and improving query performance.</p><p>Let&#39;s dive into some techniques that can boost your database performance!</p><h3>MongoDB Indexes</h3><blockquote><strong>Indexes</strong> are special data structures that store a small portion of a collection’s data in an easily searchable form. These indexes are designed to support efficient query execution, allowing the database to locate and retrieve documents much faster than by scanning the entire collection.</blockquote><p>A real-world analogy for indexes is like the index at the beginning of your school textbook. Imagine you’re going through a huge textbook and want to find a specific topic — let’s say, “Monsoon.” Instead of flipping through each page one by one, you can just turn to the index section, find “Monsoon,” and see the exact pages where it’s covered. This saves a lot of time and effort!</p><p>Similarly, in a database like MongoDB, an index helps it quickly locate the data you need without scanning every document, making your search much faster — just like using an index in your textbook.</p><h3><strong>Performance Metrics</strong></h3><h4>Query Time</h4><p>Query execution time is one of the most obvious metrics to track when assessing MongoDB performance. It serves as an initial indicator of query efficiency and can help quickly identify slow-running queries.</p><h4>Documents Scanned vs. Documents Returned</h4><p>One important metric for MongoDB performance is the <em>Documents Scanned vs. Documents Returned</em> ratio. This ratio represents the relationship between the number of documents or keys examined by MongoDB and the actual documents returned by the query. Ideally, this ratio should approach 1 as closely as possible.</p><pre>{<br> &quot;keysExamined&quot;: 124540,<br> &quot;docsExamined&quot;: 124540,<br> &quot;nreturned&quot;: 89<br>}</pre><p>When the ratio is high, it means that MongoDB is scanning more documents than necessary, which can indicate inefficiencies in query execution. Proper indexing can help ensure that MongoDB examines only the relevant documents, keeping this ratio low and optimizing overall query performance.</p><h4>Plan Summary</h4><pre>[{<br>  &quot;IXSCAN&quot;: {<br>     &quot;orderId&quot;: 1,<br>     &quot;createdAt&quot;: 1,<br>  }<br>}]</pre><p>The <em>Plan Summary</em> provides insights into how MongoDB executed a given query. Understanding the key execution stages helps you analyze query performance and identify potential optimization areas. Here are a few primary execution stages to be aware of:</p><ul><li><strong>COLLSCAN (Collection Scan)</strong>: This stage indicates that MongoDB scanned the entire collection to find matching documents. A COLLSCAN suggests the query isn’t using an index, which can be slow and resource-intensive, especially with large datasets.</li><li><strong>SORT (Explicit Sort)</strong>: This stage shows that MongoDB performed an explicit sort operation to organize the results. Sorting can be resource-heavy, especially if the sort is not supported by an index.</li><li><strong>IXSCAN (Index Scan)</strong>: This stage means the query utilized an index to locate relevant documents. IXSCAN is usually more efficient than a collection scan, as it allows MongoDB to limit the scope of scanned documents, resulting in faster query performance.</li><li><strong>FETCH</strong>: After an IXSCAN, MongoDB often operates to retrieve the full documents corresponding to the index keys found. While an IXSCAN limits the number of documents scanned, FETCH operations can still be resource-intensive if the query retrieves a large number of documents or if the documents are large.</li><li><strong>LOOKUP</strong>: Used in aggregation pipelines to perform joins across collections, LOOKUP can be useful but may indicate a need for data restructuring if used frequently.</li></ul><p>These are some of the primary stages that impact MongoDB query performance, though MongoDB includes many other execution stages as well. The ones listed here tend to have the most significant effect on database efficiency and can provide a solid foundation for understanding query behaviour and identifying optimization opportunities.</p><h3>Explain Plan</h3><p>How would one extract the above metrics for a particular query?</p><p>MongoDB’s explain command is the tool for this purpose. By running .explain() on a query, you can retrieve detailed information about the query’s execution plan, including the stages it goes through, the number of documents scanned, the indexes used, and more.</p><p>There are three verbosity levels available with explain:</p><ul><li><strong>&quot;queryPlanner&quot;</strong>: Provides a high-level overview of the query plan, showing the stages MongoDB will use without actually executing the query.</li><li><strong>&quot;executionStats&quot;</strong>: Offers a more detailed look, including both the query plan and metrics on execution time and resource usage.</li><li><strong>&quot;allPlansExecution&quot;</strong>: Delivers the most comprehensive insight, showing stats on all possible query plans MongoDB considered.</li></ul><h4>Usage</h4><pre>db.orders.explain(&#39;queryPlanner&#39;).find({ totalAmountDue: { $gt: 50000 } });<br><br>db.orders.explain(&#39;allPlansExecution&#39;).aggregate(<br>  {<br>    $match: {<br>      orderType: &#39;Event&#39;,<br>    },<br>  },<br>  {<br>    $group: {<br>      _id: &#39;$paymentMethod&#39;,<br>      count: { $sum: 1 },<br>      docs: { $push: &#39;$$ROOT&#39; },<br>    },<br>  },<br>  {<br>    $match: {<br>      count: { $gt: 1 },<br>    },<br>  }<br>);</pre><h3>Explain Plan Legend</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2b-eoI1OahM_9juR0yj-lA.png" /></figure><p>Let’s double-click on the structure</p><pre>{<br>    &quot;nReturned&quot;: 51,<br>    &quot;executionTimeMillis&quot;: 467,<br>    &quot;totalKeysExamined&quot;: 459,<br>    &quot;totalDocsExamined&quot;: 459,<br>    &quot;executionStages&quot;: {<br>        &quot;stage&quot;: &quot;FETCH&quot;,<br>        &quot;filter&quot;: {<br>            &quot;totalAmountDue&quot;: {<br>                &quot;$gt&quot;: 500000<br>            }<br>        },<br>        &quot;nReturned&quot;: 51,<br>        &quot;inputStage&quot;: {<br>            &quot;stage&quot;: &quot;IXSCAN&quot;,<br>            &quot;indexBounds&quot;: {<br>                &quot;Name&quot;: &quot;[MinKey, MaxKey]&quot;<br>            },<br>            &quot;nReturned&quot;: 459<br>        }<br>    }<br>}</pre><ul><li><strong>nReturned:</strong> This value indicates that the query returned 51 documents that matched the criteria specified in the query.</li><li><strong>executionTimeMillis:</strong> The query took 467 milliseconds to execute. Monitoring execution time helps assess query efficiency; longer times may indicate the need for optimization.</li><li><strong>totalKeysExamined:</strong> This number (459) represents how many index keys were examined during the query execution. Lowering this number can often improve performance, as it suggests the query is using the index effectively.</li><li><strong>totalDocsExamined:</strong> The same as totalKeysExamined in this case, indicating that all 459 examined keys corresponded to documents. It’s essential to have a lower number of documents examined compared to those returned, as this means more efficiency.</li><li><strong>executionStages:</strong> This section provides a detailed breakdown of how the query was processed:</li><li><strong>stage: &quot;FETCH&quot;</strong>: The primary stage of execution was a fetch, meaning that after retrieving potential matches via an index, MongoDB fetched the actual documents.</li><li><strong>filter:</strong> This specifies the condition applied to the documents, indicating that only those with totalAmountDue greater than 500,000 were considered.</li><li><strong>nReturned under executionStages:</strong> It confirms that 51 documents matched the filter after fetching.</li><li><strong>inputStage.stage: &quot;IXSCAN&quot;</strong>: This indicates that an index scan was performed, allowing the query to filter results efficiently using the index.</li><li><strong>inputStage.indexBounds</strong>: Shows the range of the index that was scanned. Here, it indicates that the entire range of the index for the Name field was utilized, from the minimum to the maximum key. This suggests that the query may benefit from a more specific index bound to narrow down the search.</li></ul><p>When examining the executionStages in the output, it&#39;s important to note the hierarchical relationship between stages, particularly the <em>inputStage</em>. This structure represents a parent-child relationship: the top-level stage (in this case, FETCH) can have one or more inputStages.</p><p>The idea is that every time you develop an API or construct a query, it’s good practice to run the explain command in the MongoDB shell. By analyzing the output based on the metrics we&#39;ve discussed, along with some additional optimization pointers I will share, you can determine the most suitable indexes to add, enhancing the performance of your queries.</p><h3>Follow the ESR Rule</h3><p>When creating compound indexes in MongoDB, following the <em>ESR Rule</em> can help you determine the optimal order of fields to index, enhancing query performance. This rule prioritizes fields based on the type of query operation, guiding the left-to-right order for fields in compound indexes:</p><ol><li><strong>Equality</strong>: Start by indexing fields used in equality queries ($eq). These fields should be placed first in the compound index since equality matches are the most selective and frequently used in filters. Additionally, if $in is used without a $sort operation, it behaves like an equality match and should be indexed here.</li><li><strong>Sort</strong>: Next, index fields used in sorting operations. By including these fields immediately after equality fields, MongoDB can leverage the index for both filtering and ordering, eliminating the need for additional sorting steps.</li><li><strong>Range</strong>: Finally, include fields representing range queries. Range queries cover conditions like $gt, $gte, $lt, $lte, as well as $regex, $ne, and $nin, which filters data based on a range of values. Additionally, if $in is combined with a .sort stage, MongoDB treats it as a range query, so it should be placed last in the index order.</li></ol><p>The ESR Rule is a helpful guideline but <strong>not</strong> a definitive solution for all indexing strategies. The specific ordering of fields in compound indexes will vary depending on the structure and patterns of your data.</p><p><strong>Example</strong></p><p>An example of a query that is looking for a movie, from Universal Pictures with a runtime greater than 50. It also has sort options on year and award wins.</p><pre>const filter = {<br>  type: &#39;movie&#39;, // Equality<br>  &#39;tomatoes.production&#39;: &#39;Universal Pictures&#39;, // Equality<br>  runtime: { $gt: 50 } // Range<br>};<br><br>const sort = {<br>  year: -1, // Sort by year in descending order<br>  &#39;awards.wins&#39;: -1 // Sort by awards.wins in descending order<br>};</pre><p>Looking at this query, it is clear that type and production are equality queries, runtime is the range query and sort is pretty obvious</p><p>So index in the following order - type, production, year, wins and runtime. This would be the appropriate index.</p><pre>{<br>  &quot;type&quot;: 1,<br>  &quot;tomatoes.production&quot;: 1,<br>  &quot;year&quot;: -1,<br>  &quot;awards.wins&quot;: -1,<br>  &quot;runtime&quot;: 1<br>}</pre><h3>Indexing $or queries</h3><p>Indexing $and queries is considerably straightforward. You would just add a compound index to cover your query.</p><p>But for an $or query, like this one. We would have to add an index on each field of the or query. Mongo can do simultaneous index scans on both these indexes.</p><pre><br>db.inventory.find({<br>  $or: [<br>    { quantity: { $lt: 20 } },<br>    { price: 10 }<br>  ]<br>})<br><br>db.inventory.createIndex({ quantity: 1 })<br>db.inventory.createIndex({ price: 1 })</pre><h3>Complex $or queries</h3><p>It is good practice to simplify complex $or queries to make it easier to index. The following query:</p><pre>{<br>  &quot;filter&quot;: {<br>    &quot;$and&quot;: [<br>      {<br>        &quot;locationId&quot;: 101<br>      },<br>      {<br>        &quot;category&quot;: &quot;ELECTRONICS&quot;<br>      }<br>    ],<br>    &quot;$or&quot;: [<br>      {<br>        &quot;orderId&quot;: 123456<br>      },<br>      {<br>        &quot;customerId&quot;: 78910<br>      }<br>    ]<br>  }<br>}</pre><p>Can be re-written as:</p><pre>{<br>  &quot;filter&quot;: {<br>    &quot;$or&quot;: [<br>      {<br>        &quot;orderId&quot;: 123456,<br>        &quot;locationId&quot;: 101,<br>        &quot;category&quot;: &quot;ELECTRONICS&quot;<br>      },<br>      {<br>        &quot;customerId&quot;: 78910,<br>        &quot;locationId&quot;: 101,<br>        &quot;category&quot;: &quot;ELECTRONICS&quot;<br>      }<br>    ]<br>  }<br>}</pre><p>Rewriting the query this way allows us to come up with indexes easily. Create separate compound indexes for each of the $or queries</p><pre>createIndex({<br>  &quot;customerId&quot;: 1,<br>  &quot;locationId&quot;: 1,<br>  &quot;category&quot;: 1<br>})<br><br>createIndex({<br>  &quot;orderId&quot;: 1,<br>  &quot;locationId&quot;: 1,<br>  &quot;category&quot;: 1<br>})</pre><h3>Compound Indexes</h3><p>The order of fields in a compound index is important for query performance. The sort order can also significantly impact the effectiveness of the index. For example, the indexes { category: 1, modifiedAt: 1 } and { category: 1, modifiedAt: -1 } are treated differently by MongoDB, as the sorting direction affects how data is stored/accessed.</p><h4>Index Prefixes</h4><p>When defining compound indexes, it’s important to note that the leftmost fields do not need to be duplicated. This means that any index containing the same leading fields as another index is considered a duplicate.</p><p>For instance, the following indexes are all duplicates of the first index:</p><ul><li>{ userId: 1, status: 1, createdAt: 1, views: -1 }</li><li>{ userId: 1, status: 1, createdAt: 1 }</li><li>{ userId: 1, status: 1 }</li><li>{ userId: 1 }</li></ul><h3>Covered Queries</h3><p><strong>Example API for Covered Queries</strong><br>Consider an API that retrieves user information based on their status, specifically returning only the usernames of active users. Here’s a sample API endpoint:</p><p><strong>API Endpoint:</strong> GET /api/users/active</p><pre>db.users.find(<br>    { status: &quot;active&quot; },  // Query filter<br>    { username: 1, _id: 0 } // Projection to return only usernames<br>);</pre><p>A <strong>covered query</strong> is a type of query that can be fully satisfied by an index, meaning that no documents need to be examined to fulfil the query.</p><p>To make this query a covered query, you would create a compound index on the status and username fields:</p><pre>db.users.createIndex({ status: 1, username: 1 });</pre><h3>Unique Index</h3><p>A unique index ensures that the indexed fields do not store duplicate values enforcing uniqueness for the indexed fields.</p><ul><li>Can be created for Single-field and Compound indexes</li><li>Cannot be created if data is violating the index already present in the collection</li><li>If a field in the index is missing in the document, it is treated as null and can throw an error if more than one such document exists. In such cases, a partial index with a unique constraint can be used</li></ul><pre>db.users.createIndex({ email: 1 }, { unique: true });</pre><h3>Duplicate Key Errors</h3><p>Errors due to bad unique indexes — Whenever a unique index is added, make sure that the data does not have duplicate entries. There is also a possibility that the field is null for a few cases.</p><p>Especially while using Mongoose, the indexes added to your schema file are built every time your API server is reloaded. This behaviour could lead to IOPS Spikes on the MongoDB instance</p><h3>Sparse Index</h3><p>Sparse indexes only contain entries for documents that have the indexed field, even if the index field contains a null value.</p><p>The index skips over any document that is missing the indexed field. The index is “sparse” because it does not include all documents of a collection. Make sure that the field is not set to null programmatically. The field should not be present on the document.</p><pre>db.addresses.createIndex( { &quot;merchantId&quot;: 1 }, { sparse: true } )</pre><h3>Partial Filter Expression</h3><p>To prevent documents with null or missing fields from impacting your unique constraint, you can use a partial index. A partial index is created with a filter expression, allowing you to specify which documents to include based on certain conditions.</p><pre>userSchema.index({ email: 1 }, { unique: true, partialFilterExpression: { email: { $exists: true, $ne: null } } });</pre><h3>Closing thoughts</h3><p>While optimizing MongoDB queries is a critical aspect of maintaining fast and efficient database operations, it’s important to remember that query optimization is just one part of performance optimization.</p><p>Good data modelling is the foundation of high-performing MongoDB applications. It helps you avoid unnecessary complexity down the line and ensures that your database scales smoothly as your application grows.</p><p><strong>References</strong></p><ol><li><a href="https://www.mongodb.com/docs/manual/core/query-optimization/">MongoDB Query Optimization — Official Documentation</a></li><li><a href="https://www.youtube.com/watch?app=desktop&amp;v=HAtnkHw_fJ8">Let’s .explain() Performance by Chris Harris</a></li><li><a href="https://devopedia.org/mongodb-query-optimization">https://devopedia.org/mongodb-query-optimization</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a0fd4c884c5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>