<?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 Deepak on Medium]]></title>
        <description><![CDATA[Stories by Deepak on Medium]]></description>
        <link>https://medium.com/@wwwdeepak?source=rss-70f28be03e07------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*KE6BJ4fOeZ9f1Vsyqf1VTw.jpeg</url>
            <title>Stories by Deepak on Medium</title>
            <link>https://medium.com/@wwwdeepak?source=rss-70f28be03e07------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 10:54:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wwwdeepak/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[The Day We Stop Checking: How AI Quietly Earns Our Trust]]></title>
            <link>https://medium.com/@wwwdeepak/the-day-we-stop-checking-how-ai-quietly-earns-our-trust-b9e6ab6b5333?source=rss-70f28be03e07------2</link>
            <guid isPermaLink="false">https://medium.com/p/b9e6ab6b5333</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[ai-agent]]></category>
            <dc:creator><![CDATA[Deepak]]></dc:creator>
            <pubDate>Tue, 13 Oct 2026 06:03:33 GMT</pubDate>
            <atom:updated>2026-10-13T06:03:33.923Z</atom:updated>
            <content:encoded><![CDATA[<p><em>What happens to the human mind when the answer is always right there, and usually correct?</em></p><h3>It starts with doubt</h3><p>The first time we hand a real task to an AI, something inside us hesitates. We write the prompt, press enter, and wait, not with excitement but with suspicion. A quiet voice says: <em>“It can’t do this as well as I can. A human would do it better.”</em></p><p>So we do what careful people do. We check everything. We read every line, run every test, and hunt for the mistake we are sure is hiding somewhere.</p><p>And then something unexpected happens. The answer is good. We try again, and it is good again. By the third time, it has even handled an edge case we forgot to mention. The suspicion does not vanish, but it softens.</p><p>This is how trust is built. Not with an announcement, but with a small, repeated experience of being right.</p><h3>Trust is a habit, not a decision</h3><p>Nobody ever decides to trust AI completely. There is no moment where we say, “From today, I will stop verifying.” It happens the way we start trusting a new colleague, a new route to work, or a new calculator.</p><p>First we check everything. Then we check most things. Then only the important things. And one day we realize that we have not checked in weeks.</p><p>The human mind loves this. Verification is expensive. It costs attention, energy, and time. Trust is cheap. It lets us move faster, and it feels comfortable. Our brain, always looking to save effort, quietly pushes us toward that comfort zone.</p><p>There is nothing wrong with that on its own. We trust doctors, pilots, and engineers without understanding their work. But there is a difference. We trust those people inside systems built on accountability, licenses, and consequences. With AI, the trust often arrives first, and the system around it arrives later, if at all.</p><h3>The quiet question: how do you know it’s correct?</h3><p>Here is the question that should keep us thinking:</p><p><strong>Once you trust the AI completely, how will you know that its solution is truly correct?</strong></p><p>You cannot verify with the same confidence you had at the start, because the habit of checking has faded. And the very tool that gave you the answer is now the easiest tool to ask, <em>“Is this right?”</em></p><p>So we ask. And sometimes we take the answer from one AI and give it to another AI to review. Two systems agree, and we feel safe.</p><p>But agreement is not the same as truth. If two systems learned from similar data, they may share the same blind spots. When both are confidently wrong in the same direction, it looks exactly like being right.</p><p>The danger is not that AI will fail often. The danger is that it will succeed so often that we stop noticing when it fails.</p><h3>Will it always be the best solution?</h3><p>No, and it does not need to be for this problem to matter.</p><p>An AI solution can be correct and still not be the <em>best</em> one. It may pass the test and still be wrong for your business. It may handle ten edge cases and miss the eleventh, the one that only appears at scale, at midnight, on the busiest day of the year.</p><p>The best solution depends on context: your users, your constraints, your history, your future. Much of that context lives in human heads, in conversations, in hard lessons from past failures. An AI can only work with what we tell it. If we stop thinking, we stop telling it the things that matter.</p><h3>What happens to the human mind?</h3><p>Think about what happened to our memory after smartphones. We stopped remembering phone numbers. We stopped remembering routes after GPS. These were small trades, and mostly worthwhile.</p><p>But judgment is not a phone number. Judgment is the ability to look at a solution and feel that something is off. It is built slowly, through years of struggle: debugging at 2 a.m., making mistakes, understanding <em>why</em> something works, not just <em>that</em> it works.</p><p>If AI does the struggle for us, we may gain speed but lose depth. We risk becoming people who can approve answers but can no longer produce them, and eventually, people who can no longer tell a good answer from a convincing one.</p><h3>Then why are we paid?</h3><p>In the IT industry, we are not paid for typing code. We never were. We are paid for the <strong>better solution</strong>, which means understanding the problem, choosing between trade-offs, anticipating failure, and taking responsibility when things break.</p><p>AI can generate options faster than any human. But someone must decide which option is right, and someone must be accountable when it is wrong. That someone cannot be the same system that produced the answer and then graded its own work.</p><p>So does the human mind still matter? More than ever, but in a different place. Less in producing, more in questioning. Less in writing the answer, more in knowing what to ask, what to doubt, and when to say, <em>“Wait, this doesn’t look right.”</em></p><h3>Trust, but keep the muscle</h3><p>The answer is not to reject AI. That would be foolish, like refusing electricity because it can shock us. The answer is to use it the way a wise person uses any powerful tool:</p><ul><li><strong>Verify in proportion to the stakes.</strong> A throwaway script needs a glance. A payment system needs a deep review.</li><li><strong>Use independent checks.</strong> Tests, real data, and human reviewers are not the same as asking another AI.</li><li><strong>Keep solving some problems yourself.</strong> Not all of them, but enough to keep your judgment sharp.</li><li><strong>Ask “why,” not just “does it work.”</strong> Understanding is the only real protection against confident mistakes.</li></ul><h3>The last thought</h3><p>AI is not capturing our trust by force. We are giving it away, one correct answer at a time, because it is comfortable and because it works.</p><p>The real question for the coming years is not <em>“Can AI be trusted?”</em> but <em>“Will we still know how to tell when it can’t?”</em></p><p>The day we stop checking is the day our own mind becomes the most important thing we have left to protect.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9e6ab6b5333" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How AI Made Me More Productive]]></title>
            <link>https://medium.com/@wwwdeepak/how-ai-made-me-more-productive-f2698c14cedf?source=rss-70f28be03e07------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2698c14cedf</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[ai-agent-development]]></category>
            <dc:creator><![CDATA[Deepak]]></dc:creator>
            <pubDate>Tue, 29 Sep 2026 02:46:01 GMT</pubDate>
            <atom:updated>2026-09-29T02:46:01.536Z</atom:updated>
            <content:encoded><![CDATA[<p><em>My journey through three stages of AI help</em></p><p>AI did not change my work all at once. It happened slowly, in stages. Each stage made my work a little easier. This is my story, told in simple words. It also matches what Cursor (a coding tool company) wrote about in their blog post “The third era of AI software development.”</p><h3>Stage 1: AI Helps Me Type</h3><p>At first, AI just helped me type. When I wrote code, it guessed the next word. Sometimes it guessed a whole line. This was like a smart spell-checker. It saved my fingers some work. But I still did all the thinking.</p><p>This stage lasted a long time — almost two years. It was simple, but it helped a lot with small, repeated work.</p><h3>Stage 2: AI Writes Small Parts For Me</h3><p>Next, AI got smarter. I could ask it to write a function, or even a full file. I would explain what I wanted, and it gave me a first draft. I checked the draft, fixed mistakes, and made it better.</p><p>This changed how I worked. I was not writing everything from zero anymore. I was reviewing and improving. But I still had to guide AI at every step. It was like talking back and forth, one step at a time.</p><h3>Stage 3: AI Finishes Whole Tasks</h3><p>Now something bigger is happening. I do not just ask AI to write one file. I give AI a full task. AI understands the goal, works on it by itself, checks its own work, and comes back when it is done.</p><p>Cursor calls this the “third era.” AI agents can now work for a long time on their own, with very little help from humans. They run on their own computer in the cloud. This means I can give AI a task and go do something else, while AI keeps working.</p><p>When AI finishes, it does not just show me code. It shows me easy things to check — like a short video, a live preview, or a summary. I do not need to read every single line anymore.</p><h3>What Changed For Me</h3><p>The biggest change is not speed. It is where I spend my attention.</p><ul><li>I spend less time on small, boring tasks (like typing or fixing simple mistakes).</li><li>I spend more time explaining what I want clearly.</li><li>I spend more time checking AI’s work, instead of doing every step myself.</li><li>I can work on many tasks at the same time, because AI handles each one on its own.</li></ul><h3>One Thing to Remember</h3><p>AI can do a lot now. But I am still responsible for the result. If AI makes a mistake, it is still my job to catch it. So I always check the work carefully, even when AI seems confident.</p><h3>In Short</h3><p>AI helped me in three steps: first with typing, then with writing small parts, and now with finishing whole tasks on its own. My job changed too. I now spend more time thinking and checking, and less time doing repeated work by hand. This has made me much more productive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2698c14cedf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How One Missing Line Made Our Database Do 200x More Work]]></title>
            <link>https://medium.com/@wwwdeepak/how-one-missing-line-made-our-database-do-200x-more-work-3990fcdb5ee4?source=rss-70f28be03e07------2</link>
            <guid isPermaLink="false">https://medium.com/p/3990fcdb5ee4</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[backend-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Deepak]]></dc:creator>
            <pubDate>Tue, 22 Sep 2026 02:46:01 GMT</pubDate>
            <atom:updated>2026-09-22T02:46:01.307Z</atom:updated>
            <content:encoded><![CDATA[<h3>A production story about batch processing, quadratic growth, and why “works in dev” isn’t enough</h3><p>I have almost four years of experience as a backend engineer, and this is the kind of bug I wish someone had warned me about earlier. It was one missing line of code. It passed dev, it passed testing, and then in production it slowed down our processing job and put heavy pressure on our database.</p><p>If you write batch jobs, this one is worth five minutes of your time.</p><p>TL;DR: I forgot to reset a batch buffer after saving it. Each save re-sent all previous records plus new ones, turning linear work into quadratic work. Idempotent upserts hid the bug by keeping the data correct while performance collapsed.</p><h3>The job</h3><p>We had a Node.js job that processed a large volume of records. The logic was simple:</p><ol><li>Fetch records in a while loop.</li><li>Add each record to an in-memory batch.</li><li>Every 250 records, write the batch to the database (insert, or update if the row already exists).</li><li>Repeat until there is no more data.</li></ol><p>Here is a simplified version of the code:</p><pre>let batch = [];<br>while (await hasMoreData()) {<br>  const record = await fetchNextRecord();<br>  batch.push(record);<br><br>  if (batch.length % 250 === 0) {<br>    await saveToDatabase(batch); // insert or update<br>    // ❌ batch is never reset here<br>  }<br>}</pre><p>Nothing about this looks alarming at a glance, which is exactly why it got through.</p><h3>The mistake</h3><p>I never cleared batch after saving it. So instead of sending 250 fresh records each time, the job sent:</p><p>Flush #Should sendActually sent12502502250500325075042501,000102502,500</p><p>Every flush re-sent everything from all previous flushes, plus the new records. On the database side, that meant:</p><ul><li>Flush 1: 250 inserts</li><li>Flush 2: 250 updates (old rows) + 250 inserts (new rows)</li><li>Flush 3: 500 updates + 250 inserts</li><li>…and so on</li></ul><p>Each batch redid the work of every batch before it.</p><h3>Why this gets dangerous so fast</h3><p>This is quadratic growth, not linear.</p><p>If you process N records in batches of size B, you should write N rows in total. With the missing reset, the total becomes:</p><pre>B × (1 + 2 + 3 + ... + k) = B × k(k+1) / 2</pre><p>where k = N / B is the number of batches.</p><p>Take 100,000 records with a batch size of 250:</p><ul><li>Number of batches: 400</li><li>Rows that should be written: 100,000</li><li>Rows actually written: 250 × 400 × 401 / 2 = 20,050,000</li></ul><p>That is roughly 200x more work for the database, caused by one missing line. Memory usage in the Node process also grows, because the array never shrinks.</p><p><em>(These numbers are a worked example to show the shape of the problem, not measurements from our incident. The ratio grows with the number of batches: the more data you process, the worse it gets.)</em></p><h3>Why dev never caught it</h3><p>Three things combined to hide the bug:</p><p>1. Small data. Our dev environment had a few hundred records, so the job flushed once or twice. A single flush hides this bug completely, because there is nothing left over to re-send.</p><p>2. A fast local database. Even thousands of redundant writes finish instantly on a local machine with no network latency and no other traffic.</p><p>3. Idempotent writes. Because we used upserts, duplicates did not throw errors. The final data was correct, just far more expensive to produce. This was a <em>performance</em> bug, not a <em>correctness</em> bug, so no test failed.</p><p>That third point is the one that stayed with me. Idempotency is a great safety property, but it also removes a noisy failure that would have exposed the bug immediately. If the duplicates had caused unique-constraint errors, we would have found the problem on day one.</p><h3>What it looked like in production</h3><p>The symptom was a job that got slower the longer it ran. The first batches were fast, and every batch after that took longer than the last.</p><p>Around the job, we saw:</p><ul><li>Database CPU and I/O climbing from millions of unnecessary writes. Upserts on existing rows still cost real work: index lookups, row updates, and write-ahead logging.</li><li>Larger transactions holding locks for longer, since each flush touched more and more rows.</li><li>Other queries slowing down, because our job was competing with everything else on the same database.</li><li>Growing memory usage in the application as the buffer grew.</li></ul><p>That “slower with every batch” pattern was the clue. A healthy batch job should take roughly the same time per batch. When batch time keeps climbing, something is accumulating, and that pointed me straight at the buffer.</p><h3>The fix</h3><p>Reset the buffer after every successful save, and don’t forget the final partial batch:</p><pre>const BATCH_SIZE = 250;<br>let batch = [];<br>while (await hasMoreData()) {<br>  batch.push(await fetchNextRecord());<br><br>  if (batch.length &gt;= BATCH_SIZE) {<br>    await saveToDatabase(batch);<br>    batch = []; // ✅ reset after every flush<br>  }<br>}<br>if (batch.length &gt; 0) {<br>  await saveToDatabase(batch); // final partial batch<br>}</pre><p>Two JavaScript details are worth knowing here:</p><ul><li>Always await the save before resetting. If you reset without awaiting, you can replace the buffer while the write is still in flight and lose track of what was actually saved.</li><li>Prefer batch = [] over batch.length = 0. Assigning a new array means a slow save keeps its own copy of the data. Clearing in place mutates the same array that an in-flight write may still be reading.</li></ul><h3>Making the mistake hard to repeat</h3><p>A fix that relies on remembering to reset a variable is only as good as the next code review. So I also moved to an async generator that produces fixed-size chunks:</p><pre>async function* chunked(asyncIterable, size) {<br>  let chunk = [];</pre><pre>  for await (const item of asyncIterable) {<br>    chunk.push(item);</pre><pre>    if (chunk.length === size) {<br>      yield chunk;<br>      chunk = [];<br>    }<br>  }</pre><pre>  if (chunk.length &gt; 0) {<br>    yield chunk;<br>  }<br>}</pre><pre>for await (const chunk of chunked(fetchRecords(), 250)) {<br>  await saveToDatabase(chunk);<br>}</pre><p>Now there is no long-lived buffer in the business logic. Every chunk is a fresh array, so state cannot leak between iterations. The batching concern lives in one small, testable function instead of being repeated in every job.</p><h3>What we changed in how we work</h3><p>I don’t want to give you a generic list of best practices. These are the three things we actually adopted.</p><h3>1. Test with more than one batch</h3><p>In tests, set the batch size to 2 or 3 and feed in 10 records. Any bug that depends on multiple flushes shows up immediately.</p><h3>2. Assert that rows written equals rows processed</h3><p>This is the check that would have caught the bug on day one, even though the final data looked correct:</p><pre>test(&#39;each record is saved exactly once&#39;, async () =&gt; {<br>  const saved = [];<br>  const saveToDatabase = jest.fn(async (rows) =&gt; saved.push(...rows));<br>  await processRecords(makeRecords(10), { batchSize: 3, saveToDatabase });<br><br>  expect(saved).toHaveLength(10);                  // written == processed<br>  expect(saveToDatabase).toHaveBeenCalledTimes(4); // 3 + 3 + 3 + 1<br>});</pre><p>Notice that this test asserts on <em>how much work was done</em>, not just on the final state. That distinction matters for any system where writes are idempotent.</p><h3>3. Log batch size and duration</h3><p>One line makes a growing batch obvious at a glance:</p><pre>console.log(`Saved batch #${batchNo} with ${batch.length} records in ${ms}ms`);</pre><p>If I had seen Saved batch #12 with 3,000 records in the logs, I would have spotted the problem in seconds. It&#39;s also worth alerting on batch duration trends, since a batch that gets slower every iteration is a red flag.</p><h3>What I took away from this</h3><ul><li>A missing reset turns linear work into quadratic work. Small mistakes inside loops scale with your data, not with your intentions.</li><li>Idempotent writes can hide bugs. They keep the data correct while performance quietly collapses, so test the amount of work done, not just the outcome.</li><li>“Works in dev” only proves the code works at dev scale. Always ask what changes at 100x the data.</li><li>Review accumulating state on purpose. Whenever I review a loop that builds up a variable, I now ask one question: <em>what survives between iterations, and should it?</em></li></ul><p>It was a small mistake, but the fixes around it, better tests, better logging, and better review habits, made our whole team stronger. The bug itself was one line. The lesson was much bigger.</p><p><em>Have you ever been bitten by a bug that only appeared at scale? I’d love to hear about it in the comments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3990fcdb5ee4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My PostgreSQL Table Kept Growing Even Though I Was Deleting Rows — Here’s Why]]></title>
            <link>https://medium.com/@wwwdeepak/my-postgresql-table-kept-growing-even-though-i-was-deleting-rows-heres-why-0ab408fdf143?source=rss-70f28be03e07------2</link>
            <guid isPermaLink="false">https://medium.com/p/0ab408fdf143</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[system-design-interview]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Deepak]]></dc:creator>
            <pubDate>Tue, 15 Sep 2026 07:18:18 GMT</pubDate>
            <atom:updated>2026-09-15T07:18:18.133Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Your table used to be fast. Now every query on it feels slower, the disk usage keeps climbing, and nothing in your code changed — here’s why.</em></p><p>In Part 1 of the MVCC series, we learned that PostgreSQL never updates a row in place. Every UPDATE creates a new row version and marks the old one as dead — but doesn&#39;t delete it. In Part 3, we saw how DELETE works the same way: the old row just gets flagged, not removed.</p><p>So here’s the obvious question nobody asks until their database starts slowing down:</p><p><strong>Where do all those dead row versions go?</strong></p><p>The answer is: nowhere, until something cleans them up. That something is VACUUM.</p><h3>The problem VACUUM solves</h3><p>Every table in PostgreSQL is really a growing pile of row versions. Live ones and dead ones sit in the same pages on disk. Nothing removes the dead ones automatically the moment they become dead — PostgreSQL just marks them and moves on, because reclaiming space immediately would mean blocking or rewriting pages on every single UPDATE and DELETE, which would be far too slow.</p><p>Instead, PostgreSQL defers that cleanup. Over time, if nothing runs the cleanup, you get:</p><ul><li><strong>Table bloat</strong> — the table on disk grows much larger than the data it actually holds, because dead versions pile up alongside live rows.</li><li><strong>Index bloat</strong> — indexes keep pointers to dead row versions too, so they grow and get slower to scan.</li><li><strong>Wasted I/O</strong> — every sequential scan or index scan has to skip over dead rows to find live ones, which means more disk pages read for the same amount of useful data.</li><li><strong>Transaction ID wraparound risk</strong> — PostgreSQL’s MVCC system uses a 32-bit transaction ID that can wrap around if it’s never “frozen.” In extreme, neglected cases this can force the database into a read-only state to protect data integrity.</li></ul><p>VACUUM exists to reclaim that dead space, keep indexes efficient, and prevent wraparound before it becomes an emergency.</p><h3>What VACUUM actually does</h3><p>Plain VACUUM (without FULL) does three main things:</p><ol><li><strong>Marks dead tuples as reusable.</strong> It scans the table, finds row versions no longer visible to any active transaction, and marks their space as free — but it doesn’t shrink the file on disk. Future INSERTs and UPDATEs can reuse that space instead of extending the table.</li><li><strong>Updates the visibility map.</strong> This map tells PostgreSQL which pages contain only live, all-visible rows. Pages marked this way can be skipped by index-only scans and future vacuum runs, which is a major speed win.</li><li><strong>Freezes old transaction IDs.</strong> It marks very old rows as “frozen” so PostgreSQL doesn’t need to keep comparing their transaction ID against the wraparound limit. This is the mechanism that actually prevents the wraparound crisis mentioned above.</li></ol><p>What it does <em>not</em> do: shrink the file size on disk. That space is marked reusable internally, but the table’s footprint on disk stays the same size until something more aggressive runs.</p><h3>VACUUM vs VACUUM FULL</h3><p>This is the part that trips people up.</p><p>VACUUM VACUUM FULL Reclaims space to OS No — marks space as reusable internally Yes — rewrites the table into a new, smaller file Locking Runs concurrently with normal reads/writes Takes an ACCESS EXCLUSIVE lock — blocks everything Typical use Routine maintenance Rare, planned downtime after major bloat or bulk deletes Speed Fast, incremental Slow, rewrites the whole table</p><p>In practice, you almost never want to reach for VACUUM FULL on a production table without a maintenance window. It works by building an entirely new copy of the table and swapping it in, which means it needs roughly double the disk space temporarily and locks out reads and writes for the duration.</p><p>Plain VACUUM is the one that matters day to day — and mostly, you don&#39;t even run it manually.</p><h3>Autovacuum: the process actually doing the work</h3><p>PostgreSQL ships with <strong>autovacuum</strong>, a background process that watches every table and triggers a VACUUM (and ANALYZE) automatically once enough rows have changed. For most workloads, this is sufficient and you never think about it.</p><p>Autovacuum decides when to act using two thresholds, roughly:</p><pre>dead_tuples &gt; vacuum_threshold + vacuum_scale_factor * total_rows</pre><p>By default, vacuum_scale_factor is 0.2 — meaning a table needs about 20% of its rows to be dead before autovacuum bothers with it. That default is tuned for small-to-medium tables. On a table with 500 million rows, waiting for 20% (100 million) dead rows before cleaning up is a recipe for exactly the bloat problem VACUUM exists to prevent.</p><p>This is the single most common real-world tuning mistake: leaving default autovacuum settings on large, high-churn tables, and then wondering why queries have gotten slower over the months.</p><h3>When autovacuum isn’t enough</h3><p>A few situations where manual intervention or tuning actually matters:</p><ul><li><strong>Large tables with high write/update volume.</strong> Lower autovacuum_vacuum_scale_factor for these specific tables (via ALTER TABLE ... SET) so cleanup happens more often, in smaller increments, instead of one huge catch-up run.</li><li><strong>Long-running transactions.</strong> An open transaction — even an idle one sitting in IDLE IN TRANSACTION — prevents VACUUM from cleaning up any row version newer than that transaction&#39;s start. This is a very common, very quiet cause of runaway bloat: one forgotten connection can block cleanup across the whole table.</li><li><strong>Bulk deletes or archiving jobs.</strong> After deleting a large chunk of a table, dead tuples spike all at once. It’s often worth triggering a manual VACUUM (or VACUUM ANALYZE) right after, rather than waiting for the next autovacuum cycle.</li><li><strong>Approaching transaction ID wraparound.</strong> PostgreSQL will start logging aggressive warnings as the oldest unfrozen transaction ID gets close to the wraparound limit. At that point, autovacuum switches into “wraparound protection” mode automatically — but if it’s been prevented from running (see long-running transactions above), this is the point where a database can eventually be forced into read-only mode. Worth monitoring age(datfrozenxid) before it ever gets close.</li></ul><h3>A practical way to see it for yourself</h3><pre>-- Check dead tuple counts per table<br>SELECT relname, n_live_tup, n_dead_tup,<br>       round(n_dead_tup::numeric / GREATEST(n_live_tup, 1) * 100, 2) AS dead_pct<br>FROM pg_stat_user_tables<br>ORDER BY n_dead_tup DESC<br>LIMIT 10;</pre><pre>-- Check when a table was last vacuumed / autovacuumed<br>SELECT relname, last_vacuum, last_autovacuum<br>FROM pg_stat_user_tables<br>ORDER BY last_autovacuum NULLS FIRST;</pre><pre>-- Check how close a database is to transaction ID wraparound<br>SELECT datname, age(datfrozenxid) AS xid_age<br>FROM pg_database<br>ORDER BY xid_age DESC;</pre><p>Running these on a production database for the first time is often eye-opening — it’s common to find a handful of tables with 30–40% dead tuples quietly dragging down every query that touches them.</p><h3>Tying it back to MVCC</h3><p>This is really the missing piece from the earlier MVCC posts: PostgreSQL’s whole approach to concurrency depends on keeping old row versions around so that other transactions can still see a consistent snapshot. That’s what makes MVCC fast and lock-free for readers. But it also means someone has to clean up afterward — and that someone is VACUUM.</p><p>Understanding VACUUM isn’t just trivia. It’s the other half of understanding why PostgreSQL performs the way it does under real, sustained write load — and it’s usually the first place to look when a table that used to be fast slowly stops being fast for no obvious reason.</p><p><em>This is a natural follow-up to the “What Really Happens When You Run UPDATE in PostgreSQL” series. If you found the MVCC internals useful, understanding VACUUM is the piece that closes the loop.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0ab408fdf143" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Deleted 90% of Our Error Logs. Here’s Why That Fixed Everything]]></title>
            <link>https://medium.com/@wwwdeepak/i-deleted-90-of-our-error-logs-heres-why-that-fixed-everything-0e2d464e5841?source=rss-70f28be03e07------2</link>
            <guid isPermaLink="false">https://medium.com/p/0e2d464e5841</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Deepak]]></dc:creator>
            <pubDate>Tue, 08 Sep 2026 02:46:00 GMT</pubDate>
            <atom:updated>2026-09-08T02:46:00.920Z</atom:updated>
            <content:encoded><![CDATA[<p>For a long time, our background jobs printed a lot of logs. “Job started.” “Batch processed.” “Shop paused.” “Request failed.” “Collection missing.” They all looked the same. Same style, same tone, same fake urgency.</p><p>So when something really broke, we didn’t spot it by reading a clear error. We found it by scrolling and scrolling until a line just <em>felt</em> wrong.</p><p>That was the real problem. We didn’t need more logs. We needed <strong>signal</strong> — logs that actually told us what mattered.</p><p>Here’s what I changed, why it helped, and what I learned.</p><h3>The problem I had</h3><p>Our workers talk to an outside API, move through queues, and write a status back so a merchant can see if a job worked or not.</p><p>Three things were mixed up together:</p><ol><li><strong>Too much noise.</strong> Small debug details used the same level as “job is done.”</li><li><strong>Confusing labels.</strong> Real failures were often marked as “info.” Normal skips and waits looked like crashes.</li><li><strong>One message, two readers.</strong> Engineers needed a code they could search for. Merchants needed a sentence they could understand. We were cramming both into one field.</li></ol><p>The worst part: the screen showed an internal code that looked like a computer error, while the real explanation was hidden somewhere else. Support would ask “what failed?” and the answer was basically “depends where you look.”</p><h3>Fix 1 — Use log levels the right way</h3><p>Our logging tool already had levels: error, warn, info, debug. We just weren’t using them properly.</p><p>I turned levels on and started using the right one for each situation:</p><ul><li><strong>error</strong> — the job actually failed, or something broke unexpectedly</li><li><strong>warn</strong> — the job kept going, but something looked off (shop was down, a dependency wasn’t ready, a normal skip)</li><li><strong>info</strong> — normal life-cycle events: job started, job finished, a decision the merchant should know about</li><li><strong>debug</strong> — extra details we only need when hunting down a tricky bug</li></ul><p>This sounds simple, but it changed everything. Once debug is only used for debugging, the production logs stop filling up with junk. Once warn means “something’s a bit off,” a normal skip stops looking like a fire. Once error is only used for real failures, we can search logs and actually trust what we find.</p><p>I also stopped repeating the level inside the log message itself. The tool already shows [ERROR] or [WARN] at the start of the line. Writing it again inside the message was just extra noise.</p><h3>Fix 2 — Give every known failure a clear name</h3><p>Just writing Error(&quot;something went wrong&quot;) doesn&#39;t help anyone.</p><p>So I built a small list of known failures. Each one has:</p><ul><li>a <strong>code</strong> (short, for engineers to search)</li><li>a <strong>message</strong> (plain English, for people to read)</li><li>a <strong>severity</strong> (how serious it is)</li></ul><p>For engineers For everyday users A short code they can search A sentence that explains what happened Function name, shop, extra details No stack traces, no technical dumps Lives in the logs Lives in the job’s “failed reason”</p><p>If an outside system tells us exactly what went wrong, we keep that message and show it to the user. The code still tells engineers what type of problem it was.</p><p>For example: the product should show something like “This collection doesn’t exist,” not a strange internal code. The log still keeps the code, so engineers can search for it later.</p><h3>Fix 3 — Not all failures are the same type</h3><p>This was the big lesson.</p><p>When we talk to an outside API, it can fail in two very different ways:</p><ol><li><strong>The connection failed.</strong> Timeout, no response, server error. We simply couldn’t finish the request. The fix: try again, wait a bit, check if the other service is down.</li><li><strong>The other system said “no.”</strong> Bad input, missing item, not allowed. This isn’t a connection problem. Trying again 10 times won’t bring back something that was deleted.</li></ol><p>We used to lump both of these into one generic “job failed” message. Now they’re separate. This isn’t just for neatness — it changes what you actually do when something breaks at 2 a.m.</p><p>If something is missing, the job should fail clearly and say so. If a shop is temporarily down, that’s a warning, not a crash. If two jobs can’t run at the same time, that’s expected — not a bug.</p><p><strong>The seriousness of an error is part of the error itself. It’s not something you guess later.</strong></p><h3>Fix 4 — Don’t show internal details to users</h3><p>The “failed reason” on a job is something merchants and support staff actually read. It’s part of the product.</p><p>Before, we had it backwards — the internal code was shown to the user, and the real explanation was hidden in a notes field. Now:</p><ul><li><strong>Failed reason</strong> = the plain message people can understand</li><li><strong>Logs</strong> = the code, function name, shop, and extra details</li><li><strong>Notes</strong> = not a place to repeat the same error twice</li></ul><p>The code was never meant for users to see. It was meant to be searched by engineers.</p><h3>What got better</h3><ul><li><strong>Faster to find problems.</strong> Filtering by [ERROR] shows real failures right away. Searching a code takes us straight to where it happened.</li><li><strong>Less false alarm.</strong> A job waiting for another job, or a shop that’s down, now shows as a warning — not something that looks like a bug.</li><li><strong>Support can explain things.</strong> “This collection no longer exists” makes sense to a person. An internal code doesn’t.</li><li><strong>Debug logs are optional again.</strong> They still exist, but they don’t clutter production unless we turn them on.</li><li><strong>Nothing gets lost.</strong> Any error we haven’t listed yet still gets caught and logged, with the original message saved. We don’t need to invent a new format every time.</li></ul><h3>What I learned</h3><ul><li><strong>Logging is a product choice, not just a technical detail.</strong> If everything is marked “info,” you don’t really have useful logs — just a diary.</li><li><strong>Every error needs two versions.</strong> A code for engineers. A message for people. Using one string for both makes both worse.</li><li><strong>Don’t print full stack traces by default.</strong> A function name and a code are usually enough to find the problem. Stack traces are for debugging, not everyday logs — and they’re often huge.</li><li><strong>Keep the other system’s error message when you get one.</strong> It’s usually more useful than anything generic we could write ourselves.</li><li><strong>Be honest with your log levels.</strong> If you catch an error and still log it as “info,” people will learn to ignore info logs completely. Catching an error doesn’t make it harmless.</li><li><strong>Short and structured beats long and messy.</strong> A small, clear JSON message beats a giant stack trace almost every time.</li><li><strong>Logs and the user interface are not the same thing.</strong> If you show users the same thing you log internally, users see too much — and engineers often don’t get what they actually need.</li></ul><h3>What I’d do differently next time</h3><p>I’d build the list of known errors <em>before</em> the number of jobs grew. Once you have dozens of workers, every error message becomes its own special case.</p><p>I’d also decide early on what counts as an error, what counts as a warning, and what counts as a normal skip. That’s a much easier decision to make early, on a whiteboard, than to fix later inside messy code.</p><p>The real fix here wasn’t a new tool. We already had everything we needed. The fix was agreeing on clear names, thinking about who reads what, and being consistent — so a log line always means the same thing.</p><p>That’s the real improvement. Not more logs. Logs you can actually trust.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0e2d464e5841" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Things I Wish Someone Told Me Earlier About Writing Database Queries]]></title>
            <link>https://medium.com/@wwwdeepak/5-things-i-wish-someone-told-me-earlier-about-writing-database-queries-2043471c8be9?source=rss-70f28be03e07------2</link>
            <guid isPermaLink="false">https://medium.com/p/2043471c8be9</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Deepak]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 03:01:02 GMT</pubDate>
            <atom:updated>2026-09-01T03:01:02.888Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been writing SQL for a while now, and looking back, most of the painful lessons I learned came from the same handful of mistakes. Not exotic bugs. Not weird edge cases. Just the basics that nobody sits you down and explains until something breaks in production.</p><p>So here are the five things that actually matter, in my experience, when you’re writing queries.</p><h3>1. Stop typing your variables straight into the query</h3><p>This is the one everyone warns you about, and for good reason. If you’re building a query by gluing strings together, especially with anything coming from a user, you are one bad input away from a very bad day.</p><pre>&quot;SELECT * FROM users WHERE email = &#39;&quot; + email + &quot;&#39;&quot;</pre><p>Looks harmless. It isn’t. Someone can type something into that email field that turns your query into something you never intended it to run. The fix isn’t complicated either — use parameterized queries or prepared statements. Let the database driver handle the escaping instead of doing it yourself. I’ve seen this exact mistake in real codebases more times than I’d like to admit.</p><h3>2. Don’t grab everything just because it’s easy</h3><p>SELECT * feels natural when you&#39;re writing a query fast, especially early on. But it quietly costs you later. You end up pulling columns you don&#39;t need, dragging more data across the network than necessary, and sometimes exposing fields that really shouldn&#39;t be sitting in an API response — think internal flags, timestamps nobody asked for, or worse.</p><p>Just write out the columns you actually need. It takes an extra ten seconds and saves you from a lot of confusion down the line, especially when someone adds a new column to the table six months later and your query silently starts returning it too.</p><h3>3. Indexes aren’t free, so don’t throw them at everything</h3><p>When a query is running slow, the instinct is to add an index and move on. Sometimes that’s the right call. But indexes come with a cost too — every insert or update now has to update that index as well, and if you’ve got ten indexes on a heavily written table, you’ll feel it.</p><p>A good rule of thumb: index the columns you’re filtering on, joining on, or sorting by often. Not every column. And when something feels slow, don’t guess — run an EXPLAIN on it and actually look at what the database is doing. It&#39;s usually more revealing than people expect.</p><h3>4. Watch out for the “one query per row” trap</h3><p>This one sneaks up on people, especially when using an ORM. You fetch a list of a hundred users, and then for each user, you fire off another query to grab their orders. Suddenly you’ve run 101 queries to do what could’ve been done in two.</p><p>It’s called the N+1 problem, and it’s probably one of the most common performance issues I’ve come across in real applications. The fix is usually a join or a batch fetch instead of looping and querying inside the loop. Worth checking for anytime a page or endpoint feels slower than it should be.</p><h3>5. NULL doesn’t play by normal rules</h3><p>This trips people up constantly. You’d think WHERE column = NULL would work the way you expect, but it doesn&#39;t — it just won&#39;t match anything, ever. You need IS NULL instead. Same logic applies when NULLs show up in joins or in aggregate functions like SUM or AVG, where they get quietly ignored instead of throwing an error.</p><p>It’s a small thing, but it’s caused more silent bugs than I can count — the kind where the query runs fine, returns a result, and that result is just wrong.</p><p>None of these are complicated once you know them. That’s kind of the point — they’re not advanced tricks, just habits that save you from debugging something at 2am that you could’ve avoided from the start.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2043471c8be9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[We Increased Our Database Storage to Fix an Error. It Didn’t Work. Here’s What Actually Fixed It.]]></title>
            <link>https://medium.com/@wwwdeepak/we-increased-our-database-storage-to-fix-an-error-it-didnt-work-here-s-what-actually-fixed-it-20caf8fc0e97?source=rss-70f28be03e07------2</link>
            <guid isPermaLink="false">https://medium.com/p/20caf8fc0e97</guid>
            <category><![CDATA[dataset]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Deepak]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 03:01:03 GMT</pubDate>
            <atom:updated>2026-08-25T06:51:03.374Z</atom:updated>
            <content:encoded><![CDATA[<p>Everyone on my team agreed on the fix. The database was filling up, the errors were piling up, so we’d add more storage and move on.</p><p>I couldn’t shake the feeling that we were wrong.</p><p>Turns out, the real problem was hiding in a metric almost nobody checks first — and once I found it, everything about our “random” job failures suddenly made sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3a5Nj-a5TrNHErYCKEzjmg.png" /></figure><h3>How We Got Here</h3><p>Our platform stores product catalogs for Shopify stores. As we added more merchants, one table kept growing faster than everything else: products. Some stores have tens of thousands of products, and across all our clients, that table became the biggest thing in our database by far.</p><p>So we did what most teams do at this point: we split it out. We created a second, dedicated database just for products and catalog data. Then we made a plan to move our clients over slowly, one batch at a time, so we could catch problems early instead of breaking everything at once.</p><p>Good plan. We did catch problems early. Just not the ones we expected.</p><h3>Something Was Breaking, and It Kept Getting Worse</h3><p>As we moved more clients to the new database, our background jobs started failing. Not all at once — just a little more each day. And the pattern was too obvious to miss: the more clients we migrated, the more jobs broke.</p><p>More migration, more failures. Every time.</p><p>The error in our logs was a <strong>connection termination error</strong> — basically, the database was cutting off connections mid-request. And if you’ve dealt with this error before, you probably jump to the same suspect I did: storage.</p><h3>Everyone Blamed Storage. I Wasn’t So Sure.</h3><p>Our database storage was at 60% full. The team’s instinct was simple: storage is climbing, connections are dropping, let’s just increase storage and move on. It made sense on the surface.</p><p>But something didn’t add up for me. From past experience, storage-related connection problems on Azure usually start showing up once you cross around 80% — not 60%. We were nowhere close to that number, and yet the errors were already there.</p><p>So instead of just going with the team’s fix, I decided to dig into the actual numbers first.</p><h3>Checking Every Metric, One by One</h3><p>CPU: normal. RAM: normal. Storage: 60%, going up slowly, but nothing alarming.</p><p>Nothing looked wrong. And that’s the most frustrating place to be — every dashboard says “everything’s fine,” but your production system is clearly not fine.</p><p>So I kept looking, and opened a metric I usually never paid much attention to: <strong>IOPS</strong>.</p><p>It was stuck at 100%. Not spiking now and then — just sitting maxed out, all the time.</p><h3>Wait, What Even Is IOPS?</h3><p>I had to look this up properly too, so let me keep it simple.</p><p>IOPS stands for <strong>Input/Output Operations Per Second</strong>. In plain words: it’s how many read and write operations your database’s disk can handle every second. Not how much data it can <em>store</em> — how many operations it can <em>do</em>, per second.</p><p>Every Azure database comes with a limit on this, completely separate from CPU, RAM, and storage space. So you could have tons of free disk space and a completely idle CPU, and still get throttled hard — because you’re asking the disk to do more operations per second than it’s allowed to.</p><p>This is exactly why it’s so easy to miss. We’re used to watching CPU and RAM because that’s usually where problems show up. We watch storage space because running out of disk is an obvious, scary problem. But IOPS just sits quietly in the background — until you hit a limit you didn’t even know existed, and then every request past that limit starts queuing up, timing out, or getting dropped.</p><p>Here’s what was actually happening to us: as we moved more clients to the new database, every one of their background jobs started hitting that database directly. More reads, more writes, more small operations happening at the same time, every second. The catalog data wasn’t just bigger — it was <em>busier</em>. And our IOPS limit was never sized for that much activity.</p><p>So every client we migrated pushed us closer to that limit, until we blew right past it. Our connections weren’t dying because the database was full. They were dying because the disk couldn’t keep up with <em>how fast</em> we were hitting it — so it started cutting connections off.</p><h3>The Actual Fix</h3><p>We increased the IOPS limit on our database. Not the storage size — the operations-per-second limit.</p><p>The jobs stopped failing almost right away.</p><p>We did increase storage eventually too, because we genuinely needed more space down the line. But that had nothing to do with fixing our connection errors. IOPS was the whole story.</p><h3>What I Actually Learned From This</h3><p>The technical takeaway is simple: <strong>when your database load is growing, check IOPS just as closely as CPU, RAM, and storage.</strong> It’s easy to forget about, but it’s often the first thing to hit a wall when you’re increasing <em>how fast</em> things happen, not just <em>how much</em> data you’re storing.</p><p>But the bigger lesson is about how we debug problems in general. It’s tempting to go with the fix that matches something you’ve seen before — “connection errors, storage is climbing, let’s add storage.” That kind of pattern-matching is fast, and it’s usually right. But when something doesn’t quite add up, when your gut says “this doesn’t feel right,” it’s worth spending the extra hour checking things properly instead of trusting the first answer that sounds reasonable.</p><p>That one hour saved us from spending money and time on a fix that wouldn’t have worked, while the real problem kept getting worse with every client we moved.</p><p>So next time your database “feels slow” and CPU, RAM, and storage all look fine — go check IOPS. It might be the one thing quietly screaming while everything else looks calm.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20caf8fc0e97" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Looping Over Your Database Calls: What Batching Taught Me About Scale]]></title>
            <link>https://medium.com/@wwwdeepak/stop-looping-over-your-database-calls-what-batching-taught-me-about-scale-7f798010a2e8?source=rss-70f28be03e07------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f798010a2e8</guid>
            <category><![CDATA[software]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[batch-processing]]></category>
            <dc:creator><![CDATA[Deepak]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 06:05:08 GMT</pubDate>
            <atom:updated>2026-08-19T06:25:02.539Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWPJ6eKar_rGXjRuAoGlPA.png" /></figure><p><em>A few production incidents, a lot of query plans, and the one habit that separates code that works from code that survives real traffic.</em></p><p>I’ve been a backend engineer for about 4 years now. If you ask me the most common reason a job suddenly goes from “takes 4 seconds” to “takes 40 minutes,” I have one answer: somewhere, someone wrote a loop around a database call.</p><p>This is not a beginner mistake. I’ve seen it from senior engineers. I’ve seen it in my own code from a few years back. It looks fine. It passes tests. It just doesn’t scale. And that gap — between “it works” and “it scales” — is where a lot of production problems start.</p><p>This is the article I wish someone gave me early in my career, before I learned it the hard way at 2 a.m., staring at a stuck job.</p><h3>The Loop That Looked Fine in Code Review</h3><p>Here’s a simplified version of some code I once approved in a PR — and later regretted:</p><pre>for (const user of usersToNotify) {<br>  await db.query(<br>    &quot;UPDATE users SET last_notified_at = $1 WHERE id = $2&quot;,<br>    [now, user.id]<br>  );<br>}</pre><p>Simple. Easy to read. Passes all tests. In staging, with 200 test users, it runs in under a second. Nobody notices anything wrong.</p><p>Then marketing sends a campaign to 800,000 users. This same loop, running quietly inside a background job, now takes minutes. Then it takes longer. It holds a database connection open so long that other parts of the system start timing out.</p><p>The code didn’t get slower. The size of the job changed. And the code was never built to handle that size. This is the lesson that took me a while to really get: every database call has a fixed cost, no matter how small the data is. If you ignore that cost, it will eventually take over your whole runtime.</p><h3>The Hidden Cost Behind Every Database Call</h3><p>When I actually sat down and measured one of these slow jobs instead of guessing, the numbers were eye-opening. For one simple UPDATE on one row, here&#39;s where the time goes:</p><ul><li><strong>Network round trip</strong>: Your app sends the request, the database replies. This usually takes 0.5–2ms, even for a tiny query. It gets worse if your app and database are in different regions.</li><li><strong>Transaction overhead</strong>: The database has to start a transaction, write a log entry, and commit — every single time, even if the actual change takes almost no time at all.</li><li><strong>Query parsing</strong>: Small, but not zero. Paid every single call.</li><li><strong>Locks</strong>: Cheap one at a time. Expensive when you’re doing thousands of them under load.</li></ul><p>None of this depends on how much data you’re touching. It depends on <strong>how many times you talk to the database</strong>. That’s the shift in thinking that changed how I write code. I stopped asking “is this query fast?” and started asking “how many round trips is this actually making?”</p><h3>Doing the Math</h3><p>For that notification job, here’s roughly what the numbers looked like:</p><p>Approach Rows Round trips Rough total time One UPDATE per user 800,000 800,000 ~25–45 minutes Batched updates (2,000 per batch) 800,000 ~400 ~15–30 seconds</p><p>This is not a small improvement. This is the difference between “nobody notices” and “someone gets paged at night.” And it didn’t cost more servers or more money — just a different way of writing the same query.</p><h3>Writing It the Right Way</h3><p>Here’s the fix, using a simple batching helper:</p><pre>const BATCH_SIZE = 2000;</pre><pre>function chunk&lt;T&gt;(items: T[], size: number): T[][] {<br>  const result: T[][] = [];<br>  for (let i = 0; i &lt; items.length; i += size) {<br>    result.push(items.slice(i, i + size));<br>  }<br>  return result;<br>}</pre><pre>for (const batch of chunk(usersToNotify, BATCH_SIZE)) {<br>  const ids = batch.map(u =&gt; u.id);<br>  await db.query(<br>    &quot;UPDATE users SET last_notified_at = $1 WHERE id = ANY($2)&quot;,<br>    [now, ids]<br>  );<br>}</pre><p>Same result as before. But instead of 800,000 database calls, this makes about 400. That’s the whole trick — fewer trips, same amount of work.</p><p>Here’s another common example: inserting many rows at once instead of one by one.</p><pre>// Slow: one insert per order<br>for (const order of newOrders) {<br>  await db.query(<br>    &quot;INSERT INTO orders (user_id, amount) VALUES ($1, $2)&quot;,<br>    [order.userId, order.amount]<br>  );<br>}</pre><pre>// Fast: one insert for the whole batch<br>const values = newOrdersk<br>  .map((_, i) =&gt; `($${i * 2 + 1}, $${i * 2 + 2})`)<br>  .join(&quot;, &quot;);</pre><pre>const params = newOrders.flatMap(o =&gt; [o.userId, o.amount]);</pre><pre>await db.query(<br>  `INSERT INTO orders (user_id, amount) VALUES ${values}`,<br>  params<br>);</pre><p>If you’re using an ORM like Prisma, this is even easier:</p><pre>// Slow<br>for (const order of newOrders) {<br>  await prisma.order.create({ data: order });<br>}</pre><pre>// Fast<br>await prisma.order.createMany({ data: newOrders });</pre><p>Same idea everywhere: don’t ask the database to do 10,000 small favors. Ask it to do one big favor.</p><h3>Where I’ve Actually Seen This Cause Real Problems</h3><p><strong>The N+1 problem in ORMs.</strong> This is the most common version of this bug, and I still find it in almost every codebase I touch. You load a list of 50 posts, and for each post, you separately fetch its comment count. That’s 51 database calls instead of 2. This happens easily with ORMs like Prisma, TypeORM, or Sequelize if you’re not careful — you loop over records and call a related query inside the loop. The fix is almost always to load everything you need in one query up front (using include, join, or a batched lookup), instead of fetching related data one item at a time.</p><p><strong>Stripe’s batch APIs.</strong> If you’ve built a payments integration, you’ll notice Stripe gives you batch endpoints for things like payouts, instead of forcing you to call their API once per payment. At their scale, if every company looped one payment at a time, it would create a huge amount of unnecessary load. Batch-first design is a deliberate scaling decision.</p><p><strong>Bulk loading in data warehouses.</strong> I once inherited a job that loaded a vendor’s daily file into a database using one INSERT per row — about 4 million rows a day. It ran overnight and often ran late into the next morning. Switching to a bulk-load command (most databases have one, like COPY in Postgres/Redshift) took that job from around 5 hours to under 10 minutes. I didn&#39;t change the data. I changed how it was loaded.</p><p><strong>Elasticsearch’s </strong><strong>_bulk API.</strong> Indexing documents one at a time works fine with small amounts of data. Once you have a real amount of data to index, the per-request overhead adds up fast. Elasticsearch&#39;s _bulk API groups many documents into a single request, and it&#39;s basically required once you&#39;re at any real scale.</p><p><strong>Bank transaction settlement.</strong> This idea is much older than software. Banks don’t settle every transaction the second it happens — they group transactions and process them at set times. It’s the same idea: many small operations are expensive one at a time, but cheap when grouped together.</p><h3>What I Watch Out for Now</h3><p>Batching is not free. Here’s what I’ve learned to be careful about:</p><ul><li><strong>Don’t load everything into memory at once.</strong> I always process data in chunks — usually somewhere between 500 and 5,000 items — instead of building one giant batch. I learned this after watching a job’s memory usage climb straight up during what I thought was a “simple” export.</li><li><strong>Batching can add delay for individual items.</strong> If a single item needs to be processed right away (like something a user is actively waiting for), don’t make it wait in a batch queue with no limit. A common fix is: send the batch when it reaches a certain size, <em>or</em> after a short time limit, whichever happens first.</li><li><strong>Plan for partial failures early.</strong> One item at a time, a failure is simple — one row fails, you move on. In a batch, one bad row can sometimes fail the whole batch, depending on your database. Decide ahead of time what you’ll do: stop everything, skip the bad row and log it, or retry items one by one if the batch fails.</li><li><strong>Watch how long a big batch holds locks.</strong> A batch that’s too large can hold database locks longer than expected, which can slow down other parts of your system running at the same time. Bigger is not always better — it’s worth testing different batch sizes instead of guessing.</li></ul><h3>The One Habit I’d Want Every Engineer on My Team to Have</h3><p>Whenever I see a database call sitting inside a loop, I ask one question before approving the code: <strong>can this be one call instead of many?</strong></p><p>Almost always, the answer is yes — a bulk insert, an ANY() or IN() clause, an ORM&#39;s createMany, a service&#39;s batch endpoint, or a queue that collects work and processes it in chunks. It&#39;s usually a small change. But it&#39;s often the difference between a job that quietly scales and one that eventually wakes someone up at night.</p><p>The idea stays the same whether you’re a two-person startup handling your first real traffic spike, or a company processing millions of records a day. Every database call has a fixed cost. Batching is how you stop paying that cost over and over again.</p><p><em>If this sounds familiar, I’d love to hear your version of this story. Mine was a Sorting job that quietly grew from 4 seconds to 40 minutes — I suspect most backend engineers have one of these somewhere in their past.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f798010a2e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Estimating Rows: The Most Important Decision the Planner Makes]]></title>
            <link>https://medium.com/@wwwdeepak/estimating-rows-the-most-important-decision-the-planner-makes-4853d71e524f?source=rss-70f28be03e07------2</link>
            <guid isPermaLink="false">https://medium.com/p/4853d71e524f</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Deepak]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 02:31:01 GMT</pubDate>
            <atom:updated>2026-08-11T02:31:01.388Z</atom:updated>
            <content:encoded><![CDATA[<p>Imagine I ask you a simple question.</p><blockquote><em>Which is faster?</em></blockquote><p>Searching for one person in a phone book.</p><p>Or reading every page from beginning to end.</p><p>You can’t answer that until you know <strong>how many people you’re looking for</strong>.</p><p>If you’re searching for a single person, using the index at the front of the book is obviously the right choice.</p><p>If you’re trying to read information about almost everyone, flipping through the entire book is much faster.</p><p>PostgreSQL faces the exact same problem.</p><p>Before it can compare execution plans, it must answer one fundamental question.</p><blockquote><strong><em>How many rows do I expect this query to return?</em></strong></blockquote><p>That single estimate influences almost every decision the planner makes.</p><p>A good estimate usually leads to a good execution plan.</p><p>A bad estimate can make PostgreSQL ignore the best index or choose one that performs terribly.</p><p>Everything starts with estimating the number of matching rows.</p><h3>But PostgreSQL Hasn’t Executed the Query Yet</h3><p>Let’s look at our query again.</p><pre>SELECT *<br>FROM orders<br>WHERE status = &#39;Cancelled&#39;;</pre><p>At this point, PostgreSQL hasn’t read a single row from the orders table.</p><p>It hasn’t traversed an index.</p><p>It hasn’t touched the heap.</p><p>So how can it possibly know whether this query will return:</p><pre>5 rows<br>or<br>5 million rows</pre><p>The answer is surprisingly simple.</p><p>It doesn’t know.</p><p>It makes an educated guess.</p><p>That guess is based entirely on statistics collected earlier by ANALYZE.</p><p>Notice something important here.</p><p>ANALYZE is <strong>not</strong> part of query execution.</p><p>It doesn’t run every time you execute a query.</p><p>Instead, it periodically samples your tables and stores statistical information that the planner can reuse later.</p><p>You can think of it as PostgreSQL building a profile of your data rather than inspecting it every time.</p><h3>A Planner Without Statistics Would Be Guessing Blindly</h3><p>Imagine two different tables.</p><h3>Table A</h3><pre>100 million rows</pre><pre>Status</pre><pre>Pending<br>Pending<br>Pending<br>Pending<br>...</pre><p>Almost every order is still pending.</p><h3>Table B</h3><pre>100 million rows</pre><pre>Status</pre><pre>Pending<br>Completed<br>Cancelled<br>Returned<br>...</pre><p>The values are spread much more evenly.</p><p>Now run exactly the same query on both tables.</p><pre>SELECT *<br>FROM orders<br>WHERE status = &#39;Cancelled&#39;;</pre><p>Should PostgreSQL use the index in both cases?</p><p>Absolutely not.</p><p>In the first table, almost every row has the same value.</p><p>The query might return only a handful of rows — or perhaps none at all — depending on the distribution.</p><p>In the second table, the same predicate could return millions of rows.</p><p>Without knowing the data distribution, PostgreSQL would be making random decisions.</p><p>That’s exactly why statistics exist.</p><h3>What Information Does PostgreSQL Actually Store?</h3><p>A common misconception is that PostgreSQL remembers every value in every column.</p><p>That would be impossible.</p><p>Imagine storing statistics for a table containing two billion rows.</p><p>The statistics would become almost as large as the table itself.</p><p>Instead, PostgreSQL stores a compact summary of your data.</p><p>When ANALYZE runs, it doesn&#39;t copy your table.</p><p>It asks questions like these:</p><pre>How many rows does this table contain?<br>↓</pre><pre>How many distinct values exist?</pre><pre>↓</pre><pre>Which values appear most often?</pre><pre>↓</pre><pre>How many NULL values are present?</pre><pre>↓</pre><pre>How is the data distributed?</pre><pre>↓</pre><pre>Is the physical order similar to the index order?</pre><p>Those answers are enough for the planner to make surprisingly accurate estimates without scanning the table every time.</p><h3>Let’s Walk Through a Real Example</h3><p>Suppose your table contains one hundred million orders.</p><p>The distribution looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/709/1*FHqqM_UBiOCTq_K59Fhn7A.png" /></figure><p>Now the planner receives this query.</p><pre>SELECT *<br>FROM orders<br>WHERE status = &#39;Cancelled&#39;;</pre><p>The planner doesn’t know the exact answer.</p><p>Instead, it checks the statistics collected by ANALYZE.</p><p>Those statistics tell it something like this:</p><pre>Value</pre><pre>Cancelled</pre><pre>Frequency</pre><pre>≈ 2%</pre><p>Now the planner performs a simple calculation.</p><pre>Estimated rows<br>=</pre><pre>100,000,000 × 2%</pre><pre>=</pre><pre>2,000,000</pre><p>Notice what just happened.</p><p>PostgreSQL estimated the number of matching rows <strong>without reading the table</strong>.</p><p>This estimate becomes the foundation for every decision that follows.</p><h3>Why This Estimate Matters So Much</h3><p>Let’s compare two completely different situations.</p><h3>Query 1</h3><pre>WHERE status=&#39;Cancelled&#39;</pre><p>Estimated rows</p><pre>2 million</pre><h3>Query 2</h3><pre>WHERE status=&#39;Pending&#39;</pre><p>Estimated rows</p><pre>80 million</pre><p>Nothing changed except the value inside the predicate.</p><p>The same table.</p><p>The same index.</p><p>The same query structure.</p><p>But from the planner’s perspective, these are completely different problems.</p><p>For the first query, traversing an index might reduce the amount of work significantly.</p><p>For the second query, the planner already knows it will probably have to visit most of the table anyway.</p><p>That one estimate can completely change the chosen execution plan.</p><h3>The Planner Doesn’t Need Perfect Accuracy</h3><p>This is another point that surprises many developers.</p><p>The planner isn’t trying to predict the exact number of rows.</p><p>It doesn’t have to.</p><p>Imagine the planner estimates:</p><pre>Expected rows</pre><pre>2,050,000</pre><p>The actual query returns:</p><pre>1,980,431</pre><p>That’s perfectly acceptable.</p><p>The estimate isn’t exact, but it’s close enough for cost comparison.</p><p>The real problem occurs when the estimate is dramatically wrong.</p><p>For example:</p><pre>Estimated rows</pre><pre>100</pre><pre>Actual rows</pre><pre>12,000,000</pre><p>Or even worse:</p><pre>Estimated rows</pre><pre>15 million</pre><pre>Actual rows</pre><pre>3</pre><p>Now the planner starts comparing execution plans using completely incorrect assumptions.</p><p>And once the assumptions are wrong, the final decision is likely to be wrong as well.</p><p>This is one of the most common reasons developers see PostgreSQL choosing an execution plan that appears irrational.</p><p>In reality, the planner is making a perfectly logical decision based on inaccurate information.</p><h3>Every Decision After This Depends on One Number</h3><p>Once PostgreSQL has estimated the number of matching rows, that estimate flows through the rest of the planning process.</p><pre>Estimated Rows</pre><pre>↓</pre><pre>Estimated Pages</pre><pre>↓</pre><pre>Estimated I/O</pre><pre>↓</pre><pre>Estimated CPU Work</pre><pre>↓</pre><pre>Estimated Cost</pre><pre>↓</pre><pre>Chosen Execution Plan</pre><p>Everything begins with that very first estimate.</p><p>If it’s accurate, PostgreSQL usually selects an excellent execution plan.</p><p>If it’s wildly inaccurate, even the best optimizer in the world will struggle to choose the right index.</p><p>So the next logical question becomes:</p><blockquote><strong><em>Where do these statistics actually come from, and why should we trust them?</em></strong></blockquote><p>To answer that, we need to look inside what ANALYZE really does, why it samples only a tiny fraction of the table, and how that small sample is often enough to make decisions for databases containing billions of rows.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4853d71e524f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Happens Inside the Planner Before Your Query Starts Running?]]></title>
            <link>https://medium.com/@wwwdeepak/what-happens-inside-the-planner-before-your-query-starts-running-e94b13b9c367?source=rss-70f28be03e07------2</link>
            <guid isPermaLink="false">https://medium.com/p/e94b13b9c367</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[query]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Deepak]]></dc:creator>
            <pubDate>Thu, 30 Jul 2026 06:06:22 GMT</pubDate>
            <atom:updated>2026-07-30T06:06:22.321Z</atom:updated>
            <content:encoded><![CDATA[<p>Let’s continue with the same query.</p><pre>SELECT *<br>FROM orders<br>WHERE status = &#39;Cancelled&#39;;</pre><p>By the time PostgreSQL reaches the planning stage, it already knows two things:</p><ul><li>The SQL query.</li><li>The indexes available on the orders table.</li></ul><p>At this point, many developers imagine PostgreSQL simply checking whether an index exists on the status column.</p><p>If it does, use it.</p><p>If it doesn’t, perform a Sequential Scan.</p><p>That would certainly make the planner simpler.</p><p>But it would also make it wrong most of the time.</p><p>Instead, PostgreSQL begins building possible execution strategies.</p><p>For our query, it might come up with something like this.</p><pre>Plan A<br>Sequential Scan</pre><pre>Plan B</pre><pre>IndexScan using idx_orders_status</pre><pre>Plan C<br><br>Bitmap Index Scan<br>+<br>Bitmap Heap Scan</pre><p>These aren’t execution plans yet.</p><p>They’re simply <strong>candidates</strong>.</p><p>Think of them as different routes on Google Maps.</p><p>Google doesn’t immediately tell you which route to take.</p><p>It first evaluates every reasonable option.</p><p>The PostgreSQL planner works the same way.</p><h3>The Planner Starts Asking Questions</h3><p>Every candidate plan has to answer the same set of questions.</p><p>For example:</p><pre>How many rows will match?</pre><pre>↓</pre><pre>How many data pages need to be read?</pre><pre>↓</pre><pre>How much CPU work is required?</pre><pre>↓</pre><pre>Will sorting be necessary?</pre><pre>↓</pre><pre>Can an existing index avoid that sort?</pre><pre>↓</pre><pre>How many random disk reads will happen?</pre><pre>↓</pre><pre>What&#39;s the total estimated cost?</pre><p>Notice something interesting.</p><p>The planner doesn’t ask:</p><blockquote><em>“Which index is better?”</em></blockquote><p>Instead, it keeps asking:</p><blockquote><em>“Which plan requires the least amount of work?”</em></blockquote><p>Indexes are simply one of the tools available to reduce that work.</p><h3>Let’s Compare Two Plans</h3><p>Suppose our table contains 100 million rows.</p><p>The planner estimates that only 2 million rows have the status &#39;Cancelled&#39;.</p><p>Now compare the two simplest plans.</p><h3>Candidate 1 — Sequential Scan</h3><pre>Read every page of the table<br>↓<br>Check every row<br>↓<br>Return matching rows</pre><p>Advantages:</p><ul><li>Reads pages sequentially.</li><li>Very predictable disk access.</li><li>No index traversal.</li></ul><p>Disadvantages:</p><ul><li>Must examine every row.</li></ul><h3>Candidate 2 — Index Scan</h3><pre>Traverse B-tree<br>↓<br>Locate matching index entries<br>↓<br>Follow pointers to heap pages<br>↓<br>Read matching rows</pre><p>Advantages:</p><ul><li>Reads far fewer rows.</li></ul><p>Disadvantages:</p><ul><li>Requires random heap lookups.</li><li>Random I/O is usually more expensive than sequential I/O.</li></ul><p>Neither plan is automatically better.</p><p>Everything depends on how much work PostgreSQL estimates each one will perform.</p><h3>Why Reading Fewer Rows Isn’t Always Faster</h3><p>This is probably the most misunderstood part of PostgreSQL.</p><p>Let’s imagine your table occupies 40 GB.</p><p>Your query returns 75% of the rows.</p><p>Most developers instinctively think:</p><blockquote><em>Use the index.</em></blockquote><p>But let’s see what actually happens.</p><h3>Using the Index</h3><pre>Read index page<br>↓<br>Jump to heap page 18<br>↓<br>Jump to heap page 943<br>↓<br>Jump to heap page 51<br>↓<br>Jump to heap page 1802<br>↓<br>Jump to heap page 726<br>...</pre><p>Notice the pattern.</p><p>The storage engine keeps jumping between pages.</p><p>These are mostly random reads.</p><p>Now compare that with a Sequential Scan.</p><pre>Page 1<br>↓<br>Page 2<br>↓<br>Page 3<br>↓<br>Page 4<br>↓<br>Page 5</pre><p>No jumping.</p><p>No seeking.</p><p>Just continuous reading.</p><p>Even on modern SSDs, sequential access is still significantly more efficient because PostgreSQL can prefetch pages and the operating system can optimize continuous reads.</p><p>If most of the table needs to be read anyway, performing millions of random heap lookups through an index often becomes more expensive than simply reading the table once.</p><p>That’s why PostgreSQL sometimes ignores an index even though it exists.</p><p>The planner isn’t trying to minimize the number of rows it reads.</p><p>It’s trying to minimize the total amount of work.</p><p>Those aren’t always the same thing.</p><h3>But Wait… How Does PostgreSQL Know Which Plan Is Cheaper?</h3><p>Here’s where things become really interesting.</p><p>The planner hasn’t executed either plan.</p><p>It doesn’t know the future.</p><p>It can’t measure the actual execution time.</p><p>Everything it knows comes from estimation.</p><p>Imagine you’re asked this question.</p><blockquote><em>Which is faster?</em></blockquote><p>Driving 20 kilometers through city traffic.</p><p>Or driving 35 kilometers on an empty highway.</p><p>You can’t know the exact answer.</p><p>But you can make a very good estimate.</p><p>The PostgreSQL planner does exactly that.</p><p>For every candidate plan, it estimates:</p><ul><li>How many rows will be returned.</li><li>How many index pages must be visited.</li><li>How many table pages must be fetched.</li><li>How much CPU work is required.</li><li>Whether additional operations like sorting or hashing are needed.</li></ul><p>After estimating each of those values, it combines them into a single number called the <strong>estimated cost</strong>.</p><p>One of the biggest misconceptions about PostgreSQL is that this cost represents time.</p><p>It doesn’t.</p><p>If a plan has a cost of 250 and another has a cost of 500, PostgreSQL isn&#39;t saying the first query will run in half the time.</p><p>The cost is simply an internal score that allows different execution plans to be compared.</p><p>The planner doesn’t care whether that number is 250, 2,500, or 25,000.</p><p>It only cares which candidate has the lowest estimated cost.</p><h3>This Explains Many “Weird” Planner Decisions</h3><p>Once you understand that PostgreSQL is comparing complete execution plans — not individual indexes — a lot of confusing behavior suddenly makes sense.</p><p>For example:</p><ul><li>An index exists, but PostgreSQL still performs a Sequential Scan.</li><li>Two different indexes can satisfy the same query, yet PostgreSQL consistently prefers one over the other.</li><li>Adding a LIMIT 10 suddenly changes the execution plan.</li><li>Adding an ORDER BY causes PostgreSQL to stop using an index that it previously preferred.</li></ul><p>These aren’t random decisions.</p><p>The planner simply recalculates the estimated cost after every change to the query.</p><p>Even a small change can make a completely different execution plan become the cheapest option.</p><p>And that leads us to the next question.</p><p>Before PostgreSQL can estimate the cost of a plan, it first needs to estimate something even more fundamental:</p><blockquote><strong><em>How many rows do I expect this query to return?</em></strong></blockquote><p>Everything else in the planner depends on that single estimate.</p><p>This section intentionally <strong>doesn’t mention </strong><strong>ANALYZE, histograms, MCVs, or </strong><strong>pg_statistic yet</strong>. It creates curiosity first. The next section naturally begins with:</p><blockquote><strong><em>“Estimating Rows: The Single Most Important Job of the PostgreSQL Planner”</em></strong></blockquote><p>That’s where we dive into ANALYZE, n_distinct, most_common_values, histograms, correlation, and how wrong row estimates lead to wrong index choices. That section is arguably the most important part of the entire article.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e94b13b9c367" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>