<?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 Isaimanaswinireddy on Medium]]></title>
        <description><![CDATA[Stories by Isaimanaswinireddy on Medium]]></description>
        <link>https://medium.com/@isaimanaswinireddy?source=rss-b39998d7d304------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*h-MeuaNkfWNoUVTv</url>
            <title>Stories by Isaimanaswinireddy on Medium</title>
            <link>https://medium.com/@isaimanaswinireddy?source=rss-b39998d7d304------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 16:58:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@isaimanaswinireddy/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[Nothing Threw an Error. Everything Was Wrong.]]></title>
            <link>https://medium.com/@isaimanaswinireddy/nothing-threw-an-error-everything-was-wrong-46bb4030f4f0?source=rss-b39998d7d304------2</link>
            <guid isPermaLink="false">https://medium.com/p/46bb4030f4f0</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[database-performance]]></category>
            <dc:creator><![CDATA[Isaimanaswinireddy]]></dc:creator>
            <pubDate>Wed, 15 Jul 2026 14:47:03 GMT</pubDate>
            <atom:updated>2026-07-15T14:47:03.812Z</atom:updated>
            <content:encoded><![CDATA[<p><em>I profiled a PostgreSQL pipeline looking for wasted work. I found an optimization that was 60% faster in testing and slower in production, a model that was quietly processing zero rows, and timestamps from 1970, and every single run reported success.</em></p><p>Here is the c<strong>omplete list of errors, exceptions, and failed</strong> runs produced by everything that goes wrong in this story:</p><p><strong>That’s it. That’s the list.</strong></p><p>Every query returned rows. Every database transformation (DBT) model exited green. Every timestamp was a valid timestamp.</p><pre>MongoDB → Airbyte CDC → PostgreSQL per tenant → dbt → API views</pre><p>The pipeline looked healthy from every dashboard we had.</p><p>I went in with a boring goal: transformation time was creeping up, and I wanted to find where PostgreSQL was doing work it didn’t need to do. I came out with a different lesson entirely, and it’s the reason this article exists:</p><p><strong>Success signals tell you that code executed. They tell you nothing about whether it did anything real.</strong></p><p>Two kinds of instrumentation ran through this investigation. EXPLAIN (ANALYZE, BUFFERS) and a home made query plan <strong>flamegraphs</strong> told me where the time went. The second kind was almost insultingly unglamorous: counting rows and reading values, to check whether each transformation processed the records it was supposed to and produced numbers that made sense. The first kind found the performance problems. The second kind found everything that mattered.</p><h3>Act one: the part where I felt smart</h3><p>The profiler pointed at one place immediately. The heaviest transformation reads a JSON array column, one array per row, expands every array into rows, and aggregates the result:</p><pre>Finalize GroupAggregate<br>└─ Gather Merge<br>   └─ Partial HashAggregate<br>      └─ Nested Loop<br>         ├─ Parallel Seq Scan on source_table         13.8 ms self<br>         └─ Function Scan jsonb_array_elements        57.8 ms self</pre><p>The scan was cheap. The aggregation was cheap. JSON expansion dominated — and the first fix took about five minutes to find. One expression was expanding an entire array and counting the elements just to check whether it was empty:</p><pre>-- Before<br>(SELECT count(*) FROM jsonb_array_elements(x)) &gt; 0</pre><pre>-- After<br>jsonb_array_length(x) &gt; 0</pre><p>On the 57,759 row database: <strong>92.2 ms → 60.2 ms</strong>. Rerun at three million rows a separate experiment on synthetic data shaped like production <strong>15.8 s → 8.6 s</strong>. It held at scale because it removed row generation entirely rather than accelerating it. When the answer is a scalar property of a JSON value, use the scalar operator.</p><p>A clean 35% in five minutes. Confidence: high.</p><p>That is exactly the state of mind in which you make the next mistake.</p><h3>Act two: the benchmark that reversed</h3><p>Several source columns stored JSON as text and reparsed it on every read:</p><pre>json_text_column::jsonb</pre><p>Repeated parsing on the hot path. The fix is obvious: store native jsonb. And the benchmark — development database, warm cache — agreed emphatically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XQ7pzNPhf03PZ3TSt9UYOA.png" /></figure><p>Sixty percent faster. I have shipped changes on far less evidence than this, and so have you.</p><p>Instead, I reran it at three million rows. The result reversed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*72EIhOqG3DcnqbAZ-Z4krQ.png" /></figure><p>Storage explained it. For this data shape, native jsonb was about 52% larger on disk:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7tTWnjln2G6GD7z21cYmNQ.png" /></figure><p>The warm benchmark had measured exactly one thing: the CPU cost of parsing while every relevant page sat in cache. At three million rows the working set outgrew the cache, and the larger representation bought 33,000 extra block reads. The parsing it saved no longer paid for the I/O it caused. Reverted.</p><p>This is not a verdict on jsonb the right representation depends on query patterns, indexing, and working set size. It&#39;s a verdict on the benchmark:</p><blockquote>A warm cache micro benchmark answers “how expensive is this CPU work?” Production asks a different question: “what happens when representation size starts driving physical reads?” A number that answers the first question is not evidence about the second.</blockquote><p>And the truly right fix made the whole debate irrelevant. Most consumers never needed the array at all they needed the <em>number of elements</em> in it. So the pipeline now materializes that count once, in the same transformation that produces the array (derived together, so they can never drift apart), and every consumer reads a plain integer column:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mo9Pvvnwykr6I8FryI_vMg.png" /></figure><p>Eight times faster, and the expansion query’s ~226 MB spill to temporary disk vanished with it.</p><blockquote>Eliminating data from the hot path beats parsing that data faster. The best optimization for this JSON was to stop reading it.</blockquote><h3>Act three: I stopped trusting green</h3><p>Here the investigation changed character. If a benchmark that decisive could be that wrong, what else was I taking on faith? I stopped looking at timings and started interrogating outputs. Three discoveries followed, and none of them had ever raised an error.</p><h3>The deletion query that couldn’t fail — because it couldn’t do anything</h3><p>Disappeared record detection used the classic pattern:</p><pre>WHERE target.key NOT IN (SELECT source.key FROM source)</pre><p>Now consider:</p><pre>SELECT 5 NOT IN (1, 2, NULL);   -- not TRUE. UNKNOWN.</pre><p>Under SQL’s three valued logic, a NULL in the set means the database cannot <em>prove</em> absence, so the comparison evaluates to UNKNOWN,and a WHERE clause discards UNKNOWN exactly like FALSE. One NULL key in that subquery and the query stops matching anything. It doesn&#39;t throw. It doesn&#39;t warn. It marks zero deletions, indefinitely, in a data-security pipeline whose job includes recording that sensitive data was deleted.</p><pre>WHERE NOT EXISTS (<br>  SELECT 1 FROM source WHERE source.key = target.key<br>)</pre><p>NOT EXISTS tests row existence directly, so a NULL key can&#39;t poison unrelated comparisons, and PostgreSQL plans it as a proper anti-join instead of a subplan scan. Faster <em>and</em> correct, but be clear about which one mattered.</p><h3>The incremental model that processed zero rows</h3><p>The dbt marts were incremental, filtering on a CDC watermark:</p><pre>WHERE cdc_updated_at &gt; max_processed_watermark</pre><p>Conventional. Green on every run. The number that mattered wasn’t the exit status, it was the row count behind the predicate:</p><pre>0 out of 57,759 rows selected</pre><p>_ab_cdc_updated_at was NULL on every row, because the dataset had been loaded through a full refresh path rather than CDC. And NULL &gt; timestamp is, you know this word by now, UNKNOWN. Every row excluded. The model succeeded on every run and processed nothing, and downstream marts would quietly stale until someone forced a full refresh.</p><p>The fix falls back to the source system’s own timestamp:</p><pre>coalesce(<br>  parse_epoch(_ab_cdc_updated_at),<br>  parse_epoch(updatedAt)<br>)</pre><p>The recovery run surfaced all 57,759 invisible rows; at test scale, 728,183 records newer than the watermark. The invariant worth wiring into your checks:</p><pre>rows selected incrementally ≈ rows changed since the previous watermark</pre><p>Zero can be the correct answer. It has to be <em>demonstrated</em> correct, not inferred from a green checkmark.</p><h3>The timestamps from 1970</h3><p>Validating that fallback meant actually reading the resolved values. They landed in January 1970.</p><p>The source timestamps were epoch <strong>seconds</strong> (~1.7 × 1⁰⁹). The shared parsing helper assumed every numeric epoch was <strong>milliseconds</strong>:</p><pre>to_timestamp(v / 1000)   -- epoch seconds ÷ 1000 ≈ the dawn of Unix time</pre><p>Every value came back as a structurally valid timestamp of the correct PostgreSQL type off by fifty six years. And the helper was shared, meaning every epoch second value that would ever pass through it was silently wrong. The repaired parser selects the unit by magnitude:</p><pre>CASE<br>  WHEN v &gt;= 1e14 THEN to_timestamp(v / 1e6)  -- microseconds<br>  WHEN v &gt;= 1e11 THEN to_timestamp(v / 1e3)  -- milliseconds<br>  ELSE                to_timestamp(v)        -- seconds<br>END</pre><p>Resolved values now span 2023–2026, as they should. Magnitude detection is a heuristic, prefer explicit units where you control the schema, but it beats imposing one assumption on every source you don’t.</p><blockquote><em>Validate the semantic range of transformed values, not just their types. A column full of valid timestamps can still be a column full of wrong dates.</em></blockquote><h3>Act four: the index that answered a question nobody was asking</h3><p>One last artifact of misplaced confidence. Every staging query filtered on tenant_id, so someone had done the responsible looking thing:</p><pre>CREATE INDEX ON source_table(tenant_id);</pre><p>But each tenant gets its own PostgreSQL database. One query ended the discussion:</p><pre>SELECT count(DISTINCT tenant_id) FROM source_table;<br>-- 1</pre><p>The predicate matched essentially every row. PostgreSQL had been ignoring the index all along correctly while the index kept charging rent in storage, write amplification, and vacuum work. The database boundary had already enforced tenant isolation; the index encoded a fact the architecture had made redundant. Dropped.</p><p>Index for measured cardinality and access patterns, not for columns that appear often in WHERE clauses.</p><h3>The scoreboard</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mz7x29SC-rPga4T1hXZiYQ.png" /></figure><p>(The same session also flagged ~745 MB of orphaned raw tables and a connection count peaking near 123 real findings, but not this story.)</p><h3>What I check now, by default</h3><p>For every meaningful query, EXPLAIN (ANALYZE, BUFFERS): actual versus estimated rows, temp reads and writes, buffer hits versus physical reads. For every incremental model: the row count behind the predicate, the watermark range, the NULL watermark count after <em>both</em> full refresh and CDC ingestion paths. For every timestamp transformation: plausible year ranges, not just successful casts. For every anti join over nullable keys: NOT EXISTS, with removed record counts verified independently. For every index proposal: the distinct value count first. And for every optimization: a rerun at a volume that changes the working set, because a warm cache number is a statement about CPU, not about production.</p><h3>The list is still empty</h3><p>I still have that list from the top of the article, every error these six problems produced. It hasn’t grown.</p><p>That’s the finding. The profiler tells you where the time goes; only output validation tells you whether the work is real. A green run proves your code executed. A valid type proves your cast succeeded. A decisive benchmark proves you measured <em>something</em>. None of them proves the system is right.</p><p>So when a number surprises you, a model that selects zero rows, a date in 1970, an optimization that looks too clean, don’t explain it away.</p><p>The unexpected number is not noise. It’s the article.</p><p><em>Setup, for the skeptical: baseline timings from one PostgreSQL 17 development database, warm cache, 57,759 rows. Three million row experiments used synthetic data shaped like the production JSON; its low cardinality lets </em><em>Memoize flatter some absolute expansion timings. Comparisons isolated individual query patterns rather than full end to end deployments, and the watermark fix still required a production like integration run before being called done.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46bb4030f4f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>