<?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"><channel><title><![CDATA[Patch Monkey]]></title><description><![CDATA[Patch Monkey]]></description><link>https://patchmonkey.hashnode.dev</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1754483889769/715cb31b-cac7-497f-ae28-0ede22bed5a1.png</url><title>Patch Monkey</title><link>https://patchmonkey.hashnode.dev</link></image><generator>RSS for Node</generator><lastBuildDate>Sun, 08 Nov 2026 02:46:36 GMT</lastBuildDate><atom:link href="https://patchmonkey.hashnode.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[When an Index Isn’t Enough!!]]></title><description><![CDATA[Welcome to Patch Monkey! If you’re reading this, you’ve probably hit that classic moment:"Why is my query so slow even after I added an index?"Let’s break…]]></description><link>https://patchmonkey.hashnode.dev/when-an-index-isnt-enough</link><guid isPermaLink="true">https://patchmonkey.hashnode.dev/when-an-index-isnt-enough</guid><category><![CDATA[Databases]]></category><category><![CDATA[PostgreSQL]]></category><category><![CDATA[query-optimization]]></category><dc:creator><![CDATA[Rahul M]]></dc:creator><pubDate>Wed, 06 Aug 2025 13:34:06 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1754485110458/27edc727-770e-4cf5-8e5c-1d0b5c543764.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Welcome to Patch Monkey! If you’re reading this, you’ve probably hit that classic moment:<br /><em>"Why is my query so slow even after I added an index?"</em><br />Let’s break down how I hit that wall, why “just index it” didn’t work, and the little tweak that made everything fast.</p>
<h2 id="heading-the-setup-simple-feed-not-so-simple-query">The Setup: Simple Feed, Not-So-Simple Query</h2>
<p>I was building a feed where users see all relevant items, newest first. The query looked like this:</p>
<pre><code class="lang-python">qs = (
    Item.objects.annotate(
        sort_timestamp=db_functions.Coalesce(<span class="hljs-string">'published_at'</span>, <span class="hljs-string">'created_at'</span>)
    )
    .filter(
        Q(published_at__isnull=<span class="hljs-literal">True</span>) | Q(published_at__lte=timezone.now()),
        category=category,
        region=region_config[<span class="hljs-string">'region_code'</span>].lower(),
    )
    .order_by(<span class="hljs-string">'-sort_timestamp'</span>, <span class="hljs-string">'id'</span>)
)
</code></pre>
<pre><code class="lang-pgsql"><span class="hljs-keyword">SELECT</span> *,
       COALESCE(published_at, created_at) <span class="hljs-keyword">AS</span> sort_timestamp
