<?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 Abhisek Ojha on Medium]]></title>
        <description><![CDATA[Stories by Abhisek Ojha on Medium]]></description>
        <link>https://medium.com/@abhisek.ojha?source=rss-7abd0b7d2b64------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1jBAUzr-NqHbKu6gmSbaEg.jpeg</url>
            <title>Stories by Abhisek Ojha on Medium</title>
            <link>https://medium.com/@abhisek.ojha?source=rss-7abd0b7d2b64------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 19:42:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhisek.ojha/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[Bucketing vs. Time-Partitioning in Iceberg]]></title>
            <link>https://medium.com/@abhisek.ojha/bucketing-vs-time-partitioning-in-iceberg-f7acb1e89b64?source=rss-7abd0b7d2b64------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7acb1e89b64</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Abhisek Ojha]]></dc:creator>
            <pubDate>Tue, 01 Sep 2026 19:27:18 GMT</pubDate>
            <atom:updated>2026-09-07T11:07:50.941Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How a single Python list controls the storage layout of ~180 CDC tables and why the busiest tables get the fewest buckets</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*64LkNQlT1Sol1_U27fHWVA.png" /></figure><h3>The Question With No Single Answer</h3><p>When you set up a table in Apache Iceberg, you’ll be asked a surprisingly straightforward question: how should the data be arranged on the disk?</p><p>By optimising data storage and query execution, you can achieve rapid query response times and minimise write sizes. Conversely, an incorrect data layout can result in either a few large files that hinder parallel read access or a multitude of small files that overwhelm the query planner with metadata. The performance of the same data can be drastically different, solely determined by the chosen storage and query execution strategies.</p><p>Iceberg gives you two tools to make that decision:</p><ul><li><strong>Bucketing</strong> :split rows into a fixed number of groups using a hash of a column. bucket(32, id) means: take each row&#39;s id, hash it, and drop the row into one of 32 groups. Rows with the same id always land in the same bucket.</li><li><strong>Time-partitioning</strong> : split rows by date. day(created_time) means: one folder per calendar day.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n8DmqJZUzlO7VOFZWSKXyg.png" /></figure><p>You can use one, both, or neither.</p><p>Here’s the challenge: there is no single “best” approach. A lookup table with 500 fixed rows requires a vastly different layout compared to a transactions table that experiences daily growth of millions of rows. I had approximately 180 tables continuously ingesting data from CDC (change data capture), which generates a stream of inserts, updates, and deletes from a production database. Hand-tuning each table was impractical, and selecting a single rule for all of them would be inaccurate for the majority of them.</p><p>So I did the boring thing that turned out to be the best thing: I put the layout decision for every table into one config list, and made every other part of the pipeline read from it.</p><h3>The Config List</h3><p>Every table is a single line in a plain Python list:</p><pre>ALL_TABLES = [<br>    # small / static tables — buckets only<br>    {&quot;group&quot;: &quot;user&quot;,      &quot;table&quot;: &quot;customer&quot;,         &quot;pk&quot;: &quot;id&quot;, &quot;buckets&quot;: 32},<br>    {&quot;group&quot;: &quot;screening&quot;, &quot;table&quot;: &quot;screening_result&quot;, &quot;pk&quot;: &quot;id&quot;, &quot;buckets&quot;: 100},</pre><pre>    # big, fast-growing tables — few buckets + a day partition<br>    {&quot;group&quot;: &quot;transaction&quot;, &quot;table&quot;: &quot;transaction&quot;, &quot;pk&quot;: [&quot;customer_id&quot;, &quot;id&quot;],<br>        &quot;buckets&quot;: 10, &quot;time_partition_column&quot;: &quot;created_time&quot;},<br>    # ...<br>]</pre><p>Each entry carries just three or four fields: the primary key, a bucket count, and only for some tables a time_partition_column.</p><p>Look closely and something looks backwards: the small, quiet tables get 32 or 100 buckets, but the biggest, busiest tables get only 10. That feels upside-down. It isn’t and it’s the most important idea in this post, so I’ll come back to it.</p><h3>One List: Several Jobs</h3><p>The list itself is trivial. The power is that multiple parts of the pipeline read from it, so the layout decision lives in exactly one place and can never fall out of sync.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t-nfC91SP8af9BzfBxGNRw.png" /></figure><h3>1. It Builds the Table Layout (the DDL)</h3><p>When a table is created, its config becomes the PARTITIONED BY clause:</p><pre>-- busy table: split by day, then into 10 buckets<br>PARTITIONED BY (day(`created_time`), bucket(10, `id`))</pre><pre>-- quiet table: just 32 buckets<br>PARTITIONED BY (bucket(32, `id`))</pre><p>No hand-written DDL, no copy-paste drift. The table’s physical shape is a direct function of its one config line.</p><h3><strong>2. </strong>It Makes the Merge Cheap: The Interesting Part</h3><p>Every cycle, a MERGE writes the latest changes into each table. Now, imagine a table with years of history. If we used a naive merge, it would have to scan the entire table every time, just to apply a few minutes of changes. That’s not the kind of cost we want to incur, right?</p><p>The instinct is obvious: only look at recent data. Add a filter so the merge reads just the last little while:</p><pre>-- the naive idea<br>WHERE t.created_time &gt;= TIMESTAMP &#39;&lt;7 days ago&gt;&#39;</pre><p>As the table is physically divided into daily sections, Iceberg can efficiently bypass the outdated folders and access only the most recent data slice. This significant difference is particularly pronounced on large tables, where scanning a substantial amount of data becomes considerably more time-consuming compared to scanning a smaller portion.</p><p>And this is exactly where I got burned so let me save you the bug.</p><p><strong>CDC</strong> doesn’t only insert new rows. It also sends updates to old rows. Someone edits a record that was created eight months ago; CDC captures that change today. Now think about what that naive filter does:</p><ul><li>The incoming change is recent, so it enters the merge.</li><li>But the merge finds the existing row by joining on the primary key <em>and</em> t.created_time &gt;= 7 days ago.</li><li>The row it’s trying to update is eight months old — so the filter hides it from the join.</li><li>The merge concludes “this row doesn’t exist yet” → and inserts a duplicate.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BoXeA6aR5AJP86twYig_EA.png" /></figure><p>I didn’t theorize this. I ran the count on one attributes table and found 17,348 duplicated keys 18,633 extra rows ,some keys with three or more copies. And the weekly full reconcile couldn’t even clean them up: once two identical copies exist, a key-based merge updates <em>both</em> of them to the same value and the duplicate lives forever.</p><p>The root mistake: I filtered by a blind, fixed cutoff instead of by the data. A hard “<strong>last 7 days</strong>” line has no idea that today’s batch contains an eight-month-old update.</p><p>The solution is to allow the incoming batch to determine the window. Instead of cutting at a fixed date, the merge reads the actual created_time range present in this batch of changes and processes it in date-aligned slices. If a batch contains only recent edits, the window remains small, and pruning is preserved. If a batch contains that eight-month-old update, the window for that slice extends far enough to include the original row, allowing the merge to find it and update it in place. This eliminates duplicates, and the change is still committed immediately.</p><p>Same performance win on the common case, but correctness no longer depends on a bet that “old rows never change.” The lesson, in one line: <strong>scope the merge to the data’s real range, not a guessed cutoff.</strong></p><p>(<em>There’s still a weekly full reconcile with no filter at all a belt-and-suspenders safety net. But it’s insurance, not the mechanism you rely on.</em>)</p><h3>3. It Scopes the Cleanup</h3><p>The weekly compaction process (OPTIMIZE) optimises file storage by rewriting numerous small files into fewer larger files. It reads the same configuration and only rewrites recent partitions, eliminating the need to process old data that is already organised. Consequently, the cleanup cost remains proportional to the number of new writes, rather than the size of the data table.</p><h3>Why Do the Busiest Tables Get the Fewest Buckets?</h3><p>This is the part that confuses everyone, so let’s make it concrete.</p><p>The total number of partitions is a multiplication, not an addition:</p><pre>total partitions ≈ number of days × number of buckets</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yj0uhQ_P86uTd5DtuhsFUw.png" /></figure><p>A day-partitioned table already splits its data into one partition per day roughly 365 per year. Now multiply by the bucket count:</p><ul><li><strong>100 buckets:</strong> 365 × 100 = 36,500 partitions per year → thousands of tiny files, bloated metadata, slow planning. A disaster.</li><li><strong>10 buckets:</strong> 365 × 10 = ~3,650 partitions per year → healthy.</li></ul><p>The day-split is already doing most of the work of spreading the data out. The buckets only need to keep a single day’s data at a sensible size so 10 is plenty.</p><p>A static table is the mirror image. It has no day-split, so buckets are the only thing spreading its data. If that table is large, one dimension has to carry the whole load, so it earns more buckets up to 100 for the biggest.</p><p><strong>The real rule is simple:</strong> <em>give buckets only as much work as they actually have to do. If a day-partition shares the load, use few buckets. If buckets work alone, use more. Always size the two together never in isolation.</em></p><h3>Why Bucket on the Primary Key Specifically?</h3><p>Because the MERGE joins on the primary key. When a table is bucketed by that same key, Iceberg can skip every bucket that can&#39;t possibly contain a matching row, it hashes the incoming keys, knows exactly which buckets they&#39;d live in, and ignores the rest.</p><p>So bucketing isn’t just a storage detail. Bucket on the column you join on and it becomes a query accelerator the merge reads a fraction of the table instead of all of it. The same <strong>pruning</strong> helps any query that filters or joins on that key, not just the merge.</p><p>For a composite key like [&quot;customer_id&quot;, &quot;id&quot;], list every column for matching, and bucket on the one you actually join on.</p><h3>Why a Config List Instead of Hand-Written DDL?</h3><p>At 180 tables, the benefits compound:</p><ul><li><strong>Change one line, everything follows.</strong> Re-tuning a table is a one-line edit : the DDL, the merge scoping, and the compaction all update from it. Nothing is rewritten automatically; the new layout applies through a swap/backfill job.</li><li><strong>You can read it.</strong> The entire platform’s storage layout is one list in git. Anyone can glance at it and see which tables are day-partitioned and whether a bucket count looks sane.</li><li><strong>Upgrades are easy.</strong> When a table grows enough to need a day-partition, you add one field, deploy, and run a swap job.</li><li><strong>You can automate the decision.</strong> Since layout is just data, a weekly job measures each table’s size and raises an alert when a table crosses a threshold (over 5 GiB) big enough to deserve a day-partition. No guessing; a number decides.</li></ul><h3>What I Learned</h3><ul><li><strong>There’s no universal partition scheme.</strong> The value isn’t in any one table’s layout ,it’s in making layout a declared decision instead of 180 hand-written scripts.</li><li><strong>Partition dimensions multiply.</strong> “Busiest tables, fewest buckets” only makes sense once you see days × buckets as a product. Tune one and ignore the other and you get either giant files or millions of tiny ones.</li><li><strong>Bucket on the column you join on.</strong> It turns bucketing from a storage detail into a query accelerator.</li><li><strong>Filter by the data, not by a guess.</strong> A fixed “last N days” cutoff quietly corrupts data the moment an old row gets updated. Scope to the batch’s real range instead.</li><li><strong>Keep layout and queries in one place.</strong> My merge scoping can never mismatch my partition column, because both come from the same line of config.</li></ul><p>One Python list decides how ~180 tables live on disk, what each merge reads, and where cleanup spends its time. Each table declares what it is and the system does the rest.</p><h3>Resources</h3><ul><li><a href="https://iceberg.apache.org/docs/latest/partitioning/">Partitioning Apache Iceberg documentation</a>: how hidden partitioning and partition transforms like day() and bucket() work.</li><li><a href="https://iceberg.apache.org/docs/latest/spark-ddl/">Spark DDL -Apache Iceberg documentation</a>: the PARTITIONED BY syntax used in this post.</li><li><a href="https://iceberg.apache.org/docs/latest/spark-writes/">Spark writes -Apache Iceberg documentation</a>: MERGE INTO semantics and write behavior.</li><li><a href="https://iceberg.apache.org/docs/latest/maintenance/">Maintenance-Apache Iceberg documentation</a>: compacting small files and other table upkeep.</li><li><a href="https://iceberg.apache.org/spec/">Iceberg table spec</a>: the formal definition of the bucket transform (a 32-bit Murmur3 hash mod N).</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7acb1e89b64" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Flattening Every JSON Key]]></title>
            <link>https://medium.com/@abhisek.ojha/stop-flattening-every-json-key-cc9a4e7387aa?source=rss-7abd0b7d2b64------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc9a4e7387aa</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Abhisek Ojha]]></dc:creator>
            <pubDate>Mon, 10 Aug 2026 21:44:12 GMT</pubDate>
            <atom:updated>2026-08-10T21:44:12.589Z</atom:updated>
            <content:encoded><![CDATA[<h4>The semi-structured data challenge that every warehouse eventually encounters, and one pattern that effectively addresses it without normalising 200 keys or requiring manual JSON parsing for everyone.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1jnt0pbsalgyuRl76TAAyg.png" /></figure><p>Eventually, every warehouse encounters a JSON blob that exceeds its capacity to manage effectively.</p><p>This data is referred to as attributes, payload, or metadata. It contains a distinct set of keys on almost every row, as all upstream entities believed they might require it in the future. For a considerable period, no one accessed it. However, one day, three teams necessitated its queryability, and it was subsequently presented to you.</p><p>This column presents a genuinely challenging modelling problem, and unfortunately, most teams encounter difficulties in effectively addressing it. Here’s an explanation of the complexities involved and a systematic approach that facilitates a clean resolution.</p><h3>The problem: an open schema in a closed column</h3><p>Relational columns require a fixed, predefined structure. In contrast, a JSON blob presents an open schema, encapsulated within a single field.</p><p>The keys differ based on the source, the type of event, and the specific circumstances of the producer’s writing during that quarter. A select few keys are highly sought after, as individuals primarily filter based on quantity, currency, and status. The majority of keys, however, remain relatively obscure and difficult to fully enumerate. Additionally, new keys emerge unexpectedly.</p><p>In the face of this predicament, teams resort to either of two approaches, both of which are deceptive.</p><p><strong>Normalise every key into a separate column</strong>. This process is never-ending. The key set is unbounded and specific to the producer, leading to an endless cycle of ALTER TABLE and model changes, resulting in a perpetually evolving schema. Furthermore, the risk of missing a new key results in silent data loss.</p><p><strong>Preserve the data in raw JSON format,</strong> rendering it unusable due to the absence of typed information. Each query necessitates manual parsing of the blob, hindering indexing capabilities and clean joins. Moreover, analysts unfamiliar with the json_extract_path_text function will be unable to access the data effectively.</p><p>You end up choosing between usability and completeness. That false choice is the whole problem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Erada6GLJplUrA7ZK3ZRwQ.png" /></figure><h3>The solution: the Hybrid flatten</h3><p>You don’t have to choose. The fix is to do both at once:</p><p><em>Promote the handful of keys people actually query into real, typed columns. Keep the entire original payload as a </em><em>SUPER map. Keep both, in one model.</em></p><p>In Redshift, it’s a single <strong>SELECT</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*brgqPbhqwjvuR-vWL7QnSg.png" /></figure><p>Indeed, the pattern comprises two distinct halves, each performing a unique function.</p><p>The promoted columns are designed to handle the frequently accessed path. The keys that users typically filter and join become typed columns, resulting in fast indexing and eliminating the need for parsing at query time. <strong>This optimises the table’s usability.</strong></p><p>The <strong>SUPER</strong> map efficiently handles the cold path. JSON parsing retains the entire payload as a semi-structured value, ensuring that any un-promoted key is only one navigation away: attrs.that_rare_key. This approach guarantees data integrity, eliminating the need to anticipate which keys may become relevant in the future.</p><p>Promoted columns enhance usability, while the <strong>SUPER</strong> map provides completeness. Consequently, there is no need to compromise between the two.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M79imY69Fssm5Q5EaRxtjw.png" /></figure><p>The payoff manifests when upstream entities introduce novel data. A previously undisclosed key emerges, already captured in attributes no schema modification, no data loss. Promote it to a typed column later, contingent upon its significance.</p><h3>See the difference</h3><p>The definitive evidence lies in the subjective experience of querying. For instance, consider an analyst seeking the aggregate completed amount per currency. In contrast to the raw data, every field must be meticulously extracted and analysed manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iiwv5fd65W7EoH4QlWjkwg.png" /></figure><p>No typing occurs; the blob is re-parsed three times, and a single incorrect amount value causes the entire query to fail. Now, let’s consider the same question against the <strong>Hybrid table</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VD-DNhS2H_YUrUrmLDDd5w.png" /></figure><p>The same response, requiring a fraction of the effort: clean, typed columns, no parsing, no surprises, and easily readable by all team members. Unfortunately, the long tail did not progress.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpCJQTkXuVprAyMa-AhEBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ZX92_UWX86ce3Z95CsS6A.png" /></figure><h3>Making it hold up with real data</h3><p>The fundamental concept depicted in the pattern is that three simple habits can sustain its effectiveness once it is implemented in a messy real-world scenario.</p><h3>1. Deal with messy values</h3><p>The same concept frequently manifests under two distinct names: “amount” and “originalAmount.” To select the appropriate value, utilise the coalesce function. Prior to converting text into a numerical representation, ensure that the text adheres to the format of a valid number. If it does not, consider storing NULL instead of allowing a single erroneous value to disrupt the entire build process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lTu25bAwTQ5QJORFd-ePxw.png" /></figure><p>A build that fails on a single malformed row is a build that fails at 3 a.m. Instead, quarantine the value.</p><h3>2. Decide what makes a row unique</h3><p>To begin, identify the unique identifier for each row. It may not always be the apparent primary key, such as customerid in this case, where the same customerid can be repeated across multiple rows. Once the primary key is identified, retain only the most recent copy of each row and discard the duplicate entries. Subsequently, implement a test that promptly detects the presence of duplicate entries.</p><p><strong>SQL:</strong></p><pre>row_number() over (<br>    partition by customer_id, id<br>    order by _loaded_at desc<br>) as _rn<br>-- ... keep where _rn = 1</pre><p><strong>YAML:</strong></p><pre>tests:<br>  - dbt_utils.unique_combination_of_columns:<br>      combination_of_columns: [customer_id, id]</pre><h3>3. Only process what changed</h3><p>Refrain from rebuilding the entire table during each iteration; this approach is both time-consuming and costly. Implement an incremental model that selects only the rows that have been added since the previous iteration. This can be achieved using a simple “newer than existing” filter. The initial iteration will populate the table, while subsequent iterations will be significantly smaller. Subsequently, tag the model so that your orchestrator automatically rebuilds it after each load, eliminating the need for custom wiring.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IVpJ4WFHekWNsQ7BJAGgug.png" /></figure><h3>When not to reach for this</h3><p>The Hybrid flatten shines when the schema is open and unpredictable. However, it can be overkill or the incorrect tool in certain cases.</p><ul><li><strong>The keys are limited and fixed</strong>. If each row contains the same small, known set of keys, simply promote them all. An escape hatch is unnecessary for a schema that remains unchanged.</li><li><strong>The payloads are substantial.</strong> Redshift has a size limit for super values (approximately 1 MB). If a single blob is excessively large, retain the promoted columns but store a truncated version, or a pointer to the complete payload, instead of the entire data.</li><li><strong>Nobody touches the long tail.</strong> If the rare keys are genuinely never queried, the raw map is dead weight. Promote what’s used and drop the rest.</li><li><strong>The data is deeply nested.</strong> Arrays and nested objects usually need their own unnesting into rows rather than a flat set of columns. The pattern still helps at the top level, but it won’t be the whole answer.</li></ul><h3>The payoff</h3><p>In the end, you have a single table that is efficient for querying, easy to join, and never discards any fields. Analysts receive clean, typed columns, while power users still have access to the complete raw payload in the attributes. Furthermore, you maintain a single model instead of a schema that is constantly being patched regardless of the new keys that are sent upstream, the table already contains them.</p><p>When inheriting a JSON column, refrain from excessive normalisation and avoid dumping it raw. Instead, promote the hot keys, retain the rest in SUPER mode, and allow the table to accommodate any subsequent data.</p><p>This is the ultimate advantage. You can now select between user-friendly and comprehensive options, and you will receive both simultaneously.</p><p><strong><em>Are you grappling with a semi-structured column? The Hybrid flatten is an excellent starting point. I would be interested in observing its performance with your payloads.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc9a4e7387aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Your Glue Catalog Is Lying About Your Schema]]></title>
            <link>https://medium.com/towards-data-engineering/your-glue-catalog-is-lying-about-your-schema-3d66be67c7aa?source=rss-7abd0b7d2b64------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d66be67c7aa</guid>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Abhisek Ojha]]></dc:creator>
            <pubDate>Wed, 29 Jul 2026 09:57:08 GMT</pubDate>
            <atom:updated>2026-07-29T09:59:47.136Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J27KJXRzUCQ5udX6yOKong.png" /></figure><h3>A schema change that refused to take</h3><p>The task was routine. We were dropping a column from one of our Iceberg tables a field that had been deprecated upstream. I executed the DDL, Athena reported success and the column was removed.</p><p>This was not the case, as confirmed by everyone who inquired.</p><p>Several hours later, a component of my ingestion pipeline that inspects a table’s columns still asserted the presence of the dropped field. I verified this by a different method and obtained the same result; the column was present. I re-ran the drop operation and it was successful again. The column had been deleted and the DDL had been committed but the component was certain it still existed.</p><p>If you have ever observed a change you made fail to appear you are acutely aware of the specific type of <a href="https://www.vocabulary.com/dictionary/paranoia">paranoia</a> that follows. Did the data actually transfer? Was I viewing the incorrect table? Was there an unrecognised <a href="https://aws.amazon.com/caching/">caching</a> layer?</p><p>There was. Once I understood it, it altered my approach to reading schemas for every Iceberg table in the platform. It also revealed itself to be a specific instance of a more general problem that is present in every lakehouse stack, not just mine. More on that later.</p><h3>Why this mattered more than it looks</h3><p>This was not merely a cosmetic issue. My CDC pipeline includes automatic column-drift detection before merging change events into a table. It compares the columns present in the incoming data against the columns of the target table to ensure that a new field upstream is detected and not silently dropped. (The detection process is a separate matter.)</p><p>This mechanism is based on the assumption that a table can be queried to provide a truthful description of its columns. If the schema read back contains columns that do not exist or is missing those that do, the drift detection is comparing against a fictional structure. Consequently, ghost columns not only clutter a listing but also corrupt any decisions built upon the schema.</p><p>The question of what the table’s columns are actually for proved to be a more complex issue than it initially appeared. The obvious solution was incorrect.</p><h3>The obvious answer, and why it lies</h3><p>The natural starting point is the AWS Glue Data Catalogue. Each Athena or Iceberg table has a corresponding Glue entry containing a <strong>StorageDescriptor.Columns list</strong>. To access the column list, simply request the table from Glue and read the column list. This is a standard procedure in tutorials.</p><p>Upon reviewing Glue’s output, I identified the missing column in StorageDescriptor.Columns. Despite this, Glue confidently reported a schema that no longer matched reality.</p><p>This is a subtle phenomenon that has been overlooked by many.</p><p>For an Iceberg table, Glue’s <strong>StorageDescriptor.Columns</strong> is not the schema. It is a cache. Iceberg manages its own schema, which is the fundamental purpose of the format. Schema evolution and time-travel are first-class operations and Iceberg maintains the complete history of every schema a table has ever had. Glue’s column list is a derived convenience copy and Athena’s Iceberg engine repopulates it after every write by <a href="https://www.dremio.com/wiki/union/">unioning</a> field names across the schema history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hq0VqiWgTtXaxjjZIDiKiA.png" /></figure><p>The column you dropped last Tuesday is still a member of a historical schema version and every subsequent write to the table re-resurrects it in the Glue cache. Dropped and renamed columns persist for several days before reappearing each time the table is written to. This behaviour is not a bug but a feature that shows the union of all the table’s historical states.</p><p>The catalog was telling the truth to a different question than the one I was asking.</p><h3>The fix: go to the source of truth</h3><p>Iceberg already knows its current schema precisely. It’s stored in the table’s <strong>metadata.json </strong>file, which defines the table’s current state. Glue even provides the location: the table’s <strong>Parameters.metadata_location</strong> points to the current metadata.json on S3. The catalogue holds the actual truth but also a stale cache nearby.</p><p>Instead of trusting the cache, I follow the pointer. I request the table from Glue but only to retrieve metadata_location. I then read this JSON from S3, find the current schema by its ID and return its fields.</p><p>python</p><pre>def get_iceberg_columns(table: str) -&gt; list[tuple[str, str]] | None:<br>    &quot;&quot;&quot;Reads the current schema from Iceberg&#39;s `metadata.json` (pointed at by<br>    Glue&#39;s `Parameters.metadata_location`) rather than Glue&#39;s<br>    `StorageDescriptor.Columns`. The StorageDescriptor is a cache that Athena&#39;s<br>    Iceberg engine repopulates after every write by unioning field names across<br>    the schema HISTORY — so dropped/renamed columns keep reappearing there for<br>    days after the DDL. Iceberg&#39;s own metadata.json is the source of truth.&quot;&quot;&quot;<br>    resp = _GLUE_CLIENT.get_table(DatabaseName=ICEBERG_DB, Name=table)</pre><pre>params = resp[&quot;Table&quot;].get(&quot;Parameters&quot;) or {}<br>    meta_uri = params.get(&quot;metadata_location&quot;)<br>    if not meta_uri or not meta_uri.startswith(&quot;s3://&quot;):<br>        raise RuntimeError(<br>            f&quot;iceberg_db.{table} Glue entry has no metadata_location; &quot;<br>            f&quot;refusing to fall back to StorageDescriptor since it carries &quot;<br>            f&quot;historical ghost columns.&quot;<br>        )</pre><pre>bucket, _, key = meta_uri[len(&quot;s3://&quot;):].partition(&quot;/&quot;)<br>    meta = json.loads(_S3_CLIENT.get_object(Bucket=bucket, Key=key)[&quot;Body&quot;].read())</pre><pre>current_id = meta[&quot;current-schema-id&quot;]<br>    schema = next(<br>        (s for s in meta.get(&quot;schemas&quot;, []) if s.get(&quot;schema-id&quot;) == current_id),<br>        None,<br>    )<br>    ...<br>    return [<br>        (f[&quot;name&quot;], _iceberg_type_to_glue(f[&quot;type&quot;]))<br>        for f in schema.get(&quot;fields&quot;, [])<br>    ]</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fxXxl5fx6cR64bu0tkFWIQ.png" /></figure><p>The key is meta[“current-schema-id”]. Iceberg’s metadata.json contains all the schemas a table has had, each with an identifier. This history is the source of the data pollution in the Glue cache. However, it also records the current schema. I select only that schema and discard the others. Dropped columns are retained in the older schema entries and are not included in the returned data as they are not part of the current schema.</p><h3>The detail I’m glad I got right: refuse to fall back</h3><p>If a table’s Glue entry lacks metadata_location, it is advisable to fall back to StorageDescriptor.Columns to return a value.</p><p>I deliberately do not. Reverting to the StorageDescriptor silently reintroduces the exact ghost-column bug this function is designed to prevent and does so in a code path that is not monitored. I prefer the system to fail with a clear error message rather than returning a schema I know is unreliable. A seemingly correct but incorrect schema is far more dangerous than an error. The error can be rectified quickly whereas a corrupted schema can corrupt drift detection for days before it is noticed.</p><p>That’s a principle I keep relearning: when your fix is “stop trusting the convenient-but-wrong source,” you have to close the back door too, or it creeps back in through the fallback.</p><h3>What I took away</h3><p>A catalogue serves as a convenience layer, not the definitive source of truth. This is a prevalent pitfall, surpassing the analogy of an iceberg on glue. Glue, Hive Metastore, and Unity cache and index metadata for expedient retrieval. However, for self-describing table formats such as Iceberg, Delta Lake, and Hudi, the format’s own metadata holds primacy. The catalogue’s copy may lag, cache, or even actively misrepresent the format. When they diverge, the format prevails. The Iceberg/Glue union behaviour encapsulates the most pronounced manifestation of this trap. If you are employing Delta or Hudi, consider the following query: from <em>where does my code actually access the schema, and is that the format or the catalogue?</em></p><p>Schema evolution incurs a cost that remains imperceptible until metadata examination. The very feature that renders Iceberg exceptional—its comprehensive, versioned schema history is the source of the ghost-column cache. Powerful features inadvertently expose their internal workings to adjacent systems. The knowledge that a table retains its previous schemas elucidates why the obsolete columns persistently reappear..</p><p>The statement <strong>“It succeeded” </strong>does not necessarily imply that the change was successful. While the Data Definition Language (DDL) was satisfactory, the root cause of the issue lay solely on the read side, within a caching layer that I had not previously identified as potentially unreliable. When a change fails to persist, it is prudent to scrutinise the reporting of the current state before attributing the issue solely to the change itself.</p><p>The discordant beats subside. <strong>A guard that silently degrades to an incorrect but readily available answer is not a guard</strong>. If the source of truth is unavailable, acknowledging so is more beneficial than confidently presenting falsehoods.</p><p><strong>The dropped column is retained in the metadata.json file</strong> corresponding to the schema version of that table, as per Iceberg’s design. Glue will continue to display it until the table ceases to exist. However, I have ceased requesting Glue to do so; instead, I adhere to its reference to the actual file containing the pertinent information.</p><h3>Final thought</h3><p>One of the most significant lessons from this experience was not about Apache Iceberg itself, but rather about distributed systems.<br>The component that provides the answer to your question may not always be the component that owns the actual truth.</p><p>During debugging, instead of simply asking “What is the current state?”, it is crucial to ask “Who is the authoritative source for that state?”.This distinction transformed hours of confusion into a concise five-minute diagnosis.</p><p>If this saved you from encountering phantom columns or you have encountered similar metadata surprises with Iceberg, Delta Lake, or Hudi, I would be delighted to hear about it in the comments section.</p><p><strong>Thanks for reading!</strong><br>In this article, I delve into the realm of data engineering, exploring topics such as AWS, Apache Iceberg, lakehouse architectures, and the debugging narratives that reveal the intricacies of distributed systems. If you found this article insightful, I encourage you to follow me on Medium for further practical engineering deep dives and practical lessons gained from constructing production data platforms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d66be67c7aa" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/your-glue-catalog-is-lying-about-your-schema-3d66be67c7aa">Your Glue Catalog Is Lying About Your Schema</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Bug That Deleted Nothing]]></title>
            <link>https://medium.com/towards-data-engineering/the-bug-that-deleted-nothing-b98f3c6dbadc?source=rss-7abd0b7d2b64------2</link>
            <guid isPermaLink="false">https://medium.com/p/b98f3c6dbadc</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[change-data-capture]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Abhisek Ojha]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 13:01:31 GMT</pubDate>
            <atom:updated>2026-07-17T13:49:15.459Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How Postgres TOAST quietly NULLed out our data and the four lines of SQL that stop it.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JN8XL3rU-T7EMWYsEJuVZw.png" /></figure><h3>A pipeline that looked perfectly healthy</h3><p>If you’ve built a CDC pipeline out of Postgres, or you are planning to, stop and read this first. It might save you from the bug that cost me weeks and a backfill.</p><p>My setup will look familiar. Every change from around 180 Postgres tables streams into an Apache Iceberg <strong>lakehouse</strong> on S3. PeerDB captures changes off the Postgres write-ahead log and drops them as files onto S3, then an Athena MERGE folds each batch into the Iceberg tables. Dagster runs the schedule. Near-real-time analytics on production data without hammering the production database. Thousands of teams run some version of this exact setup.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RB5c9sTEIN3EvC8QowQriQ.png" /></figure><p>Every dashboard said it was healthy, too. Row counts matched. No merge ever failed. Nothing threw. Green top to bottom, day after day. I had no reason to doubt any of it. If your pipeline looks like this, you probably don’t either.</p><p>Which is exactly why this took so long to find. The failures that page you at 3 a.m. are annoying, but at least they announce themselves. This one didn’t, and that’s what makes it worth sharing.</p><h3>The first hint</h3><p>I found it by accident. I was querying the lakehouse for something completely unrelated when a customer record caught my eye: its payload_json field, a big JSON blob we rely on downstream, was empty. Not malformed. Just NULL, where I was certain it had been full before.</p><p>My first assumption was that the source was wrong. So I checked Postgres directly, and the value was sitting right there, intact. Perfect at the source, NULL in the lakehouse.</p><p>That’s an uncomfortable thing to discover, because it means the corruption is happening inside your own pipeline. The one part of the system you thought you understood completely.</p><p>So I went looking. And once I knew what to look for, the pattern was hard to miss: it was always the big columns. The large JSON fields, the long text blobs. Never the integers, never the short strings, never the timestamps. Something was hollowing out specifically the largest columns in my tables, and only some of the time.</p><h3>Following the thread</h3><p>I started tracing individual rows. Find a row whose payload_json had gone NULL, then pull up the exact change event that last touched it.</p><p>The change event that corrupted the row turned out to be an update to something completely unrelated. A last_login timestamp, say. The user had logged in. That&#39;s it. Their payload_json hadn&#39;t been touched in weeks.</p><p>But in the raw change event PeerDB emitted, payload_json simply wasn&#39;t there. The payload contained id and last_login and nothing else. The column I cared about wasn&#39;t null. It was absent.</p><p>At first I assumed PeerDB was dropping data. Then I noticed a metadata field I’d been ignoring this whole time: _peerdb_unchanged_toast_columns. Its value was &quot;payload_json&quot;.</p><p>So the tool wasn’t losing my data. It was flagging something, and I didn’t know the word yet. That word sent me into a corner of Postgres I’d never had a reason to visit.</p><h3>Meeting TOAST</h3><p>TOAST stands for The Oversized-Attribute Storage Technique. Postgres engineers apparently have a sense of humor.</p><p>The idea: a Postgres row is supposed to fit inside an 8 KB page, and plenty of values don’t. A big JSON document, a long block of text, a chunk of binary. Rather than let those blow up the row, Postgres compresses them and, if they’re still too big, stores them out-of-line in a separate TOAST table. What stays behind in the main row is a small pointer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zC8ZDdhVETmUtV2ytQAsrg.png" /></figure><p>For everyday application work this is invisible. You insert a huge JSON blob, you read it back, it works, you move on. I’d been using Postgres for years without once thinking about it.</p><p>Now flip to the perspective of <strong>change data capture,</strong> which reads the write-ahead log. When you update a row without changing its TOASTed column, Postgres has zero reason to rewrite that big out-of-line value. It would be expensive and pointless, since nothing changed. So the WAL record for that update doesn’t include the TOASTed value at all.</p><p>Completely sensible optimization for the database. Complete landmine for anything downstream trying to reconstruct the row.</p><p>PeerDB, reading that WAL record, can’t emit a value it was never given. But here’s what I’d missed: it doesn’t paper over the gap with a fake NULL either. It omits the column from the data payload and lists its name in _peerdb_unchanged_toast_columns. Effectively: &quot;I don&#39;t have this one. It didn&#39;t change. Look up the current value yourself.&quot;</p><p>The tool had been telling me the truth the whole time. My code just wasn’t listening.</p><h3>The four words that were corrupting everything</h3><p>My MERGE did the obvious thing at that point. For a matched row, set every column from the incoming event:</p><pre>SET payload_json = &lt;value extracted from the source event&gt;</pre><p>And when you extract a JSON field that isn’t present in the payload, you get NULL.</p><p>So every time a user did anything other than change their payload_json (logged in, updated a setting, anything at all), my merge set payload_json = NULL and overwrote a perfectly good value with nothing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NosU7DHfHND_B708wLTbZA.png" /></figure><p>Suddenly the whole pattern made sense. It was always the big columns because those are the ones that get TOASTed. It was intermittent because it only struck when a row was updated without touching its large field, which is honestly most updates. And nothing ever errored because writing a NULL is a perfectly valid operation. Row counts don’t change. Schemas don’t change. The pipeline stays green while it quietly eats your most important data.</p><p>I’d been staring at a healthy dashboard sitting on top of slow, silent corruption.</p><h3>Building the fix</h3><p>Once I understood the mechanism, the correct behavior was easy to state. For every column, on every update:</p><ol><li>If the column is named in _peerdb_unchanged_toast_columns, it means &quot;unchanged and omitted,&quot; so keep whatever&#39;s already in the target table.</li><li>Otherwise, take the incoming value. Even if it’s NULL, because sometimes an update genuinely clears a field, and I have to honor that.</li></ol><p>The second rule is the subtle one. I couldn’t just skip NULLs, because a NULL can be the truth. Think of an update that deliberately clears a notes column. The only thing that can tell &quot;unchanged and omitted&quot; apart from &quot;deliberately set to NULL&quot; is that metadata string, so the metadata string is what the logic has to read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*El8YBlZAfFnRWt0tQxKQPw.png" /></figure><p>I wrote a small function that generates a per-column CASE expression:</p><pre>def _toast_aware_update_expr(col: str) -&gt; str:<br>    # regex with comma/start/end boundaries so &quot;name&quot; doesn&#39;t match &quot;long_name&quot;<br>    return (<br>        f&#39;&quot;{col}&quot; = CASE &#39;<br>        f&#39;WHEN regexp_like(s.&quot;_peerdb_unchanged_toast_columns&quot;, \&#39;(^|,){col}($|,)\&#39;) &#39;<br>        f&#39;THEN t.&quot;{col}&quot; &#39;   # in the unchanged list → preserve the target&#39;s value<br>        f&#39;ELSE s.&quot;{col}&quot; &#39;   # otherwise take the source (may legitimately be NULL)<br>        f&#39;END&#39;<br>    )</pre><p>t is the target, the row already in Iceberg. s is the source, the incoming change. If the column is in the unchanged list, keep t. Otherwise take s. It produces SQL like this:</p><pre>&quot;payload_json&quot; = CASE<br>    WHEN regexp_like(s.&quot;_peerdb_unchanged_toast_columns&quot;, &#39;(^|,)payload_json($|,)&#39;)<br>    THEN t.&quot;payload_json&quot;   -- unchanged: leave it alone<br>    ELSE s.&quot;payload_json&quot;   -- changed: take the new value<br>END</pre><p>One trap in that regex, and yes, I stepped in it. The metadata is a flat comma-separated string like &quot;name,payload_json,bio&quot;. My first instinct was a plain substring check, but that would let a column called name match inside long_name or nickname, and I&#39;d end up preserving a stale value on a column that actually had changed. Which is a subtler version of the exact bug I was trying to fix. The anchors (^|,) and ($|,) force the match to be a whole list element, bounded by a comma or the end of the string. Two small anchors, and skipping them puts you right back where you started.</p><h3>The design decision I’m most happy with</h3><p>I could have worked out which columns are TOAST-eligible and wrapped only those in the CASE. Instead I apply it to every non-primary-key column, uniformly:</p><pre>non_pk_cols = [n for n, _ in business_cols if n not in pks]</pre><pre>biz_update = &quot;,\n&quot;.join(<br>    _toast_aware_update_expr(c) for c in non_pk_cols<br>)</pre><p>Here’s why that works. A non-TOAST column, an integer or a short string, can never appear in _peerdb_unchanged_toast_columns, because Postgres only omits out-of-line values. For those columns the WHEN is always false and the CASE falls through to ELSE s.&quot;col&quot;, which is ordinary source-wins behavior. Exactly what I&#39;d want anyway.</p><p>By blanket-applying the guard, I never have to maintain a list of which columns are TOASTable, and I can’t forget to wrap a new one when the schema changes. It’s a no-op where it isn’t needed and a safeguard where it is. I went in expecting the uniform version to be the lazy option. It turned out to be the safer one.</p><p>Primary keys are the one exception. They’re excluded, because you never update a join key, and PKs don’t get TOASTed anyway.</p><h3>Where it lives in the bigger picture</h3><p>The TOAST handling is one clause inside a larger MERGE, and the other pieces are worth seeing too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z3dY79Ce_DqQ0tJMijaWZQ.png" /></figure><p>Before upserting, I collapse multiple changes to the same row down to just the latest one: ROW_NUMBER() partitioned by primary key, ordered by timestamp descending, keep the top row. If a record changed three times inside one batch, only its final state gets applied. That dedup is also what makes the MERGE idempotent. I can reprocess a window of already-merged rows to catch late-arriving changes, and re-applying the same latest state does nothing.</p><p>From there the MERGE branches three ways. A Postgres delete becomes a real DELETE. A matched row gets the TOAST-aware UPDATE described above, plus audit columns. A brand-new row gets a straight INSERT, no TOAST guard needed, since there’s no prior value to preserve.</p><p>The mental model of the whole thing fits in a sentence: for each row’s latest change, delete it if it’s a delete; otherwise upsert every non-PK column while preserving anything Postgres flagged as unchanged-and-omitted.</p><p>One alternative I looked at and rejected: re-reading the full existing row from Iceberg and reconstructing it on every update. That doubles your I/O on exactly the largest columns, the TOASTed ones you’re trying to protect. The CASE only ever inspects a small metadata string and preserves the big out-of-line value by reference. Cheaper and more correct at the same time, which doesn’t happen often.</p><h3>What I actually learned</h3><p>I fixed the merge, backfilled the damage, and the big columns stopped disappearing. A few things stuck with me beyond the incident itself.</p><p><strong>CDC hands you deltas,</strong> not snapshots, and deltas can leave things out. The absence of a value is information in its own right. Treating “absent” as “NULL” is the root of a whole family of silent-corruption bugs. TOAST just happens to be the one I met first.</p><p><strong>Your source database’s internals leak into your correctness whether you invited them or not</strong>. I never expected an 8 KB-page storage optimization to shape my merge logic, but it did, and there was no way around it. The leak always lands on the consuming side.</p><p><strong>The bugs that don’t throw are the ones to fear.</strong> A green pipeline is not the same thing as a correct pipeline. A MERGE writing NULLs sails through every row-count reconciliation you can build. Given the choice, I’d rather make the merge correct by construction than try to catch corruption after the fact.</p><p>And read the metadata your tools give you. _peerdb_unchanged_toast_columns existed the whole time, doing its job, telling the truth. The rest was on me.</p><p>In the end it’s a handful of lines of conditional SQL and one carefully anchored regex. Not much code for the difference between a lakehouse you trust and one that’s quietly hollowing out its own most valuable columns while every dashboard tells you everything’s fine.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b98f3c6dbadc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/the-bug-that-deleted-nothing-b98f3c6dbadc">The Bug That Deleted Nothing</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to stop your CDC pipeline from burning your AWS budget]]></title>
            <link>https://medium.com/towards-data-engineering/how-to-stop-your-cdc-pipeline-from-burning-your-aws-budget-a305955ce16f?source=rss-7abd0b7d2b64------2</link>
            <guid isPermaLink="false">https://medium.com/p/a305955ce16f</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-visualization]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Abhisek Ojha]]></dc:creator>
            <pubDate>Fri, 17 Jul 2026 12:58:35 GMT</pubDate>
            <atom:updated>2026-07-17T14:01:43.219Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Four layout fixes that took our Athena bill from $5,950 to $5 a day :a CDC-to-Iceberg story</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b9oax1S9oZvFMA5YQCZXFw.png" /></figure><h3>The number I couldn’t unsee</h3><p><strong>$5,950 in a single day.</strong></p><p>That was the zenith. One day, one AWS account, one line item — EUC1-DataScannedInTB — Athena reading bytes off S3 at $5 per terabyte. And it was not a transient surge; the pipeline was averaging thousands of dollars per day, consistently, and increasing as we added tables.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQAzWPAW2mwr9YZMpiruKg.png" /></figure><p>Here is the portion that still causes discomfort: we had approximately 190 GB of data at rest. In total. We were paying to scan it thousands of times over—exceeding half a petabyte per day. A dataset that could be stored on an inexpensive SSD was generating a bill that, annually, surpassed a million dollars. On test data, at 36 tables, on the way to a 180-table target that would have driven the daily cost past $15,000.</p><p>The pipeline functioned flawlessly throughout its operation, That’s what made it more dangerous.</p><p>This is the story of how we got that daily number down to about $4–5 — and why there was no single heroic fix. It took four levers, and the interesting engineering is in how they fit together.</p><p>This narrative illuminates the process through which we successfully reduced the daily expenditure to approximately $4–5. Notably, there was no singular, heroic solution to this challenge. Instead, we achieved this outcome by employing four distinct levers, and the intriguing aspect lies in the <a href="https://www.vocabulary.com/dictionary/intricate">intricate</a> manner in which these levers are <a href="http://vocabulary.com/dictionary/interwoven">interwoven</a>.</p><h3>Where the money went</h3><p>The setup was textbook lakehouse. PeerDB captures changes off the Postgres write-ahead log (change data capture, or CDC) and lands them on S3 as Avro. Athena runs MERGE INTO to fold each batch into Apache Iceberg tables. Clean on a whiteboard.</p><p>I profiled the queries, and the median MERGE was scanning 139 GB — to update one table with a few minutes of changes. We ran ~30 of those per cycle (one per active table), plus 5 preamble full-scan probes, roughly 89 times a day:</p><pre>5 preamble queries  × ~190 GB  ≈   950 GB<br> ~30 per-table MERGEs × ~139 GB  ≈ 4,170 GB<br> ────────────────────────────────────────────<br> per cycle:                      ≈   5.1 TB   ($25 base → $66 at peak)<br> × ~89 cycles/day                →   thousands of dollars daily</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JCe7mp8Ovru1iXnlvUo6hA.png" /></figure><p>Three innocent-looking decisions had compounded into this:</p><p><strong>1. PeerDB writes every table into one flat Avro stream.</strong> A row’s table identity lives in a column (_peerdb_destination_table_name), not in the storage layout. So to merge transaction, Athena still reads every other table&#39;s rows off S3 and filters them out after.</p><p><strong>2. Avro has no file-level statistics.</strong> Parquet and ORC keep per-file min/max stats, so Athena can skip files a predicate can’t match. Avro can’t. Every WHERE filters rows, never files — you pay for every byte regardless.</p><p><strong>3. The landing prefix was one unpartitioned monolith that grew for seven days.</strong> Nothing to prune, everything re-read, every cycle.</p><p>The bill wasn’t a bug. It was the faithful product of reading everything, being unable to skip anything, and letting “everything” grow.</p><h3>Lever 1 — keep the source small (the archive layer)</h3><p>The first realization: the merge’s source kept growing, but each merge only needed the last few minutes of changes. So after a batch is safely merged into every table, we move it out of the landing prefix — copy to a sibling cdc/archive/ prefix, delete from landing. The live landing zone stays permanently tiny: 5–50 MB instead of 190 GB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fwu35KJZkhzXjn-RAStxCQ.png" /></figure><p>Two details made it real:</p><p><strong>The archive never reads a byte of data.</strong> PeerDB names each file after its batch id (28412.avro), so archiving is pure S3 metadata: list, parse the filename, copy, delete. Moving data costs pennies because we never open the files.</p><p><strong>Sibling, not child.</strong> Athena scans a Glue location recursively. Archiving to cdc/…/archive/ (a child of the table&#39;s path) would do nothing — the files would still be in scope. It has to be a true sibling, outside the table&#39;s LOCATION, to actually leave the scan path. An invisible mistake that would have silently negated the whole thing.</p><p>But here’s the honest part: the archive alone only fixes the preamble and shrinks each source scan’s raw size. It does not fix “every MERGE reads every table.” Even a small Avro landing is still one undifferentiated blob with no stats. For that, we had to change the shape of the data.</p><h3>Lever 2 — partition the source by table, in a format that prunes</h3><p>Once per cycle, before the merges, we now run a single CREATE TABLE AS SELECT that reads the small landing window and writes a transient staging table — as Parquet, ZSTD-compressed, and critically:</p><pre>CREATE TABLE raw_db.peerdb_cdc_staged_&lt;run&gt; WITH (<br>    format = &#39;PARQUET&#39;,<br>    partitioned_by = ARRAY[&#39;_peerdb_destination_table_name&#39;],<br>    write_compression = &#39;ZSTD&#39;<br>) AS SELECT ... FROM &lt;landing&gt; WHERE _peerdb_batch_id BETWEEN ...</pre><p>This flips two of the three root causes at once. The table identity that used to live in a column is now a partition directory, so each per-table MERGE reads only _peerdb_destination_table_name=transaction/ — not the whole cycle. And it&#39;s Parquet, so within that partition Athena gets real column statistics and file skipping. We pay one bounded scan to stage the window, and every MERGE after that reads only its own slice of it. &quot;Read all tables to merge one table&quot; is gone — structurally, not by tuning.</p><h3>Lever 3 — bucket every target on its primary key, sized to the table</h3><p>The MERGE’s target side matters too. Every Iceberg table is partitioned by bucket(N, &lt;pk&gt;) — hash-bucketed on the primary key. Because the MERGE joins on the PK, bucketing on that same key lets Athena prune the target read to just the buckets that can contain matching rows, instead of scanning the whole table.</p><p>The non-obvious part was choosing N. Too few buckets and each is huge; too many and you drown in tiny files. So the bucket count is a deliberate, per-table decision driven by size and cardinality:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jCN1acLl03iNhtslg3zzdw.png" /></figure><p>Bucket count Used for Why 32 (default) Most lookup / config / mid tables Sensible baseline; keeps file sizes reasonable 64 Larger tables (task, reported_people, …) More spread for more data 100 The biggest, highest-cardinality tables (screening, person_history, …) Wide fan-out so no single bucket is enormous 10 The busiest tables — which also get day-partitioning Fewer buckets on purpose (see below)</p><p>That last row is the subtle one. The highest-velocity tables (transaction, score, sanction, …) get only 10 buckets — fewer than a boring lookup table. That&#39;s not a mistake: those tables are also day-partitioned, so their data is already split across hundreds of daily partitions. Multiply hundreds of days by a big bucket count and you&#39;d get an explosion of tiny files, which is its own performance and cost disaster. Ten buckets per day is plenty. The two partition dimensions have to be sized together.</p><h3>Lever 4 — day-partition only the tables big enough to earn it</h3><p>For the high-velocity, time-series tables we add a second partition dimension: day(&lt;created_time&gt;). The combined spec looks like:</p><pre>-- busy time-series table<br>PARTITIONED BY (day(`created_time`), bucket(10, `id`))</pre><pre>-- everything else<br>PARTITIONED BY (bucket(32, `id`))</pre><p>The temptation is to day-partition everything. That’s a trap — a small lookup table split by day is just thousands of near-empty partitions, which hurts. So day-partitioning is applied selectively, based on measured size, and we let a job make the call rather than guessing.</p><p>A weekly asset sizes every non-time-partitioned table using Iceberg’s own metadata — no data scan required:</p><pre>SELECT sum(file_size_in_bytes) FROM &quot;screening$files&quot;</pre><p>If any table crosses a 5 GiB live-data threshold, the check fails loudly and tells the operator exactly what to do: add a time_partition_column and run the partition-swap job for that table. Small tables are left alone with just their bucketing; a table only earns a day partition once it&#39;s genuinely large. Capacity planning as a guardrail, not a gut call.</p><h3>How the levers stack</h3><p>None of these is sufficient alone, and that’s the real lesson:</p><pre>Archive        → shrinks the source from 190 GB to ~20 MB<br> Stage-by-table → each MERGE reads only its own partition, as prunable Parquet<br> Bucket-by-PK   → target read prunes to matching buckets on the join key<br> Day-partition  → big time-series tables scan only the relevant days<br> ──────────────────────────────────────────────────────────────────<br> per-MERGE source scan: 139 GB → single-digit MB<br> daily bill:            ~$5,950 → ~$4–5   (≈1000× on the busiest tables)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bGFAZ9TFT42-WdohknUWOw.png" /></figure><p>The archive changed how much raw data sits in the scan path. The partitioning changed how much of it any given query has to touch. You need both. Shrinking the source without partitioning still makes every table read every other table’s rows; partitioning without shrinking the source still drags seven days of history through every cycle.</p><h3>What I took away</h3><p><strong>On a lakehouse, your bill is bytes-scanned, and bytes-scanned is decided by layout — not query volume.</strong> File format, partition columns, bucket counts, directory structure: those settle your cost long before any SQL runs.</p><p><strong>Cutting a cloud bill is a system, not a switch.</strong> I badly wanted one heroic fix. There wasn’t one. There were four modest changes that only worked in combination, and understanding why each was insufficient alone was the actual engineering.</p><p><strong>Partition dimensions interact — size them together.</strong> The counterintuitive “busiest tables get the fewest buckets” only makes sense once you see buckets and day-partitions multiplying into file count. Tuning one in isolation would have quietly recreated the problem.</p><p><strong>Let measurements make the structural calls.</strong> Day-partitioning by a measured 5 GiB threshold — instead of a blanket rule or a hunch — is what keeps small tables simple and big tables fast, automatically, as the data grows.</p><p>We had 190 GB of data and were scanning half a petabyte a day to serve it. The fix wasn’t a bigger cluster or a pricing deal. It was four ideas about shape: keep the source small, partition it by table, bucket the targets on their key, and day-partition only what’s big enough to matter. Everything else was details — and, as usual, the details were the whole job.</p><h3>Resources</h3><ul><li><a href="https://aws.amazon.com/athena/pricing/">Amazon Athena pricing</a> — the $5/TB-scanned model that drives everything in this post</li><li><a href="https://docs.aws.amazon.com/athena/latest/ug/merge-into-statement.html">Athena MERGE INTO reference</a></li><li><a href="https://docs.aws.amazon.com/athena/latest/ug/create-table-as.html">Athena CTAS reference</a> — the stage-by-table trick in Lever 2</li><li><a href="https://iceberg.apache.org/docs/latest/partitioning/">Apache Iceberg partitioning</a> — bucket and day transforms used in Levers 3 and 4</li><li><a href="https://iceberg.apache.org/docs/latest/spark-queries/#files">Iceberg metadata tables</a> — the $files table behind the 5 GiB threshold check</li><li><a href="https://docs.peerdb.io/">PeerDB documentation</a> — the CDC tool capturing changes off the Postgres WAL</li><li><a href="https://parquet.apache.org/">Apache Parquet</a> and <a href="https://avro.apache.org/">Apache Avro</a> — the two file formats whose statistics (or lack thereof) shaped the bill</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a305955ce16f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/how-to-stop-your-cdc-pipeline-from-burning-your-aws-budget-a305955ce16f">How to stop your CDC pipeline from burning your AWS budget</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Zero Records. 6 Hours. Why Your Airbyte CDC Sync Lies to You About Being Idle.]]></title>
            <link>https://medium.com/towards-data-engineering/zero-records-6-hours-why-your-airbyte-cdc-sync-lies-to-you-about-being-idle-9d7040cf6d1b?source=rss-7abd0b7d2b64------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d7040cf6d1b</guid>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Abhisek Ojha]]></dc:creator>
            <pubDate>Sat, 04 Apr 2026 06:27:24 GMT</pubDate>
            <atom:updated>2026-04-04T06:27:24.567Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>It was late. The sync had been running for 5hours and 56 minutes. Zero bytes. Zero records. And the worst part? Everything looked completely normal.</blockquote><p>I refreshed the Airbyte UI at least twenty times that night. The record count never moved. The logs kept printing the same heartbeat line every 10 seconds. The sync status said “running”,not failed, not stuck, just quietly, confidently running. Into nothing.</p><p>If you’ve set up <strong>Airbyte CDC</strong> on a <strong>Postgres</strong> database, there’s a good chance you’ve seen this. Your source database is quiet. No inserts. No updates. No deletes. And yet — the sync just keeps running. And running. And running.</p><p>This is not a bug in <strong>Airbyte</strong>. It’s not a misconfiguration. It’s a fundamental misunderstanding of how <strong>Debezium</strong> — the engine powering Airbyte’s Postgres CDC — actually works. And once you understand it, the fix is one SQL statement.</p><p>I’m writing this because I spent hours figuring it out so you don’t have to.</p><h3>😱 The Shocking Number</h3><p>We were building a data pipeline for ingesting transaction and alerting data from a live Postgres RDS instance into an analytics layer every 15 minutes.</p><p>First sync. We triggered it. It ran.</p><h4><strong>5 hours 56 minutes. Zero bytes. Zero records loaded.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rney5KmaBkqshiLOFKIf3A.png" /></figure><p>Not once. Every single run. Our 15-minute schedule was completely broken — every new trigger was hitting a 409 Conflict error because the previous sync was still running and blocking the connection.</p><p>We tried cancelling and restarting. We checked the Postgres logs — the source database was completely idle. We checked the Airbyte connector version. We restarted pods. Nothing changed.</p><p>The pipeline was deadlocked before it ever did any real work.<br>🤯 Common Mistakes We Made Before Finding the Fix</p><p>Before we found the root cause, we went down every wrong path you can imagine. Sound familiar?</p><p>❌ <strong>Increased the memory limits</strong> on the Airbyte connector pod — didn’t help<br>❌ <strong>Restarted the Airbyte server</strong> — sync resumed exactly where it left off<br>❌ <strong>Checked RDS parameter groups</strong> for connection timeouts — all looked fine<br>❌ <strong>Reduced the number of tables</strong> in the connection — helped slightly but didn’t solve it<br>❌ <strong>Set </strong><strong>Initial Waiting Time = 300 seconds</strong> — countdown never triggered<br>❌ <strong>Added a Debezium heartbeat query</strong> — still didn’t work on its own</p><p>Every single one of these felt like it should work. None of them did. Because we were treating the symptom, not the cause.</p><h4><strong>🔍 What’s Actually Happening Inside Debezium ?</strong></h4><p>To understand the fix, you need to understand what <strong>Debezium</strong> actually does when it connects to your Postgres database.</p><p>Postgres uses a <strong>Write-Ahead Log (WAL)</strong> — a sequential record of every single transaction committed to the database. Before any data is written to disk, it gets written to the WAL first. This is how Postgres guarantees durability and enables replication. Think of it as a continuous journal of everything that ever happens on your database instance.</p><p>When Airbyte sets up CDC, it creates a <strong>logical replication slot</strong> on your Postgres instance and starts streaming the WAL through Debezium. Debezium reads this stream, filters for changes relevant to your tables, and sends them to your destination — in our case, S3.</p><p>Here’s the part that catches everyone:</p><blockquote><strong><em>By default, Debezium streams the ENTIRE WAL — not just your tables.</em></strong></blockquote><p>Every autovacuum job. Every background maintenance task. Every write from every other application connected to the same Postgres instance. All of it flows through the WAL, and all of it reaches Debezium.</p><p>So when you configure Initial Waiting Time = 300 seconds — which is supposed to tell <strong>Debezium</strong> &quot;exit after 5 minutes if you see no changes&quot; — it never fires. Because from <strong>Debezium&#39;s</strong> perspective, <strong>the WAL is never quiet.</strong> Other activity keeps it alive and the timer keeps resetting.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3dkr4GrlF7intTRhZ5MLig.png" /></figure><p>This is the trap. And it’s invisible because the Airbyte UI shows the sync as “running” — not hanging, not erroring, just running — while loading absolutely nothing into your destination.</p><h3><strong>✅ Fix 1 — Create a Dedicated Postgres Publication</strong></h3><p>A Postgres <strong>publication</strong> is a named set of tables that the replication system should track. When you create one and point Airbyte at it, Debezium only receives WAL events for those specific tables — everything else is filtered out at the source, before it ever reaches Debezium.</p><p>This is the single most impactful change you can make. Everything else is secondary.</p><h4><strong>Step 1 — Create the publication on your Postgres RDS instance:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*152k5kFf1Ie3uQVpFG5b8g.png" /></figure><h4><strong>Step 2 — Create a heartbeat table.</strong></h4><p>Without this, <strong>Debezium</strong> has no way to write a real WAL record to confirm it has caught up to the current <strong>LSN position</strong>. The countdown timer relies on actual WAL writes — not just reads — to determine when it’s safe to exit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-f_CE70GsASy0W2JQaknDA.png" /></figure><h4><strong>Step 3 — In Airbyte → Sources → Postgres → Edit, configure these settings:</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7OKUw81CI88iGDTzcO0ErQ.png" /></figure><p>With this setup, Debezium now only watches your specific tables. When they’re quiet, it genuinely sees silence — and the countdown starts ticking properly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z8UFYZDoOe3IKs3U-HPiXA.png" /></figure><h3><strong>💥 Fix 2 — Handle the 409 Conflict Gracefully</strong></h3><p>Once syncs started completing in under 7 minutes, we hit the next problem. Our orchestrator was scheduling a new sync every 15 minutes. Occasionally, a sync would run slightly longer — and when the next trigger fired, Airbyte returned:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JtpOTxNhtbMN1HWScbYxMg.png" /></figure><p>Airbyte returns 409 when you try to start a new sync on a connection that already has an active job running. Our code was treating this as a hard failure and crashing the entire pipeline run.</p><p>But think about it — a sync already running is not a failure. It means the previous run is still in progress. The right response is to find that running job and wait for it to finish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DjkPrZPnptFUJxKApy6n8w.png" /></figure><p>Now instead of crashing, the pipeline gracefully hands off to the already-running sync and waits for it to complete. No lost runs. No broken schedules.</p><h3><strong>🟡 Fix 3 — Treat </strong><strong>incomplete as a Success</strong></h3><p>The last surprise was subtle. After all the fixes above, some syncs were returning a status of incomplete instead of succeeded. Our polling code was treating anything other than succeeded as a failure — which meant downstream steps like merging and normalizing never ran, even when perfectly valid data had already landed in the destination.</p><p>Here’s what incomplete actually means in Airbyte: the sync processed the records it could find, advanced the LSN checkpoint to mark progress, and exited gracefully. It is <strong>not</strong> a failure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WbiBtJc4lLn3_JaYzB-sAA.png" /></figure><p>With this change, partial syncs no longer blocked the pipeline. Every valid sync — whether succeeded or incomplete — flows through to downstream processing correctly.</p><h3>🔑 Key Takeaways</h3><ol><li><strong>Debezium watches the entire WAL by default</strong> — not just your tables. On a busy Postgres instance this means Initial Waiting Time is completely ineffective without scoping your publication first.</li><li><strong>A dedicated publication is the single most impactful fix</strong> — once Debezium only watches your tables, the timeout works exactly as documented. Syncs that hung for hours complete in minutes.</li><li><strong>The heartbeat table is not optional</strong> — without it, Debezium cannot write a real WAL record to confirm it has caught up. The countdown relies on actual WAL writes to function correctly.</li><li><strong>409 Conflict is not an error</strong> — it&#39;s a scheduling overlap. Handle it by latching onto the running job instead of crashing.</li><li><strong>incomplete is not a failure</strong> — Airbyte advances the checkpoint and syncs what it can. Always let your downstream steps run.</li></ol><p><em>Have you hit this before? How long was your longest CDC sync with zero records? Drop it in the comments — I’d genuinely love to know I’m not alone. 👇</em></p><p><em>Next up: How we orchestrated the entire pipeline with Dagster — sensors, asset dependencies, Helm conflicts and all. Coming soon.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d7040cf6d1b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/zero-records-6-hours-why-your-airbyte-cdc-sync-lies-to-you-about-being-idle-9d7040cf6d1b">Zero Records. 6 Hours. Why Your Airbyte CDC Sync Lies to You About Being Idle.</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A step-by-step guide using AWS DMS and Airbyte CDC on PostgreSQL]]></title>
            <link>https://medium.com/towards-data-engineering/a-step-by-step-guide-using-aws-dms-and-airbyte-cdc-on-postgresql-d603b498c675?source=rss-7abd0b7d2b64------2</link>
            <guid isPermaLink="false">https://medium.com/p/d603b498c675</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Abhisek Ojha]]></dc:creator>
            <pubDate>Thu, 26 Mar 2026 19:34:57 GMT</pubDate>
            <atom:updated>2026-04-04T06:27:07.932Z</atom:updated>
            <content:encoded><![CDATA[<p><em>How to combine AWS DMS bulk load and Airbyte Change Data Capture to migrate millions of rows without taking your production database offline — and keep it that way.</em></p><h3>Who This Is For</h3><p>You’re a data engineer running a PostgreSQL database in production. You need to migrate that data into a modern lakehouse (Apache Iceberg on S3, queryable via Athena), but you cannot afford any downtime, and you cannot afford to miss a single row. This guide walks through every decision, every risk, and every line of configuration you’ll need.</p><h3>The Core Problem</h3><p>Most migration guides give you two bad choices:</p><ul><li><strong>Take a snapshot and restore it</strong> — downtime, stale data, and you miss everything that changed during the migration.</li><li><strong>Stream changes only (CDC)</strong> — fast but you have no historical baseline, so you start with an empty lake.</li></ul><p>The approach here solves both simultaneously by running <strong>two pipelines in parallel from the same moment in time (T0)</strong>: AWS DMS for the historical bulk load, and Airbyte CDC for every change happening <em>right now</em>.</p><h3>Architecture Overview</h3><pre>PostgreSQL (Primary, WAL logical)<br>         │<br>         ├──── Snapshot copy at T0 ──────────► AWS DMS ──► s3://raw/dms/ ──► Iceberg (merged once at end)<br>         │<br>         └──── Replication Slot at T0 ─────► Airbyte CDC ──► s3://raw/airbyte/ ──► Iceberg (continuous)</pre><p>The two streams meet at a single <strong>Iceberg MERGE</strong> step, where a timestamp guard ensures only the newest version of any row ever wins — no matter which pipeline delivers it.</p><h3>Phase 1 — AWS DMS: The Bulk Load</h3><h3>What DMS Does</h3><p>DMS reads from a <strong>copy/replica</strong> of your PostgreSQL database — not the live primary. This is critical: it means your production traffic is completely untouched during a full table scan of potentially tens of millions of rows.</p><p>Every row is written as a <strong>Parquet file</strong> to a staging S3 path (e.g., s3://your-bucket/staging/dms/). DMS stamps each row with a _dms_load_ts timestamp.</p><p><strong>Important nuance:</strong> DMS in full-load mode treats every row as an INSERT. There is no operation column, so _is_deleted is always false for all DMS rows.</p><h3>Normalise View (DMS)</h3><p>Before the DMS data can be merged into Iceberg, a view normalises it into a unified shape:</p><pre>SELECT<br>    id,<br>    -- ... your business columns ...<br>    _dms_load_ts        AS _loaded_at,<br>    &#39;DMS&#39;               AS _record_source,<br>    false               AS _is_deleted<br>FROM s3_dms_raw</pre><h3>When Does the DMS Data Land in Iceberg?</h3><p><strong>Only after the full load is completely finished.</strong> The staging bucket acts as a waiting room. Once DMS is done, a single MERGE writes all historical rows into Iceberg. After that, the staging bucket is deleted — it is no longer needed.</p><h3>Phase 2 — Airbyte: Continuous CDC from T0</h3><h3>What Airbyte Does</h3><p>A <strong>replication slot</strong> (WAL bookmark) is created on the live PostgreSQL database at exactly T0 — the same moment DMS starts on the copy. This is the key insight: Airbyte captures <em>every single change</em> that occurs from T0 onwards, including all changes happening while DMS is still running its bulk load.</p><p>Airbyte reads the WAL via the pgoutput protocol and writes delta rows as Parquet to S3:</p><pre>s3://your-bucket/raw/airbyte/public/orders/2024/03/25/<br>    ├── 0.parquet<br>    └── 1.parquet</pre><p>Each file includes Airbyte’s internal columns: _airbyte_raw_id, _airbyte_extracted_at, _airbyte_generation_id, and _ab_cdc_deleted_at (populated only on DELETE events).</p><h3>Normalise View (Airbyte)</h3><pre>SELECT<br>    id,<br>    -- ... your business columns ...<br>    _airbyte_extracted_at                           AS _loaded_at,<br>    &#39;AIRBYTE&#39;                                       AS _record_source,<br>    (_ab_cdc_deleted_at IS NOT NULL)                AS _is_deleted,<br>    ROW_NUMBER() OVER (<br>        PARTITION BY id ORDER BY _airbyte_extracted_at DESC<br>    )                                               AS _row_num<br>FROM s3_airbyte_raw<br>WHERE _row_num = 1   -- deduplicate Airbyte restart replays</pre><p>Airbyte merges into Iceberg <strong>immediately and continuously</strong>. This pipeline never stops.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IEL9NOvn_GstZiAjuG51pQ.png" /></figure><h3>Duplicate Handling — Two Lines of Defence</h3><h3>Defence 1: ROW_NUMBER() Dedup in the Normalise View</h3><p>If Airbyte restarts and replays events, the same change can arrive twice in one batch. The ROW_NUMBER() partition in the normalise view keeps only the latest version of each row before it reaches the MERGE.</p><h3>Defence 2: The MERGE Timestamp Guard</h3><pre>MERGE INTO iceberg_db.orders AS target<br>USING normalised_source AS source<br>ON target.id = source.id<br>WHEN MATCHED AND source._loaded_at &gt; target._loaded_at THEN<br>    UPDATE SET ...<br>WHEN NOT MATCHED THEN<br>    INSERT ...</pre><p>The condition source._loaded_at &gt; target._loaded_at means:</p><ul><li>If DMS arrives with a row timestamped T0 but Airbyte already wrote an UPDATE for that row at T2 — <strong>DMS is silently skipped. Airbyte wins.</strong></li><li>If a stale or duplicate event arrives — <strong>it is ignored. No overwrite, no error.</strong></li></ul><h3>Iceberg MERGE — The Three Cases</h3><p>The final merge handles:</p><ol><li><strong>INSERT</strong> — new row, never seen before → write it</li><li><strong>UPDATE</strong> — row exists but source timestamp is newer → overwrite it</li><li><strong>DELETE</strong> — sets _is_deleted = true (soft delete, invisible to consumers)</li></ol><p>After each merge run, run <strong>compaction</strong> and <strong>snapshot expiry</strong> jobs to keep table health and query performance strong.</p><h3>Querying with Athena</h3><p>All consumer queries filter WHERE _is_deleted = false. Soft-deleted rows are invisible without any extra logic.</p><p>For <strong>GDPR hard deletes</strong>, run expire_snapshots immediately after the DELETE statement to physically purge data from S3 — removing it from all historical snapshots.</p><h3>Risk Assessment: What Can Go Wrong and How to Prevent It</h3><h3>Risk 1 — Airbyte Goes Down and WAL Files Pile Up</h3><p><strong>What happens:</strong> Airbyte crashes or loses its connection. PostgreSQL cannot delete WAL files because the replication slot bookmark is still there — so they accumulate on disk. If they fill the RDS disk entirely, the <strong>production database goes down</strong> — not just Airbyte.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yardkqZwsuhX0_x3ZcqmFw.png" /></figure><p><strong>Solution:</strong> Set a CloudWatch alarm on OldestReplicationSlotLag at <strong>5 GB(<em>Choose a threshold that fits your data volume</em>)</strong>. When it fires, restart Airbyte. It picks up from exactly where it stopped — the bookmark is still valid. No data is lost.</p><h3>Risk 2 — First Alarm Missed, WAL Keeps Growing</h3><p><strong>What happens:</strong> Nobody acted on the 5 GB<strong>(<em>Choose a threshold that fits your data volume</em>)</strong> alarm. WAL is now approaching 9 GB. At 10 GB, PostgreSQL forcibly kills the replication slot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cqz5z087525wZKAoIck4Mw.png" /></figure><p><strong>Solution:</strong> Set a <strong>second, louder alarm at 9 GB</strong> — this one must page someone directly. At this point either restart Airbyte immediately, or manually drop the slot and plan a recovery.</p><h3>Risk 3 — Both Alarms Missed — PostgreSQL Kills the Slot</h3><p><strong>What happens:</strong> max_slot_wal_keep_size = 10 GB kicks in. PostgreSQL forcibly invalidates the replication slot to save the database from a disk-full crash. The database stays alive, but Airbyte&#39;s bookmark is gone.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9zsJXLK-CC4sLZBWM0-wUg.png" /></figure><p><strong>Solution:</strong> Set max_slot_wal_keep_size = 10 GB <strong>(<em>Choose a threshold that fits your data volume</em>)</strong>in the RDS parameter group <strong>before go-live</strong>. This is a one-time setting. The DB automatically self-protects even with zero human intervention.</p><h3>Risk 4 — Slot is Gone, Full Re-Read Needed</h3><p><strong>What happens:</strong> The slot was invalidated. Airbyte needs to read every single row from scratch to rebuild its baseline.</p><p><strong>Wrong approach:</strong> Running Airbyte full refresh on the primary puts huge read pressure on production during business hours.</p><p><strong>Right approach:</strong> Re-run DMS from a <strong>fresh snapshot copy</strong> — DMS reads from an isolated copy, so the primary is completely untouched. Run this during the pre-agreed off-peak window. Once DMS finishes, create a fresh replication slot and restart Airbyte in CDC-only mode from the current WAL position. The pipeline is back to normal — this is exactly the same as the original go-live setup.</p><h3>PostgreSQL Partitioned Tables — Special Handling</h3><p>If your database uses table partitioning (e.g., one partition per organisation), Airbyte will by default see every physical partition as a separate stream. A database with 5 logical tables and 128 organisations becomes <strong>638 streams</strong> to manage.</p><h3>Fix 1 — Route All Events Through Parent Tables</h3><pre>ALTER PUBLICATION airbyte_pub SET (publish_via_partition_root = true);</pre><p>This routes all partition events through the 5 parent streams only. New partitions added in future are automatically included — no manual refresh, no Lambda trigger needed (PostgreSQL 15+).</p><p>Verify it worked:</p><pre>SELECT pubname, pubviaroot<br>FROM pg_publication<br>WHERE pubname = &#39;airbyte_pub&#39;;</pre><h3>Fix 2 — Use Composite MERGE Keys to Prevent Cross-Tenant Collisions</h3><p>If your partition key column name differs per table (e.g., some tables use organisation_id, others use customer_id), a single id MERGE key will cause silent cross-tenant data collisions — org 1 row 101 silently overwrites org 22 row 101.</p><pre>-- Tables using organisation_id as partition key<br>ON target.id = source.id<br>AND target.organisation_id = source.organisation_id</pre><pre>-- Tables using customer_id as partition key<br>ON target.id = source.id<br>AND target.customer_id = source.customer_id</pre><p>Check your live DB to confirm which column each table uses before writing your merge scripts.</p><h3>Airbyte Connection Setup Reference</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h3VBHkYbGJ46FGnP4ORz5A.png" /></figure><p><strong>JDBC URL Parameters (Advanced):</strong></p><pre>ssl=true&amp;sslmode=require&amp;tcpKeepAlive=true&amp;socketTimeout=3600</pre><p>Pre-requisites on the database side:</p><pre>-- Database &amp; schema access<br>GRANT CONNECT ON DATABASE your_db TO airbyte_user;<br>GRANT USAGE ON SCHEMA public TO airbyte_user;<br>GRANT SELECT ON ALL TABLES IN SCHEMA public TO airbyte_user;<br>ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO airbyte_user;</pre><pre>-- CDC / WAL access<br>GRANT rds_replication TO airbyte_user;<br>GRANT pg_read_replication_slot TO airbyte_user;<br>GRANT pg_monitor TO airbyte_user;</pre><p>Make sure your RDS instance has wal_level = logical set in the parameter group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GPAUn80D4K9Tj0RzgVAF1A.png" /></figure><p>The IAM user attached to the access key needs <strong>Read and Write</strong> permissions on the target S3 bucket.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IsOOzgKlLpIwvn3IGZvl5w.png" /></figure><p><strong>Takeaway:</strong> Schema changes need a coordinated deployment — update the normalise view, update the MERGE script, and let Airbyte do a schema refresh in the same change window. Never let a schema change land in production silently.</p><h3>Summary</h3><p>This architecture gives you:</p><ul><li>✅ <strong>Zero downtime</strong> — DMS reads from a copy, production is never touched</li><li>✅ <strong>No data gaps</strong> — DMS covers T0 history, Airbyte covers T0 onwards</li><li>✅ <strong>Idempotent merges</strong> — timestamp guard prevents any overwrites from stale data</li><li>✅ <strong>Self-healing</strong> — max_slot_wal_keep_size protects the DB automatically</li><li>✅ <strong>Partition-safe</strong> — pubviaroot and composite MERGE keys handle complex schemas</li><li>✅ <strong>GDPR-ready</strong> — soft deletes visible in Iceberg, hard deletes via snapshot expiry</li></ul><p>The data ingestion layer is the foundation everything else builds on. Get this right, and your transformation and visualisation layers have a clean, reliable, always-current dataset to work with.</p><p><em>This is Part 1 of a series on building a production data platform — covering ingestion, transformation, and visualisation. Follow along if you’re building something similar or want to avoid the pitfalls the hard way.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d603b498c675" width="1" height="1" alt=""><hr><p><a href="https://medium.com/towards-data-engineering/a-step-by-step-guide-using-aws-dms-and-airbyte-cdc-on-postgresql-d603b498c675">A step-by-step guide using AWS DMS and Airbyte CDC on PostgreSQL</a> was originally published in <a href="https://medium.com/towards-data-engineering">Towards Data Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>