<?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 Abderrahmane Oubagha on Medium]]></title>
        <description><![CDATA[Stories by Abderrahmane Oubagha on Medium]]></description>
        <link>https://medium.com/@a.oubagha?source=rss-99a07a22cb8f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*iXYRq17dC9UEDz5O</url>
            <title>Stories by Abderrahmane Oubagha on Medium</title>
            <link>https://medium.com/@a.oubagha?source=rss-99a07a22cb8f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:00:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@a.oubagha/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[Dataform Incremental Load Optimizations]]></title>
            <link>https://medium.com/@a.oubagha/dataform-incremental-load-optimizations-917cdc78cf56?source=rss-99a07a22cb8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/917cdc78cf56</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[dataform]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[bigquery]]></category>
            <dc:creator><![CDATA[Abderrahmane Oubagha]]></dc:creator>
            <pubDate>Sun, 28 Jun 2026 20:55:48 GMT</pubDate>
            <atom:updated>2026-06-28T20:55:48.175Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LAxtmMebj-if8rpfC3a6cQ.png" /></figure><h4>Four practical techniques that dramatically reduced BigQuery costs and execution time for production Dataform incremental pipelines.</h4><h3>Introduction</h3><p><strong>Dataform</strong> makes building incremental pipelines remarkably simple. With just a few lines of configuration, you can process only new or updated data instead of reloading entire tables. However, writing an incremental pipeline doesn’t necessarily mean it will be efficient.</p><p>While optimizing several production pipelines, I discovered that some of our incremental jobs were scanning <strong>terabytes of data</strong> even though only a tiny fraction of the records had changed. The pipelines were technically incremental, yet a few implementation details were preventing BigQuery from taking advantage of partition pruning and other query optimizations.</p><p>In this article, I’ll share four practical techniques that significantly reduced both execution time and BigQuery costs across our Dataform pipelines. These optimizations don’t change your business logic — they simply help BigQuery scan far less data.</p><h3>1. Always Filter on the Partition Column</h3><p>Dataform makes it easy to build incremental pipelines. To enable incremental loading, simply set the table type to incremental in the config block:</p><pre>config {<br>  type: &quot;incremental&quot;,<br>  schema: &quot;bq_dataset&quot;,<br>  name: &quot;bq_table&quot;<br>  ………<br>}</pre><p>Once that’s done, you can define different logic for full refreshes and incremental runs using the when(incremental()) helper .<br>A common approach is to use a watermark column, such as updated_at, to process only newly added or modified records:</p><pre> SELECT user_id, country<br> FROM  ${ref(&quot;source_table&quot;)}<br>  ${<br>     when(incremental(), <br>        `WHERE updated_at &gt; (SELECT MAX(updated_at) FROM ${self()})`<br>    )<br>}</pre><p>With this WHERE filter, only new data will be processed. However, there is one important edge case: what if the table is partitioned by date (updated_date) rather than by the updated_at timestamp column?</p><p>In that case, the BigQuery job will scan the <strong>entire table</strong> to find the relevant rows, because it doesn’t know which partitions to skip — the WHERE clause operates on a non-partition column, so partition pruning cannot take effect.</p><p>The solution is to combine both filters — one on the partition column to prune partitions, and one on the precise timestamp for accuracy:</p><pre>jaSELECT user_id, country<br>FROM  ${ref(&quot;source_table&quot;)}<br>  ${<br>     when(incremental(),<br>        `WHERE updated_date &gt;= (SELECT MAX(updated_date) FROM ${self()})<br>          AND updated_at &gt; (SELECT MAX(updated_at) FROM ${self()})`<br>    )<br>}</pre><p>With this combined filter, only the required partitions will be scanned and BigQuery will skip all irrelevant ones.</p><blockquote><strong>Assumption</strong><br>We Assume that the source table is partitioned by date, this is the norm for large scale BQ tables.</blockquote><h3>2. Use Variables Instead of Dynamic Subqueries</h3><p>The subquery approach shown above is known as a <strong>dynamic partition filter</strong>, whereas using a predicate with a constant value is called a <strong>static filter</strong>. Dynamic filters don’t guarantee that partition pruning works correctly, because BigQuery doesn’t know the value at compile time. The problem is compounded if you add transformations on one or both sides of the comparison, or if there is a type mismatch between the two sides (e.g. a DATE column compared against a TIMESTAMP).</p><p>To fix this, we can use procedural language to declare a variable, assign the value of the incremental watermark to it, and then reference that variable in the WHERE clause. In plain SQL it looks like this:</p><pre>DECLARE max_updated_date DATE;<br>SET max_updated_at = (SELECT MAX(updated_date) FROM bq_source_table);</pre><p>In Dataform, we achieve the same result using pre_operations blocks, like this:</p><pre>pre_operations {<br>  DECLARE<br>    max_updated_date DATE;<br>    ${<br>        when(incremental(),<br>            `SET max_updated_date = (<br>              SELECT MAX(updated_date)<br>              FROM ${self()}<br>            );`<br>        )<br>    }<br>}</pre><blockquote><strong>Warnning</strong> : <br>Ensure that the DECLARE statement is inside the pre_operations block, as Dataform expects only a SELECT statement in the query body.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6u86GeNzQdD-IOdMD-C2GA.png" /><figcaption>Dataform job scans the entire table when using a dynamic subquery</figcaption></figure><blockquote>💡 For one of our jobs, the bytes processed dropped from <strong>2.2 TB to 80 GB</strong> after switching from a dynamic subquery to a variable in pre_operations.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RHiJnM_j7D8mKsT6hSBWSg.png" /><figcaption>Dataform job scans only the required data when using procedural language</figcaption></figure><h3>3. Use a Temp Table Instead of a CTE</h3><p>CTEs are a great option for writing readable SQL, but they don’t always improve performance. <br>When the same CTE is referenced multiple times, BigQuery’s optimizer <strong>may</strong> execute the underlying subquery multiple times depending on the execution plan.</p><p>Consider a query that joins the same users CTE twice — once to match clients, and once to match partners:</p><pre>WITH users AS (...)<br><br>SELECT<br>  order_id,<br>  ...<br>FROM ${ref(&#39;orders&#39;)} AS orders<br>JOIN users AS clients<br>  ON orders.user_id = clients.id<br>  AND clients.type = &#39;client&#39;<br>JOIN users AS partners<br>  ON orders.user_id = partners.id<br>  AND partners.type = &#39;partner&#39;</pre><p>The optimizer may evaluate the expensive users query twice.</p><p>If the CTE performs significant computation, it’s often better to materialize it once.<br>You can use a temp table in pre_operations so the data is materialized once and reused:</p><pre>pre_operations {<br>    CREATE TEMP TABLE users AS ....<br>}<br><br>SELECT<br>  order_id, ...<br>FROM ${ref(&#39;orders&#39;)} AS orders<br>JOIN users AS clients ON orders.user_id = clients.id AND clients.type = &#39;client&#39;<br>JOIN users AS partners ON orders.user_id = partners.id AND partners.type = &#39;partner&#39;<br><br>post_operations {<br>     DROP TABLE IF EXISTS users;<br>}</pre><h3>4. Reduce MERGE Costs with updatePartitionFilter</h3><p>When inserting data on the target table Datafrom give you two options:</p><p>When inserting data into the target table, Dataform gives you two options:</p><ul><li><strong>Insert (default):</strong> simple and with no overhead cost or time, but can produce duplicates.</li><li><strong>Merge:</strong> you can specify a unique key (one or more columns) in the config file, and at insert time, Dataform will merge existing records based on the key from the source data and insert any new ones.</li></ul><p>During the merge step, Dataform needs to identify which records already exist in the target table — which means it must scan it. On a large partitioned table, this comes with a significant cost. Fortunately, the updatePartitionFilter config option lets you limit how much of the target table is scanned during the merge.</p><p>Here is a config <em>without</em> updatePartitionFilter:</p><pre>config {<br>  type: &quot;incremental&quot;,<br>  name: &quot;target&quot;,<br>  uniqueKey: [&quot;id&quot;],<br>  bigquery: {<br>    partitionBy: &quot;created_date&quot;<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VSNh7_gSW4071pYvh0FIhA.png" /><figcaption>MERGE without updatePartitionFilter — the entire target table is scanned</figcaption></figure><p>Now add updatePartitionFilter to restrict the scan to only the relevant partition window:</p><pre>config {<br>  .....<br>  uniqueKey: [&quot;id&quot;],<br>  bigquery: {<br>      ...........<br>      updatePartitionFilter:<br>          &quot;created_date &gt;= DATE_SUB(CURRENT_DATE(), INTERVAL 7 DAY)&quot;<br>       .....<br>  }<br>}</pre><p>After setting this, the Dataform job will scan only the past week of data when checking for records to merge, rather than the full table history.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VY5vbNJnwRWBQEobtqQmEQ.png" /><figcaption>MERGE with updatePartitionFilter — only the relevant partitions are scanned</figcaption></figure><blockquote><strong>Warning — Potential Duplicates<br></strong>If the source data contains records older than the interval specified in updatePartitionFilter, you might end up with duplicates.<br>To avoid this, apply the same date filter to your source data to ensure that records older than the interval either don&#39;t exist or are not relevant.</blockquote><h3>Conclusion</h3><p>Most Dataform optimization discussions focus on SQL transformations. In practice, the largest gains often come from helping BigQuery <em>scan less data</em>.</p><p>The combination of partition pruning, static filtering with procedural variables, temp table materialization, and MERGE optimization can reduce both execution time and query costs by an order of magnitude on large incremental pipelines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=917cdc78cf56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Metadata Becomes the Bottleneck : Optimizing Spark Streaming & Delta Lake]]></title>
            <link>https://medium.com/@a.oubagha/when-metadata-becomes-the-bottleneck-optimizing-spark-streaming-delta-lake-fce3029973c3?source=rss-99a07a22cb8f------2</link>
            <guid isPermaLink="false">https://medium.com/p/fce3029973c3</guid>
            <category><![CDATA[spark-optimization]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[delta-lake]]></category>
            <category><![CDATA[apache-spark-streaming]]></category>
            <dc:creator><![CDATA[Abderrahmane Oubagha]]></dc:creator>
            <pubDate>Sun, 24 May 2026 08:18:51 GMT</pubDate>
            <atom:updated>2026-05-24T08:18:51.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hRS4s56J3s3suXbVmRdN9A.png" /></figure><h4>A deep-dive into checkpoint compaction and Delta Lake transaction log growth in high-frequency file streaming pipelines — and how to fix them.</h4><h3>Introduction</h3><p>Building low-latency data pipelines with Spark Structured Streaming and Delta Lake is relatively straightforward at small scale. However, once a pipeline starts processing continuous micro-batches at high frequency, an unexpected bottleneck begins to appear: <strong>metadata operations</strong>.</p><p>In one of my streaming pipelines, the actual data processing logic was fast and stable, yet end-to-end latency kept increasing over time. After investigation, the root cause was not transformations, joins, or compute resources — it was metadata compaction mechanisms inside both Spark Structured Streaming checkpoints and Delta Lake transaction logs.</p><p>To achieve low latency, the pipeline intentionally generates many small files through frequent micro-batches. Smaller files mean Spark can begin processing events sooner after they land in storage, directly reducing end-to-end latency. However, this comes at a cost: each micro-batch produces its own metadata records, and over time these compound into significant overhead. Spark periodically compacted processed-file metadata, and Delta Lake continuously rebuilt larger snapshots and transaction logs. Both became major latency contributors.</p><p>In this article, I will share:</p><ul><li>How Spark Structured Streaming manages file-source metadata</li><li>Why checkpoint compaction can become a hidden bottleneck</li><li>How Delta Lake metadata and snapshot compaction affect latency</li><li>The tradeoffs of small files in low-latency systems</li><li>The custom optimization strategy I implemented to reduce metadata overhead</li></ul><blockquote><strong><em>Scope</em><br></strong>The focus of this article is not Spark transformations or business logic optimization, but rather the less-discussed <em>operational</em> side of streaming systems: metadata scalability.</blockquote><h3>Pipeline Context</h3><p>The pipeline starts with <strong>Google Cloud Pub/Sub</strong>, which ingests high-volume, real-time events. At the time of writing, Apache Spark does not provide a native connector for Pub/Sub comparable to its Kafka integration. As a result, data must first be written to an intermediate storage layer before Spark can consume it.</p><p>To address this, we use a <strong>GCS subscription</strong>, which automatically writes Pub/Sub messages into Google Cloud Storage as JSON files. This lets Spark Structured Streaming consume the data using its native file-based streaming capabilities.</p><p>Since Spark processes data from files, ingestion latency depends directly on how quickly files are created in GCS. To minimize latency, the Pub/Sub subscription is configured to flush files as frequently as possible, so Spark can process them and write results to a Delta Lake table at a high refresh rate.</p><blockquote><strong><em>Stack</em><br>Apache Spark 3.5</strong> · Structured Streaming (file source) · <strong>Delta Lake 3.1.0</strong> · Storage: <strong>GCS (GCP)</strong></blockquote><h3>Streaming Files with Spark</h3><p>Spark Structured Streaming supports various data sources, including message brokers like Kafka or Azure Event Hub, as well as file-based sources. It is possible to stream data directly from a data lake by monitoring a directory for new files as they arrive. Files are processed in order of modification time (reversed if latestFirst is set). Supported formats include text, CSV, JSON, ORC, and Parquet.</p><h4>The cleanSource Option</h4><p>One of the most operationally important options for file-source streaming is cleanSource, which controls what happens to source files after they are processed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BIeE5LivP2LbpL1FZjl1sA.png" /></figure><blockquote><strong>Recommendation<br></strong>It is highly recommended to use cleanSource with archive or delete to avoid long directory scans, even though each option has its own cost.</blockquote><blockquote>Both actions are best-effort: a failed delete or archive operation will not fail the streaming query. Understanding this behavior is important when discussing deduplication and exactly-once guarantee.</blockquote><h3>Spark Checkpoint</h3><h4>Why Checkpoint</h4><p>Checkpointing in Spark Streaming serves two critical purposes. First, it provides <strong>fault tolerance</strong> by persisting the current progress (which files or partitions have been processed) into reliable storage. Second, it maintains <strong>stateful computations</strong> such as aggregations or windowed counts across micro‑batches.</p><p>On a restart — whether due to a crash, an OOM error, or a planned upgrad Spark reads the checkpoint to determine exactly where the previous execution stopped. This guarantees exactly-once delivery for data processed during a failed micro‑batch.</p><pre>streamWriter = df.writeStream \<br> .foreachBatch(stream_batch_process)\<br> .option(&quot;checkpointLocation&quot;, path/to/checkpoint) \<br> .trigger(processingTime=&quot;20 seconds&quot;)<br>streamWriter.start().awaitTermination()</pre><h3>How Spark Tracks Processed Files</h3><p>Inside the checkpoint directory, the sources/ folder contains one subfolder per stream (stream stream join for example). This folder tracks the offset — which data has already been processed — for each stream individually.</p><p>Because our pipeline streams from files, Spark saves the list of every file processed in each batch. A new metadata file is created per batch, formatted in plain text:</p><pre>v1<br>{&quot;path&quot;:&quot;gs://pubsub/drivers_locations/data/2025-11-06T11:00:00+00:00_19c353.json&quot;,&quot;timestamp&quot;:1762426806857,&quot;batchId&quot;:0}<br>{&quot;path&quot;:&quot;gs://pubsub/drivers_locations/data/2025-11-06T11:00:00+00:00_0aacb6.json&quot;,&quot;timestamp&quot;:1762426806940,&quot;batchId&quot;:0}<br>{&quot;path&quot;:&quot;gs://pubsub/drivers_locations/data/2025-11-06T11:00:01+00:00_7b77f3.json&quot;,&quot;timestamp&quot;:1762426806970,&quot;batchId&quot;:0}</pre><p>The file begins with a version header (v1), which ensures a checkpoint created with a newer Spark version will not be silently consumed by an older version. The remaining lines list all files processed in the given micro batch.</p><h3>Compaction Every 10 Batches</h3><p>To avoid scanning thousands of individual batch files on restart, Spark compacts these metadata files every 10 batches by default (controlled by spark.sql.streaming.fileSource.log.compactInterval). Every 10th file is merged into a single .compact file named after the batch number, e.g., 9.compact, 19.compact, etc.</p><p>Critically, the compact file contains the <strong>full accumulated list of processed files from the very beginning of the stream</strong> — not just the last 10 batches.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tFTw52J2-NtD3mreRX2sPQ.png" /><figcaption>Inside the checkpoint sources/0/ folder: individual batch files (30–70 KB each) and .compact files (318 MB each) that accumulate all processed file paths since stream start.</figcaption></figure><h3>The Compaction Problem</h3><p>The .compact file grows indefinitely. Every compaction event appends the new batch&#39;s entries to the full historical list, so the file never shrinks. In a low-latency pipeline generating hundreds of small files per minute, this file can reach <strong>several gigabytes</strong> within days. The consequences are:</p><ul><li><strong>Latency spikes every 10 batches</strong> — the Driver must read the entire compact file into memory during each compaction event, causing a noticeable processing pause.</li><li><strong>Out-of-Memory (OOM) errors</strong> — the compact file eventually exceeds the Driver’s available heap, crashing the job entirely.</li></ul><p>The chart below captures this in the Spark UI. Notice the regular spikes every ~10 batches in the Batch Duration panel — these correspond exactly to checkpoint compaction events. During these events, the Driver becomes busy with metadata I/O, causing data to accumulate and resulting in larger input batches immediately after the spike.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mwQeawHlN9ZQQeWRBgHglQ.png" /><figcaption>Spark Structured Streaming batch metrics. The <strong>Batch Duration</strong> panel shows periodic spikes every ~10 batches caused by checkpoint compaction</figcaption></figure><blockquote><strong>Note</strong> : The other regular spikes are caused by Delta Lake snapshot compaction, It will be discussed later.</blockquote><h3>Fix: Custom Checkpoint Truncation</h3><p>Since none of the available configuration parameters address the root cause, the solution is to truncate the compact file programmatically — surgically, without stopping the job, and without risking data loss or replay gaps.</p><p>The function runs inside the foreachBatch callback, triggered at controlled intervals (e.g., every 10,000 batches). It retains a configurable trailing window of recent file entries — large enough to cover the maxFileAge window and prevent reprocessing on restart, but small enough to keep the compact file bounded.</p><blockquote><strong>How Much History to Keep?<br></strong>A safe rule of thumb: retain entries covering at least as much history as maxFileAge (default: 7 days). This ensures the job will not reprocess recently seen files on restart. If deduplication is handled downstream, you can use a smaller window tuned purely for latency.</blockquote><pre>def truncate_latest_compact(checkpoint_path, n_lines=20000):<br>    # Finds the latest .compact file in the Spark checkpoint sources folder<br>    # and truncates it to reduce Driver memory pressure.<br>    #<br>    # Args:<br>    #   checkpoint_path: Cloud storage path to the streaming source metadata<br>    #                    (e.g., &#39;gs://bucket/checkpoint/sources/0&#39;).<br>    #   n_lines:         Number of most recent file entries to retain (default 20000).<br>    <br>    client = storage.Client()<br><br>    # 1. Parse bucket and prefix<br>    bucket_name, prefix = get_bucket_name_and_prefix(checkpoint_path)<br>    bucket = client.bucket(bucket_name)<br>    blobs = list(client.list_blobs(bucket, prefix=prefix))<br><br>    # 2. Find the latest .compact file<br>    compact_blobs = [b for b in blobs if b.name.endswith(&quot;.compact&quot;)]<br>    latest_blob = sorted(<br>        compact_blobs,<br>        key=lambda x: int(x.name.split(&#39;/&#39;)[-1].split(&#39;.&#39;)[0])<br>    )[-1]<br>    print(f&quot;Latest compact: {latest_blob.name} | Size: {latest_blob.size} bytes&quot;)<br><br>    head_bytes = latest_blob.download_as_bytes(start=0, end=2048)<br>    header = head_bytes.decode(&quot;utf-8&quot;, errors=&quot;ignore&quot;).splitlines(keepends=True)[0]<br><br>    bytes_per_row = 2 * 1024 * 1024 / 10000<br>    required_bytes = int(bytes_per_row * n_lines * 1.2)<br>    tail_start = max(0, latest_blob.size - required_bytes)<br>    tail_bytes = latest_blob.download_as_bytes(start=tail_start)<br>    tail_lines = tail_bytes.decode(&quot;utf-8&quot;, errors=&quot;ignore&quot;).splitlines(keepends=True)<br>    tail = &quot;&quot;.join(tail_lines[-n_lines + 1:])<br>    final_content = header + tail<br><br>    # Overwrite the original blob with the truncated content<br>    latest_blob.upload_from_string(final_content, content_type=&quot;application/octet-stream&quot;)<br>    print(f&quot;Successfully truncated {latest_blob.name} to header + {n_lines} lines.&quot;)<br><br><br># -- Integration inside foreachBatch callback --<br><br>def write(batch_df, batch_id):<br>    batch_df.write \<br>        .format(&quot;delta&quot;) \<br>        .option(&quot;mergeSchema&quot;, &quot;true&quot;) \<br>        .mode(&quot;append&quot;) \<br>        .partitionBy(&quot;load_date&quot;, &quot;hour&quot;) \<br>        .save(data_write_path + &quot;/data/&quot;)<br><br>    try:<br>        # Trigger truncation at batch 10000, 20000, 30000, ...<br>        if batch_id &gt;= 10000 and (batch_id - 1) % 10000 == 0:<br>            truncate_latest_compact(<br>                data_write_path + &quot;/checkpoint/sources/0/&quot;,<br>                n_lines=200000<br>            )<br>    except Exception as e:<br>        print(f&quot;Truncation failed: {e}&quot;)<br><br><br>df.writeStream \<br>    .foreachBatch(write) \<br>    .trigger(processingTime=&quot;30 seconds&quot;) \<br>    .option(&quot;checkpointLocation&quot;, data_write_path + &quot;/checkpoint/&quot;) \<br>    .start() \<br>    .awaitTermination()</pre><blockquote><strong>Warning <br></strong>When using foreachBatch, Spark provides an <em>at-least-once</em> guarantee, not exactly-once. If a batch fails mid-write before the checkpoint commit, partially processed data will be replayed on the next attempt. Always implement idempotent writes or downstream deduplication when this matters.</blockquote><h3>Results After Applying Checkpoint Truncation</h3><p>After deploying the custom truncation function, the periodic batch-duration spikes caused by checkpoint compaction were significantly reduced and stabilized. As shown below, the difference between regular batches and checkpoint-compaction batches became much smaller, resulting in more consistent streaming performance and lower metadata overhead.</p><p>Although a slight overhead remains during compaction cycles — which is expected due to checkpoint maintenance operations — the latency impact is now substantially lower and more predictable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vNd5JQPt1eAVGb9x5-dwSA.png" /><figcaption>Spark Structured Streaming batch metrics after applying checkpoint truncation</figcaption></figure><h3>Part Two : The Delta Lake Small File Problem</h3><p>As described earlier, generating many small files is an intentional strategy for achieving low latency. However, it introduces a parallel problem at the Delta Lake layer.</p><p>Small files are expensive in two ways: <br>1. They require excessive I/O overhead during reads (each file requires its own open/read/close cycle)<br>2. They cause the Delta Lake transaction log to grow rapidly, which degrades both read and write performance by increasing metadata management overhead, ultimately adding latency to processing time.</p><h4>How Delta Lake Metadata Grows ?</h4><p>Every write to a Delta table appends a JSON transaction log entry to the _delta_log/ directory, recording what was added or removed. With several of micro-batches per minute, this directory accumulates thousands of small JSON files quickly.</p><p>To keep this manageable, Delta Lake automatically creates a <strong>checkpoint file</strong> (a Parquet snapshot of the full table state) every 10 commits by default. This mirrors exactly the compaction behavior seen in Spark checkpoints: the snapshot absorbs all previous log entries and grows larger with every cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fg4CXyWPhCJQ2tdIC18DHQ.png" /><figcaption>The _delta_log/ directory of a high-frequency Delta table. Checkpoint files (.checkpoint.parquet) reach 1.8 GB each, while individual JSON transaction logs are 30–120 KB.</figcaption></figure><p>The figure below shows the periodic latency spikes caused by Delta log compaction :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*F9aLePDEEkPHfI7wy1R-XQ.png" /></figure><h4><strong>Managing Small Files Through Compaction</strong></h4><p>The two solutions to this problem are <strong>manual compaction</strong> (running the OPTIMIZE command on a schedule) and <strong>auto compaction</strong> (enabling Delta Lake to compact files automatically after each write).</p><p>This will significantly reduces the number of file references stored in the transaction log and future checkpoints, lowering metadata overhead and improving both read and write efficiency. Instead of tracking many tiny files across the table state, Delta Lake now maintains metadata for a much smaller set of optimized files.</p><p>Let’s discuss each approach in detail below:</p><h3>1. Manual Compaction with OPTIMIZE</h3><p>Delta Lake’s OPTIMIZE command compacts small Parquet files into larger ones, reducing I/O overhead for reads and keeping the transaction log checkpoint size manageable.</p><p>For partitioned tables, it is more efficient to run it on specific partitions rather than the full table, reducing processing time and avoiding unnecessary rewriting of already-optimized data.</p><pre>from delta.tables import DeltaTable<br><br>deltaTable = DeltaTable.forPath(spark, read_path)<br><br># Run OPTIMIZE on a specific partition (e.g., the most recent date)<br>deltaTable.optimize().where(&quot;load_date=&#39;2026-04-08&#39;&quot;).executeCompaction()</pre><h4>Tuning OPTIMIZE Thresholds</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k8nzYuDvACCia2VlZ2gouQ.png" /></figure><blockquote><strong>Important<br></strong>OPTIMIZE does not physically delete old files. Instead, it rewrites data into new compacted files and creates a new transaction log entry pointing to these new files. The previous files are no longer referenced by the latest delta log snasphot . To actually reclaim storage space, the VACUUM command must be run separately (we will discuss this later).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A2c2kuc2kbPIlZmNU5XzOA.png" /><figcaption>Example json transaction file after applying compaction</figcaption></figure><blockquote><strong>Warning</strong><br>If your manual VACUUM runs on a separate partition from the active streaming write, there is no conflict. Likewise, if your streaming job is append‑only (no updates or deletes), VACUUM is safe even on the same partition. However, if the streaming pipeline performs MERGE or UPDATE operations, be aware that a concurrent VACUUM may remove files still needed by those operations, leading to transaction conflicts.</blockquote><h3>2. Auto Compaction</h3><p>The idea of autoCompact is that it can run OPTIMIZE on your table while a process is already running without additional commands. <br>One of the biggest advantages is that you don’t need to have a secondary process running that might conflict with a stream processing application, for example.<br>The downside is that there could be a relatively minor effect on the processing latency. This is because after a file is committed, Spark will perform an OPTIMIZE operation as part of the same process. It analyzes the files available in the table and applies the compaction as necessary. This can be especially helpful with a streaming write, as the transactions tend to be smaller than you would find in many other workload types, but it does come as a trade-off since it will insert additional tasks to do the compaction, which can hold up processing time. This means that for cases with tight SLA margins, you may wish to avoid using it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_Ec3Xx5FYVtymkaISrUKiw.png" /><figcaption>Example of Streaming Metrics Showing Batch Duration Peaks During Auto Compaction</figcaption></figure><h4>Configuration</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pl1LT4f6VCqYpkpNaDXHcA.png" /></figure><blockquote><strong>Note</strong> Even when auto compaction is enabled, it is still good practice to run scheduled OPTIMIZE regularly. Auto compaction handles incremental writes well but may not consolidate all historical small files across partitions as thoroughly as a targeted OPTIMIZE call.</blockquote><h3>Optimized Write</h3><p>Optimized Write is designed for distributed scenarios where many parallel tasks write to the same Delta table simultaneously. It automatically determines the optimal number of output files and partition layout, eliminating the need to manually call coalesce(n) or repartition(n) before writing.</p><p>However, Optimized Write alone does not solve the small file problem for high-frequency streaming. Even with automatic file sizing, each micro-batch still produces its own set of small files. Optimized Write reduces the <em>number</em> of files per batch, but compaction via OPTIMIZE is still required to consolidate files across batches over time.</p><p>For this reason, Optimized Write is not considered a standalone solution to the small file problem in this article. Instead, it should be viewed as a complementary optimization that can improve and simplify both manual and automatic compaction strategies.</p><p><strong>You can enable Optimized Write by :<br></strong>1. Per write operation using the optimizeWrite option<br>2. At the Delta table level using delta.autoOptimize.optimizeWrite<br>3. Globally for the Spark session using spark.databricks.delta.optimizeWrite.enabled</p><h4>VACUUM: Reclaiming Storage</h4><p>Delta Lake retains historical versions of data files for time travel (30 days by default). Files marked as removed by OPTIMIZE or other operations are <em>not</em> deleted from storage automatically, even after the retention period expires. To physically reclaim storage, run the VACUUM command.</p><pre>from delta.tables import DeltaTable<br><br>deltaTable = DeltaTable.forPath(spark, table_path)<br><br># Always do a dry run first to see what would be deleted<br>spark.sql(f&quot;VACUUM delta.`{table_path}` DRY RUN&quot;)<br><br># Standard vacuum: keep 7 days of history (default)<br>deltaTable.vacuum(retentionHours=168)<br><br># To use a shorter retention period (&lt; 7 days), disable the safety check first:<br>spark.conf.set(&quot;spark.databricks.delta.retentionDurationCheck.enabled&quot;, &quot;false&quot;)<br>deltaTable.vacuum(retentionHours=24)  # Keep 24 hours for streaming sources</pre><blockquote><strong>Warning</strong> : <br><em>Always do a dry run first to see what would be deleted : <br></em>spark.sql(f”VACUUM delta.`{table_path}` DRY RUN”)<br><em>It return a listing of the files that will be removed from storage when the vacuum is run.</em></blockquote><blockquote>Run VACUUM regularly as part of the same maintenance schedule as OPTIMIZE. Together they form a complete housekeeping routine: OPTIMIZE consolidates small files into large ones, and VACUUM removes the obsolete originals from storage.</blockquote><h3>Conclusion</h3><p>In high-frequency Spark Structured Streaming pipelines, metadata management is just as critical as compute optimization. Two independent compaction mechanisms — Spark checkpoint compaction and Delta Lake snapshot compaction — both follow the same pattern: they accumulate unbounded history and cause periodic latency spikes that worsen over time.</p><p>The central insight is that the <em>small-files / low-latency</em> tradeoff is real but manageable. Frequent micro-batches give you data freshness; deliberate, bounded metadata management prevents that freshness from degrading into instability. Both layers — Spark checkpoint and Delta Lake — require explicit operational attention in any production streaming deployment at scale.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fce3029973c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>