<span class="hljs-keyword">FROM</span> item
<span class="hljs-keyword">WHERE</span> (published_at <span class="hljs-keyword">IS</span> <span class="hljs-keyword">NULL</span> <span class="hljs-keyword">OR</span> published_at &lt;= <span class="hljs-meta">$1</span>)
  <span class="hljs-keyword">AND</span> category = <span class="hljs-meta">$2</span>
  <span class="hljs-keyword">AND</span> region = <span class="hljs-meta">$3</span>
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> sort_timestamp <span class="hljs-keyword">DESC</span>, id <span class="hljs-keyword">ASC</span>;
</code></pre>
<p><strong>What’s going on?</strong></p>
<ul>
<li><p>Show items if <code>published_at</code> is null (never scheduled) or in the past.</p>
</li>
<li><p>Sort by a display timestamp (either published or created).</p>
</li>
<li><p>And it took almost 799ms (even with a limit).</p>
</li>
</ul>
<h2 id="heading-classic-move-add-an-index">Classic Move: Add an Index</h2>
<p>Of course, I did what everyone says <em>add an index!</em><br />So I threw this into my model:</p>
<pre><code class="lang-python">models.Index(
    fields=[<span class="hljs-string">'region'</span>, <span class="hljs-string">'category'</span>, <span class="hljs-string">'published_at'</span>],
    name=<span class="hljs-string">'idx_region_category_pub'</span>,
)
</code></pre>
<pre><code class="lang-pgsql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_region_category_pub
<span class="hljs-keyword">ON</span> item (region, category, published_at);
</code></pre>
<p>Did it help?<br /><strong>Barely.</strong></p>
<h3 id="heading-looking-deeper-the-query-plan-the-aha-moment">Looking Deeper: The Query Plan (The “Aha” Moment)</h3>
<p>When I checked the query plan (<code>EXPLAIN</code> always do this!), I saw:</p>
<pre><code class="lang-pgsql"><span class="hljs-keyword">Limit</span>  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">20049.49</span>.<span class="hljs-number">.20057</span><span class="hljs-number">.11</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">3041</span> width=<span class="hljs-number">265</span>)
  -&gt;  Sort  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">20049.49</span>.<span class="hljs-number">.20125</span><span class="hljs-number">.68</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">30409</span> width=<span class="hljs-number">265</span>)
        Sort Key: (COALESCE(published_at, created_at)) <span class="hljs-keyword">DESC</span>, id
        -&gt;  Bitmap Heap Scan <span class="hljs-keyword">on</span> item  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">10318.84</span>.<span class="hljs-number">.19823</span><span class="hljs-number">.06</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">30409</span> width=<span class="hljs-number">265</span>)
              Recheck Cond: (((region = <span class="hljs-meta">$2</span>) <span class="hljs-keyword">AND</span> (category = <span class="hljs-meta">$3</span>) <span class="hljs-keyword">AND</span> (published_at <span class="hljs-keyword">IS</span> <span class="hljs-keyword">NULL</span>)) <span class="hljs-keyword">OR</span> ((region = <span class="hljs-meta">$2</span>) <span class="hljs-keyword">AND</span> (category = <span class="hljs-meta">$3</span>) <span class="hljs-keyword">AND</span> (published_at &lt;= <span class="hljs-meta">$1</span>)))
              -&gt;  BitmapOr  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">10318.84</span>.<span class="hljs-number">.10318</span><span class="hljs-number">.84</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">30683</span> width=<span class="hljs-number">0</span>)
                    -&gt;  Bitmap <span class="hljs-keyword">Index</span> Scan <span class="hljs-keyword">on</span> idx_region_category_pub  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">0.00</span>.<span class="hljs-number">.93</span><span class="hljs-number">.81</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">628</span> width=<span class="hljs-number">0</span>)
                          <span class="hljs-keyword">Index</span> Cond: ((region = <span class="hljs-meta">$2</span>) <span class="hljs-keyword">AND</span> (category = <span class="hljs-meta">$3</span>) <span class="hljs-keyword">AND</span> (published_at <span class="hljs-keyword">IS</span> <span class="hljs-keyword">NULL</span>))
                    -&gt;  Bitmap <span class="hljs-keyword">Index</span> Scan <span class="hljs-keyword">on</span> idx_region_category_pub  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">0.00</span>.<span class="hljs-number">.1030</span><span class="hljs-number">.08</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">30055</span> width=<span class="hljs-number">0</span>)
                          <span class="hljs-keyword">Index</span> Cond: ((region = <span class="hljs-meta">$2</span>) <span class="hljs-keyword">AND</span> (category = <span class="hljs-meta">$3</span>) <span class="hljs-keyword">AND</span> (published_at &lt;= <span class="hljs-meta">$1</span>))
