<?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 Venkatesh Gopalakrishnan on Medium]]></title>
        <description><![CDATA[Stories by Venkatesh Gopalakrishnan on Medium]]></description>
        <link>https://medium.com/@imgv?source=rss-1e838ab290e7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hb0om1FaPEavicRPaOmYEQ.png</url>
            <title>Stories by Venkatesh Gopalakrishnan on Medium</title>
            <link>https://medium.com/@imgv?source=rss-1e838ab290e7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 16:24:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@imgv/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[Why Your Analytics Report Can Be Wrong Even When Every Query Is Correct]]></title>
            <link>https://medium.com/@imgv/repeatable-read-snapshot-isolation-analytics-df15a213d41c?source=rss-1e838ab290e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/df15a213d41c</guid>
            <category><![CDATA[data-analytics]]></category>
            <category><![CDATA[database-engineering]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Venkatesh Gopalakrishnan]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 05:34:06 GMT</pubDate>
            <atom:updated>2026-09-12T18:49:24.686Z</atom:updated>
            <content:encoded><![CDATA[<h4>A look at how REPEATABLE READ and snapshot isolation keep analytical queries honest on a live database.</h4><blockquote>Originally published at <a href="https://slothdriven.substack.com/p/repeatable-read-snapshot-isolation-analytics">https://slothdriven.substack.com</a> on September 1, 2026.</blockquote><p>Imagine you’re a data analyst who needs to report how much money moved through the system today. Nobody’s handed you a warehouse or a BI tool with pre-aggregated numbers, so you’re running straight against the transactional database, the same one the live application is writing to right now.</p><p>This is specifically an <a href="https://www.databricks.com/blog/what-is-oltp">OLTP</a> problem. A proper <a href="https://www.databricks.com/blog/what-is-olap">analytics setup</a> — a warehouse fed by batch loads or replication — usually hands you a consistent, already-settled snapshot as part of how the data lands there. The issue below only shows up when you’re reading straight from the live transactional database instead, which happens more often than it should: no warehouse yet, a report that needs fresher numbers than the nightly load provides, or just an analyst with read access to production and no other option.</p><p>You write three queries, each one simple and each one obviously correct on its own:</p><pre>SELECT SUM(amount) FROM payments WHERE created_at &gt;= CURRENT_DATE;<br>SELECT SUM(amount) FROM refunds WHERE created_at &gt;= CURRENT_DATE;<br>SELECT COUNT(*) FROM orders WHERE created_at &gt;= CURRENT_DATE;</pre><p>The tables involved have tens of millions of rows apiece, so each query takes anywhere from thirty seconds to a couple of minutes to finish. That doesn’t feel alarming by itself, and while your queries run, the application keeps doing exactly what it’s supposed to be doing: processing payments, issuing refunds, updating orders, all in real time, all completely unrelated to the fact that you happen to be reading from the same tables right now.</p><p>Here’s the part that’s easy to miss. Your payments query might finish based on the state of the database at, say, <em>10:00:00</em>. A refund gets committed by the application at <em>10:00:20</em>. Your refunds query then runs at <em>10:00:30</em> and picks up that new refund, because by then it’s committed and visible. Nothing here is broken. No query returned incorrect results. You never read uncommitted data, never saw a half-written row, never violated anything the database promised you at the statement level. And yet the report you’ve assembled from these three queries describes a version of the system that never actually existed at any single point in time — a blend of the database at <em>10:00:00</em> and the database at <em>10:00:30</em>, stitched together as if it were one moment.</p><p>This is the part that tends to surprise people who’ve mostly thought about isolation levels in the context of preventing dirty reads. Correctness at the level of one query and correctness at the level of a report built from several queries are not the same guarantee, and most databases, by default, only give you the first one.</p><p>Most relational databases default to something like READ COMMITTED, which guarantees each individual statement only ever sees data that has actually been committed - no dirty reads, no half-finished writes leaking through. What it does not guarantee is that two statements issued back-to-back, even inside the same session, see the <em>same</em> committed state. Each statement is free to take its own fresh look at &quot;what&#39;s committed right now,&quot; and if time has passed and something new landed in between, the next statement sees the new version. That&#39;s not a bug. That&#39;s exactly what READ COMMITTED is designed to do - it optimizes for always showing you the freshest committed data, not for showing you a stable, unchanging picture across multiple statements.</p><p>The trouble is that a report is rarely one statement. It’s a batch of them, run in sequence, expected by whoever reads the final numbers to describe one coherent snapshot of the business. Under READ COMMITTED, nothing in the database is actually promising you that.</p><p>This is where an isolation level like REPEATABLE READ earns its keep, and it&#39;s worth being precise about what it does, because the name undersells it a bit. Once a transaction running under REPEATABLE READ takes its first read, it effectively pins itself to that version of the database - every later statement inside that same transaction keeps seeing that exact same version, no matter how long the transaction runs or how much gets committed elsewhere in the meantime. Run all three of those payments, refunds, and orders queries inside one such transaction, and they&#39;ll all agree on the same 10:00:00, even if the transaction is still open at 10:05.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vtN_SRQ16Acu2s_6.png" /><figcaption>Same three queries, same fifteen seconds of real time — but under READ COMMITTED, a refund committed mid-batch quietly slips into the second query. Under REPEATABLE READ, every query in the transaction stays pinned to the same snapshot, whether or not something else commits while it runs.</figcaption></figure><p>Most modern databases implement this using <a href="https://en.wikipedia.org/wiki/Multiversion_concurrency_control">multiversion concurrency control</a> — instead of locking rows to keep other transactions out, the engine keeps multiple versions of each row around and simply hands your transaction the version that matches the moment it started, while everyone else keeps writing new versions undisturbed. It’s worth knowing that &quot;REPEATABLE READ&quot; as defined by the SQL standard is technically a slightly weaker guarantee than this - the standard only promises that rows you&#39;ve already read won&#39;t change out from under you, while still technically permitting new rows to appear in a repeated range query (the classic <a href="https://en.wikipedia.org/wiki/Isolation_(database_systems)">phantom read</a>). In practice, though, most major databases implement REPEATABLE READ using full <a href="https://en.wikipedia.org/wiki/Snapshot_isolation">snapshot isolation</a>, which closes that gap and gives you the full, stable, single-point-in-time view the name implies. It&#39;s a good example of an engine giving you more than the standard technically requires, which is a pleasant surprise as far as database standards go.</p><p>The practical fix, then, isn’t complicated. Instead of letting each analytical query run as its own implicit transaction — which is what happens by default in most notebooks, BI tools, and ad hoc SQL sessions unless you explicitly say otherwise — wrap the whole batch in one explicit transaction and set the isolation level before you start:</p><pre>BEGIN;<br>SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;<br><br>SELECT SUM(amount) FROM payments WHERE created_at &gt;= CURRENT_DATE;<br>SELECT SUM(amount) FROM refunds WHERE created_at &gt;= CURRENT_DATE;<br>SELECT COUNT(*) FROM orders WHERE created_at &gt;= CURRENT_DATE;<br><br>COMMIT;</pre><p>That’s genuinely the whole change. No application code to rewrite, no infrastructure to add, just an explicit acknowledgment that this batch of queries needs to agree on one version of reality before you start running it.</p><h3>What it costs you</h3><p>None of this comes free, and it’s worth being upfront about the trade-off rather than presenting REPEATABLE READ as a setting you flip on with no downside.</p><p>Holding a snapshot open for the duration of a long analytical transaction means the database has to keep every old version of every row that existed at snapshot time available, for as long as your transaction stays open, because your transaction might still need to read one of them. On a table that’s being actively written to the whole time your report runs, that means old row versions pile up rather than getting cleaned up, since the cleanup process can’t safely remove a version your open transaction might still need. The longer the transaction runs, and the busier the underlying tables are, the more that accumulates.</p><p>In practice this shows up as bloat — tables and indexes taking up more space than they should, and background cleanup processes falling behind on tables that are otherwise perfectly healthy — and the irony is that this cost lands on the exact same live, transactional workload you were trying not to disturb in the first place. A five-minute analytical query with a pinned snapshot, run against a table taking heavy write traffic, can leave a small mess behind for the database to clean up well after your report has already finished and you’ve moved on.</p><p>A couple of practical habits go a long way here: keep these transactions as short as you reasonably can, even under a stable isolation level, and if the option exists, run this kind of analytical work against a read replica rather than the primary database the application is actually writing to. That way the snapshot-related overhead lands somewhere that isn’t competing with production traffic for resources.</p><h3>The actual pitch to data analysts</h3><p>If you’re building a report out of more than one query, the question worth asking before you run any of them isn’t just whether each query is individually correct. It’s whether all of them, taken together, are actually describing the same moment. Under the isolation level most systems ship with by default, they usually aren’t, and the report can look completely reasonable while quietly mixing two or three different versions of the truth. Pinning your analytical work to a single consistent snapshot costs a little in overhead and requires you to be a bit more deliberate about how you open your transaction, but it’s a small price for a report that describes something that actually happened.</p><p><strong>How do you handle analytics or reporting queries that need to run against a live transactional database? Do you rely on isolation levels like </strong>REPEATABLE READ<strong>, offload the work to a read replica, keep it strictly on a warehouse, or something else entirely? I&#39;d be interested to hear what&#39;s worked for you.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df15a213d41c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Replacing a Nightly DELETE Job With Partition Drops Makes Sense for a 50-Million-Row Audit…]]></title>
            <link>https://medium.com/@imgv/why-we-replaced-a-nightly-delete-job-with-partition-drops-on-a-50-million-row-audit-table-d3921f2fb268?source=rss-1e838ab290e7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3921f2fb268</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[partitioning]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[database-engineering]]></category>
            <dc:creator><![CDATA[Venkatesh Gopalakrishnan]]></dc:creator>
            <pubDate>Tue, 25 Aug 2026 05:06:33 GMT</pubDate>
            <atom:updated>2026-08-27T17:00:20.187Z</atom:updated>
            <content:encoded><![CDATA[<h3>Why Replacing a Nightly DELETE Job With Partition Drops Makes Sense for a 50-Million-Row Audit Table</h3><h4>How PostgreSQL time-based partitioning can turn database cleanup from a heavy DELETE operation into a simple retention strategy.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*dOpyUr4Jvj1vRuao" /><figcaption>Photo by <a href="https://unsplash.com/@jkilmister?utm_source=medium&amp;utm_medium=referral">John Kilmister</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Every system that logs <em>“who did what and when”</em> eventually runs into the same problem: <strong>the audit table never stops growing.</strong> Consider an audit table that has crossed <strong><em>50 million rows</em></strong>, with a retention policy requiring anything <strong><em>older than a year</em></strong> to be removed.</p><p>It records every change to a core resource — who made the change, what changed, and when it happened. After a bit more than a year in production it has crossed 50 million rows and is still growing. The retention policy requires keeping a year of history and expiring older data.</p><p>The requirement sounds simple enough. The harder part is figuring out how to remove that data without turning retention itself into a database problem.</p><h3>The obvious fix</h3><p>The first instinct on pretty much any team is a scheduled job that does something along these lines:</p><pre>DELETE FROM audit_log<br>WHERE created_at &lt; now() - interval &#39;1 year&#39;;</pre><p>Wrap that in a stored procedure, run it nightly, and for a while it works fine, especially while the table is still small enough that nobody notices the job running.</p><p>The trouble shows up once the amount of data being expired becomes large enough that row-by-row cleanup is meaningful. The first purge can be especially painful if retention is introduced after the table has already accumulated a backlog of expired data. After that, a steady-state nightly job may remove only the newly expired rows, but every one of those rows still creates work: <strong>WAL</strong>, <strong>dead tuples</strong>, and subsequent <strong>vacuum</strong> and <strong>index</strong> <strong>cleanup</strong>. On PostgreSQL in particular, a DELETE is a lot less quiet than it looks on the page:</p><ul><li>Every deleted row generates a <a href="https://www.howtouselinux.com/post/understanding-write-ahead-logging-wal-in-postgresql">write-ahead log </a>(WAL) entry, so deleting a few million rows in one transaction produces a proportional spike in WAL traffic sitting on top of your normal write load. If that WAL is being shipped somewhere for replication or point-in-time recovery, you’ve just handed that infrastructure a burst of extra bytes it wasn’t sized for.</li><li>A DELETE also does not necessarily make the records disappear immediately. PostgreSQL uses <a href="https://www.postgresql.org/docs/16/mvcc-intro.html"><em>MVCC</em></a>, so deleted row versions become <a href="https://www.postgresql.org/docs/current/routine-vacuuming.html">dead tuples</a> that remain until <a href="https://www.postgresql.org/docs/current/routine-vacuuming.html">autovacuum</a> can reclaim the reusable space. If a cleanup workload creates dead tuples faster than vacuum can process them, table and index bloat can become part of the operational problem.</li><li>Indexes are not free either. A bulk delete leaves dead row versions and associated index entries that later become cleanup work for VACUUM. The more indexes the audit table carries, the more maintenance work retention creates. An audit table with indexes on fields such as user_id, resource_id, and created_at can therefore make a large row-by-row purge considerably more expensive than the DELETE statement itself suggests.</li><li>A large DELETE also competes with the foreground workload for I/O, WAL bandwidth, buffers, and CPU. PostgreSQL does not block all concurrent writers simply because a DELETE is running, but transactions touching the same rows can <a href="https://www.crunchydata.com/blog/postgres-locking-when-is-it-concerning">contend</a> and a long running cleanup transaction can create operational pressure elsewhere in the system.</li></ul><p>The usual workaround is to split the cleanup into smaller batches with short pauses between them. That caps the size of each transaction, spreads WAL and I/O over time, and reduces how long any one batch holds row locks. It works, but retention has now become a job that needs tuning, monitoring, retry logic, and some definition of what happens when it falls behind — all to accomplish something that is conceptually just “throw away old data.”</p><h3>The alternative: don’t delete rows, drop partitions</h3><p>What actually changes things for us is realizing we aren&#39;t deleting some arbitrary set of rows scattered across the table, we are deleting a contiguous block of time, and that’s a meaningfully different problem to solve. Postgres happens to have a mechanism built specifically for that case: <a href="https://www.postgresql.org/docs/current/ddl-partitioning.html#DDL-PARTITIONING-DECLARATIVE">declarative partitioning</a>.</p><p>Instead of treating the audit log as one physical table forever, we partition it by range on created_at, with one partition per month. Applications still read from and write to audit_log; PostgreSQL routes the rows into the appropriate physical partition underneath. A simplified version of the structure looks like this:</p><pre>CREATE TABLE audit_log (<br>     id          bigint NOT NULL,<br>     user_id     bigint,<br>     resource_id bigint,<br>     created_at  timestamptz NOT NULL<br> ) PARTITION BY RANGE (created_at);<br> <br>CREATE TABLE audit_log_2026_08<br>PARTITION OF audit_log<br>FOR VALUES FROM (&#39;2026-08-01&#39;)<br>              TO (&#39;2026-09-01&#39;);</pre><h4>The parent is the logical table the application knows about. Each monthly partition is an ordinary PostgreSQL table containing only rows from that time range.</h4><p>There is an important retention detail hidden in that choice of partition size. Monthly partitions mean expiry happens at month granularity, not at an arbitrary row-level timestamp. You cannot drop half of a monthly partition just because some of its rows crossed the one-year boundary.<br><strong><em>If your policy requires an exact rolling 365-day cutoff, monthly partitions alone are not sufficient. You would need smaller partitions — daily partitions, for example — or separate handling for the boundary partition.</em></strong> The partition interval should match the precision your retention policy actually requires.</p><p>Once a complete partition is outside the retention window, the cleanup can operate on the partition itself rather than every row inside it. The simplest case, when the data can be destroyed immediately, is to drop the old partition:</p><pre>DROP TABLE audit_log_2024_08;</pre><p>Another option is to detach it first:</p><pre>ALTER TABLE audit_log <br>DETACH PARTITION audit_log_2024_08;</pre><pre>DROP TABLE audit_log_2024_08;</pre><p><a href="https://www.postgresql.org/docs/17/sql-altertable.html?utm_source=chatgpt.com#SQL-ALTERTABLE-DETACH-PARTITION">Detaching</a> is useful when you want a deliberate intermediate state — for example, to archive the old table, run a final check, or keep it available briefly outside the live partition hierarchy before deleting it.</p><p>Postgres doesn’t scan a single row to do this, doesn’t generate WAL proportional to how much data was in that partition, and doesn’t have to touch a single index entry, because detaching and dropping a partition is really just Postgres updating its own catalog metadata about which physical tables make up audit_log and then removing one of them. It genuinely doesn’t matter whether that partition held ten thousand rows or ten million; the operation costs about the same either way, and it’s about as close to instant as anything in a production database gets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PvGU2Fye_50M17-e836Y7Q.png" /><figcaption>Laid out side by side like this, the difference is really about <em>where</em> the cost lives. The DELETE path pays a cost proportional to how many rows it touches, every single night. The partition path pays almost nothing, because it’s not touching rows at all — it’s just relabeling which physical table is part of the logical one.</figcaption></figure><h3>What it actually costs you</h3><p>If I stopped the article here and called this a clean, free win, I’d be doing the exact thing I get annoyed at when other partitioning articles do it, so it’s worth being straightforward about the parts that aren’t free.</p><p><strong>Migrating an existing large table into partitions isn’t something you can just flip on, since you can’t retroactively partition a table that already has 50 million rows sitting in it without a plan.</strong> We have to build the new partitioned structure, backfill the historical data into the correct monthly partitions, and then cut writes over carefully enough to avoid either a gap or a duplication window, and that migration work is genuinely the part that eats your planning time, not the partitioning concept itself.</p><p>Your query patterns also need to make sense for the partition key. PostgreSQL’s <a href="https://www.postgresql.org/docs/current/ddl-partitioning.html">partition pruning</a> works when it can determine from the query predicates that certain partition bounds cannot contain matching rows. For example, a query with a useful time range:</p><pre>WHERE user_id = ?<br>AND created_at &gt;= ?<br>AND created_at &lt; ?</pre><p>can allow PostgreSQL to eliminate irrelevant monthly partitions. A query such as:</p><pre>WHERE user_id = ?</pre><p>with no time restriction may need to consider many or all of them. Partitioning therefore works best when the column you partition on also lines up reasonably well with the way the data is queried.</p><p>Partition maintenance becomes its own small ongoing responsibility as well, since new months don’t create their own partitions automatically. Something has to create next month’s partition ahead of time, whether that’s a cron job, an extension like <a href="https://github.com/pgpartman/pg_partman"><strong>pg_partman</strong></a>, or your own migration tooling.<strong> If an inserted value does not match any existing partition and there is no </strong><strong>DEFAULT partition, the insert fails.</strong> A default partition can provide a safety net, but it also adds maintenance considerations when new explicit partitions are attached later. Either way, partition creation is something you want automated and monitored rather than something somebody remembers to do on the last day of every month.</p><p>And indexes exist per partition rather than globally across the whole table, which is normally exactly what you want, but it’s worth knowing going in: a unique constraint across the entire logical table isn’t automatically enforced unless the partition key is part of that constraint.</p><p>None of this is a dealbreaker. It’s just the honest cost of the approach, and it felt more useful to say so than to write another article that reads like a product pitch for partitioning.</p><h3>When I would not do this</h3><p><strong>I would not introduce partitioning just because a table has become “<em>large</em>”. </strong>Partitioning adds schema and operational complexity, and that complexity only pays for itself when the workload gives you a reason to use it.</p><p>If the table is modest, the number of expired rows is small, and a simple indexed and batched DELETE finishes comfortably inside your maintenance budget, keeping the simpler design may be the better engineering decision.</p><p>I would also hesitate if most important queries cannot constrain the partition key, if the retention cutoff needs much finer precision than the chosen partition interval, or if the application depends on uniqueness rules that become awkward across partitions.</p><p>For us, the combination that makes partitioning attractive is specific: a <strong><em>high-volume append-heavy audit table</em></strong>, <strong><em>a retention rule based on time</em></strong>, and <strong><em>old data that could be discarded in contiguous time ranges</em></strong>. Change those assumptions and I would re-evaluate the decision rather than automatically reaching for partitions.</p><h3>What we actually saw</h3><p>We don’t have a clean before-and-after measurement of WAL volume or lock-wait time, so I wouldn’t invent one. What matters for this example is the workload: roughly 50 million rows, one-year retention, monthly partitions, and aged-out partitions that can be dropped independently of how many rows they contain.</p><p>The bigger benefit is operational: retention stops being a job that needs to process millions of individual rows and becomes a simple partition lifecycle — create new partitions, let them age, and remove them when they’re outside the retention window.</p><h3>The actual takeaway</h3><blockquote>Deleting data and expiring data look identical from a distance, but they’re different problems underneath.</blockquote><p>A DELETE statement is built to remove whatever rows match some condition, and that generality is exactly what makes it expensive once the table gets large, since Postgres genuinely has to go find and process every one of those rows. <strong><em>Expiring an entire time range is a narrower, more structured problem, and a partition drop solves it by using that structure directly instead of scanning the table to rediscover it every single night.</em></strong></p><p>The same reasoning holds well beyond audit logs, for anything with a natural <em>“older than X, throw it away”</em> lifecycle, whether that’s time-series metrics, event tables, or request logs. If your retention rule can be stated as <em>“everything before this date,”</em> it’s worth checking whether you’re reaching for the right tool before building a DELETE job and a batching strategy just to keep it from causing trouble in production.</p><blockquote>How have you handled retention for large audit tables? Did you use partitioning, batched deletes, archival, or something else? I’d be interested to hear what worked for you.</blockquote><blockquote>I’m exploring more production database engineering problems as I work through what I’m learning. If that’s your thing, feel free to follow along.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3921f2fb268" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>