</code></pre>
<ul>
<li><p><strong>BitmapOr</strong></p>
</li>
<li><p><strong>Bitmap Heap Scan</strong></p>
</li>
<li><p>A huge “Recheck” cost</p>
</li>
</ul>
<p>Turns out, that filter with <code>published_at IS NULL OR published_at &lt;= NOW()</code> messes things up.<br />Postgres has to grab two separate index slices (one for <code>IS NULL</code>, one for <code>&lt;= NOW()</code>), merge them (<code>BitmapOr</code>), and then bounce around the table to double-check all the matches (“recheck”).<br />No straight walk through the index = not fast.</p>
<h2 id="heading-the-fix-change-the-query-not-just-the-index">The Fix: Change the Query, Not Just the Index</h2>
<p>Here’s where the “patch monkey” spirit kicked in.<br />Instead of trying to index around the filter, I rewrote the query so filter and sort use the same value:</p>
<pre><code class="lang-python">qs = (
    Item.objects.annotate(
        sort_timestamp=Coalesce(<span class="hljs-string">'published_at'</span>, <span class="hljs-string">'created_at'</span>)
    )
    .filter(
        category=category,
        region=region_config[<span class="hljs-string">'region_code'</span>].lower(),
        sort_timestamp__lte=timezone.now(),
    )
    .order_by(<span class="hljs-string">'-sort_timestamp'</span>, <span class="hljs-string">'id'</span>)
)
</code></pre>
<pre><code class="lang-pgsql"><span class="hljs-keyword">SELECT</span> *,
       COALESCE(published_at, created_at) <span class="hljs-keyword">AS</span> sort_timestamp
<span class="hljs-keyword">FROM</span> item
<span class="hljs-keyword">WHERE</span> category = <span class="hljs-meta">$1</span>
  <span class="hljs-keyword">AND</span> region = <span class="hljs-meta">$2</span>
  <span class="hljs-keyword">AND</span> COALESCE(published_at, created_at) &lt;= <span class="hljs-meta">$3</span>
<span class="hljs-keyword">ORDER</span> <span class="hljs-keyword">BY</span> sort_timestamp <span class="hljs-keyword">DESC</span>, id <span class="hljs-keyword">ASC</span>;
</code></pre>
<p>No more <code>OR</code>—just a single, straightforward condition on <code>sort_timestamp</code>. <strong>Now</strong> both filter and sort use the same expression, which means...</p>
<h2 id="heading-now-the-index-actually-works-for-you">Now the Index Actually Works For You</h2>
<p>Here is an updated index to cover the sort_timestamp</p>
<pre><code class="lang-python">Index(
    <span class="hljs-string">"region"</span>,
    <span class="hljs-string">"category"</span>,
    Coalesce(<span class="hljs-string">"published_at"</span>, <span class="hljs-string">"created_at"</span>).desc(),  <span class="hljs-comment"># matches -sort_timestamp</span>
    F(<span class="hljs-string">"id"</span>),
    name=<span class="hljs-string">"idx_region_category_sort"</span>,
)
</code></pre>
<pre><code class="lang-pgsql"><span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">INDEX</span> idx_region_category_sort
<span class="hljs-keyword">ON</span> item (
    region,
    category,
    COALESCE(published_at, created_at) <span class="hljs-keyword">DESC</span>,
    id
);
</code></pre>
<h2 id="heading-finally"><strong>Finally,</strong></h2>
<p>With the updated query &amp; index, query plan looks like:</p>
<pre><code class="lang-pgsql"><span class="hljs-keyword">Limit</span>  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">0.56</span>.<span class="hljs-number">.3197</span><span class="hljs-number">.94</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">3014</span> width=<span class="hljs-number">265</span>)
  -&gt;  <span class="hljs-keyword">Index</span> Scan <span class="hljs-keyword">using</span> idx_region_category_sort <span class="hljs-keyword">on</span> item  (<span class="hljs-keyword">cost</span>=<span class="hljs-number">0.56</span>.<span class="hljs-number">.31978</span><span class="hljs-number">.64</span> <span class="hljs-keyword">rows</span>=<span class="hljs-number">30144</span> width=<span class="hljs-number">265</span>)
        <span class="hljs-keyword">Index</span> Cond: ((region = <span class="hljs-meta">$2</span>) <span class="hljs-keyword">AND</span> (category = <span class="hljs-meta">$3</span>) <span class="hljs-keyword">AND</span> (COALESCE(published_at, created_at) &lt;= <span class="hljs-meta">$1</span>))
</code></pre>
<p>Now it’s an <code>Index Scan</code> directly matches our filters and sort—no BitmapOr, no heap scan, no expensive sort step.</p>
<p>And we brought down the query execution time from <strong>~799ms to 5ms 🎉</strong></p>
]]></content:encoded></item></channel></rss>