<?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 Sunil Khairnar on Medium]]></title>
        <description><![CDATA[Stories by Sunil Khairnar on Medium]]></description>
        <link>https://medium.com/@sunilkhairnar777?source=rss-e83341cfdb68------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*XN6HRNVklankDxHjl4kHWg.jpeg</url>
            <title>Stories by Sunil Khairnar on Medium</title>
            <link>https://medium.com/@sunilkhairnar777?source=rss-e83341cfdb68------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 06:31:00 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sunilkhairnar777/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[Cloud Composer: The Good, The Bad, and The Ugly — A Data Engineer’s Perspective]]></title>
            <link>https://blog.dataengineerthings.org/cloud-composer-the-good-the-bad-and-the-ugly-a-data-engineers-perspective-ec61f5bd5fc0?source=rss-e83341cfdb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec61f5bd5fc0</guid>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[google-cloud-composer]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Sunil Khairnar]]></dc:creator>
            <pubDate>Tue, 02 Jun 2026 10:12:21 GMT</pubDate>
            <atom:updated>2026-06-25T11:39:51.507Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TlBAMFTEk8Ge2N6R9Q-xJQ.jpeg" /></figure><p><strong>Orchestration</strong> is the skeleton of any modern data platform. After building and operating data pipelines on GCP platform for more than 3 years, I have learned that Cloud Composer can be one of the most valuable service — or one of the most frustrating — depending on how it is used.</p><p><strong>This article is not a product review. It is a practical assessment from a Data Engineer and Data Architect perspective.</strong></p><p>We’ll discuss:</p><ul><li><em>The Good</em>: where Composer shines</li><li><em>The Bad</em>: limitations you should understand</li><li><em>The Ugly</em>: mistakes that create operational nightmares</li></ul><p>Let’s dive in.</p><h3>What Cloud Composer Actually Is</h3><p>Cloud composer is an orchestration platform built on <a href="https://airflow.apache.org/docs/apache-airflow/stable/index.html">Apache Airflow</a>. Its primary responsibilities include:</p><ul><li>Scheduling workflows</li><li>Managing dependencies</li><li>Triggering jobs</li><li>Handling retries</li><li>Monitoring execution</li></ul><h3>The Good</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GvCwuScXGKqRSTdzYwJAzw.png" /></figure><h4>1. Excellent Workflow Orchestration</h4><p>The Google Cloud Composer’s real strength. Let’s consider typical production workflow which may look like below</p><pre>Step #1 GCS File Arrived<br>Step #2 Dataflow Processing<br>Step #3 BigQuery Load<br>Step #4 DBT transformations<br>Step #5 Dashboard Refresh</pre><p>Managing these dependencies manually becomes difficult very quickly. Cloud Composer provides a simple and reliable way to orchestrate complex workflows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gGQM6jCuKBwx--XLNLvi7w.png" /></figure><h4>2. Native Integration with Google Cloud</h4><p>One of Composer’s strongest advantages is its tight integration with the GCP ecosystem.</p><p>It works naturally with:</p><ul><li>BigQuery</li><li>Dataflow</li><li>Dataproc</li><li>Cloud Storage</li><li>Pub/Sub</li><li>Cloud Run</li><li>Vertex AI</li></ul><p>A single DAG can coordinate an entire data platform. For organizations heavily invested in Google Cloud, this is a significant advantage.</p><h4>3. Retry and Failure Management</h4><p>The Cloud Composer provides built in capabilities as below, which helps improve the operational resiliency</p><ul><li>Automatic retries</li><li>Retry delays</li><li>Failure notifications</li><li>Dependencies management</li></ul><h4>4. Centralized Visibility (<em>One screen to rule them all</em>)</h4><p>The Airflow UI provides the visibility into:</p><ul><li>Running jobs</li><li>Failed tasks</li><li>Retry history</li><li>Execution duration</li><li>Dependency chains</li></ul><p>This makes troubleshooting significantly easier and faster.</p><h4>5. Enterprise-Scale Scheduling</h4><p>Most of the teams eventually reach a point where they manage:</p><ul><li>Hundreds of pipelines</li><li>Thousands of tasks</li><li>Multiple environments</li></ul><p>Composer provides a centralized platform for managing these workflows. Without orchestration, operational complexity becomes overwhelming.</p><h3>The Bad</h3><p>Now let’s discuss the challenges. Because Cloud Composer isn’t perfect.</p><h4>1. It Can Be Expensive</h4><p>Sometimes teams underestimate the cost of Cloud Composer. Even when the pipelines are idle:</p><ul><li>Airflow components remain active</li><li>Underlying infrastructure continues running</li><li>Storage and monitoring costs accumulate</li></ul><p>For smaller teams, Cloud Composer may feel expensive compared to lightweight alternatives.</p><p>This doesn’t mean Cloud Composer is overpriced.</p><p>It means you should ensure the team’s orchestration needs justify the operational footprint.</p><h4>2. Environment Updates Are Slow</h4><p>Tasks such as:</p><ul><li>Add a python package</li><li>Update an Airflow provider</li><li>Modify / Update dependencies</li></ul><p>may take significantly longer time than engineers expect. Compared to serverless services, Cloud Composer feels heavy. Managing the environmental updates sometimes is a cumbersome process.</p><h4>3. Scheduler Performance Can Become a Bottleneck</h4><p>The large deployment often experience</p><ul><li>Slow DAG parsing</li><li>Scheduling delays</li><li>Metadata database slowness</li></ul><p>These are not unique to the Cloud Composer, but these are common challenges in a large Airflow environment. And as a team we need to anticipate it during the design phase.</p><h3>The Ugly</h3><p>These are the mistakes we commonly see in production environments while using Cloud Composer</p><h4>1. Using Composer as a Data Processing Engine</h4><p>We usually end up writing a DAGs:</p><ol><li>containing hundreds of lines of Pandas transformations.</li><li>business logic directly embedded inside DAG definitions</li></ol><p>Example:</p><pre>df = pd.read_csv(&quot;very_large_file.csv&quot;)<br><br># Transform data <br><br># Aggregate data <br><br># Join data <br><br># Write data to BigQuery</pre><p>I will be honest here, I made the same mistakes in the past. But there is a better way to manage this with architecture as below</p><pre>Composer<br>   ↓<br>Dataflow (Performing aggregation / joins / tranformations)<br>   ↓<br>BigQuery</pre><p>This architecture can scale far better and is easy to manage.</p><h4>2. Monolithic DAGs</h4><p>It is the ugly practice to build a DAG containing:</p><ul><li>150 tasks</li><li>Multiple business domains</li><li>Complex branching logic</li></ul><p>Everything becomes tightly coupled. And when task #98 fails:</p><ul><li>Troubleshooting becomes painful</li><li>Recovery becomes difficult</li><li>Deployment risk increases</li></ul><p>Smaller DAGs are usually easier to operate and maintain.</p><h4>3. Thousands of Dynamically Generated DAGs</h4><p>Dynamic DAG generation is powerful. And with great power comes great responsibility.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/678/1*PnpO-7Q7RJ2DmdiLJZDfUA.jpeg" /><figcaption>from Reddit.com</figcaption></figure><p>The result of abusing dynamic DAG generation (generating hundreds or even thousands of DAGs dynamically):</p><ul><li>Slow scheduler performance</li><li>Airflow UI degradation</li><li>Metadata database growth</li><li>Operational instability</li></ul><p>Just because something can be automated doesn’t mean it should be.</p><h4>4. Using Composer for Real-Time Streaming</h4><p>Composer is fundamentally scheduler-based. It is not an event-processing platform. It is not designed for millisecond-level orchestration.</p><p>I’ve seen teams attempt to orchestrate near-real-time workloads through Airflow scheduling.</p><p>The result of attempting to orchestrate near-real-time workloads through Airflow scheduling:</p><ul><li>Increased complexity</li><li>Higher latency</li><li>Unnecessary operational overhead</li></ul><p>For event-driven systems, consider services designed specifically for real-time processing, such as pub/sub → Dataflow</p><h3>When I Recommend Cloud Composer</h3><p>Cloud Composer is a great choice when:</p><p>✅ You operate multiple data pipelines</p><p>✅ You need dependency management</p><p>✅ You use several GCP services</p><p>✅ You require centralized orchestration</p><p>✅ You need enterprise-grade scheduling</p><p>In these scenarios, Composer provides significant value.</p><h3>When I Would Look Elsewhere</h3><p>Composer may not be the best fit when:</p><p>❌ Workloads are very small</p><p>❌ Simple scheduling is sufficient</p><p>❌ Costs must be minimized</p><p>❌ Architecture is entirely event-driven</p><p>❌ You don’t need complex orchestration</p><p>Sometimes simpler solutions are more effective.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec61f5bd5fc0" width="1" height="1" alt=""><hr><p><a href="https://blog.dataengineerthings.org/cloud-composer-the-good-the-bad-and-the-ugly-a-data-engineers-perspective-ec61f5bd5fc0">Cloud Composer: The Good, The Bad, and The Ugly — A Data Engineer’s Perspective</a> was originally published in <a href="https://blog.dataengineerthings.org/">Data Engineer Things</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Late Arriving Data in BigQuery Pipelines: What Actually Works]]></title>
            <link>https://medium.com/@sunilkhairnar777/handling-late-arriving-data-in-bigquery-pipelines-what-actually-works-36128ce2744a?source=rss-e83341cfdb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/36128ce2744a</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[google-bigquery]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <category><![CDATA[latency]]></category>
            <category><![CDATA[real-time-streaming-data]]></category>
            <dc:creator><![CDATA[Sunil Khairnar]]></dc:creator>
            <pubDate>Wed, 20 May 2026 11:11:31 GMT</pubDate>
            <atom:updated>2026-05-20T11:11:31.877Z</atom:updated>
            <content:encoded><![CDATA[<p>The revenue dashboard suddenly changed yesterday’s numbers by 18%.</p><p>Nothing was wrong with the SQL.</p><p>The real issue?</p><p><strong><em>Late arriving data.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HyGKBZG_ww6aleL4Vom_rA.png" /></figure><p>A payment event that occurred at 9:35 AM did not arrive in the pipeline until 4:37 PM.</p><p>By that time:</p><ol><li>Daily aggregations were already computed</li><li>Dashboards has refreshed</li><li>Finance team had downloaded and shared the reports</li><li>And business team started questioning the numbers</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEfCW_YxN5FjtgybmL0dgw.png" /></figure><p>In this article, I will explain:</p><ul><li>Why late arriving data happens</li><li>Why it breaks BigQuery pipelines</li><li>Common mistakes data engineers make</li><li>Practical strategies that actually work</li><li>How to design resilient and correct analytics systems</li></ul><h3>What is Late Arriving Data?</h3><p>Late arriving data refers to events that arrive significantly later than when they actually occurred.</p><pre>{ <br>  &quot;order_id&quot;: 1001, <br>  &quot;event_timestamp&quot;: &quot;2026-05-15 10:00:00&quot;, <br>  &quot;ingestion_timestamp&quot;: &quot;2026-05-15 10:30:00&quot; <br>}</pre><p>The event occurred at 10:00 AM but it ingested into the topic at 10:30 AM. This difference is what caused the problem.</p><h3>Why Late Data Happens in Real Systems</h3><p>Late data is extremely common because distributed systems are imperfect.</p><p>Real causes include:</p><ul><li>Mobile devices going offline</li><li>Batch retry delays</li><li>API throttling</li><li>Pub/Sub backlog</li><li>Network outages</li><li>CDC lag</li><li>Streaming retries</li><li>Third-party system delays</li></ul><p><strong>Late data is not a bug. It’s an architectural reality.</strong></p><h4>Common Problems Caused by Late Data</h4><ol><li>Incorrect aggregates in report</li><li>Broken incremental model (process may ignore the late data completely)</li><li>Dashboard Inconsistency</li></ol><h3>Avoid below mistakes while building the pipeline</h3><h4><strong>#1 Using Only Ingestion Time</strong></h4><p>Bad design:</p><pre>PARTITION BY ingestion_date</pre><p>Why this fails:</p><ul><li>Analytics should use event time</li><li>Not arrival time</li></ul><p>Late events get assigned incorrectly.</p><h4>#2 Processing Only Today’s Partition</h4><p>Example:</p><pre>WHERE event_date = CURRENT_DATE()</pre><p>Late events from yesterday — permanently missed.</p><h4>#3 Immutable Daily Aggregates</h4><p>Pipelines are designed to compute daily aggregates once and never recompute them. This becomes dangerous because — yesterday’s data may still be incomplete.</p><h4>#4 Append-Only Pipelines</h4><p>Late events often require:</p><ul><li>updates</li><li>corrections</li><li>deduplication</li></ul><p>Append-only designs struggle badly here.</p><h3>So, What how to Manage Late Arriving Data?</h3><p>Now let’s discuss practical strategies that work in real BigQuery pipelines.</p><h4>#1 Separate Event Time from Ingestion Time</h4><p>This is foundational while designing event driven pipelines. Every pipeline should track below two attributes per event.</p><pre>event_timestamp <br>ingestion_timestamp</pre><p>Why both matters? Check out below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e2I3rY3GGwUeb_DVO-a_Pg.png" /></figure><h4>#2 Sliding Window Reprocessing</h4><p>This became our most important improvement while dealing with late arriving data.</p><pre># Instead of processing: <br>event_date = CURRENT_DATE()<br># We processed <br>event_date &gt;= DATE_SUB(CURRENT_DATE(), INTERVAL 3 DAY)</pre><p>This captures:</p><ul><li>delayed events</li><li>retries</li><li>backfills</li></ul><p>A sliding reprocessing window dramatically improves correctness.</p><h4>#3 Use MERGE Instead of Append-Only</h4><p>With Append Only:</p><ul><li>Old incorrect aggregates remain unchanged</li><li>Late data creates inaccurate dashboards</li></ul><p>With Merge:</p><ul><li>Corrects existing aggregates</li><li>Keeps KPIs and reports accurate</li><li>Ideal for late arriving events in BigQuery streaming pipelines</li></ul><pre>MERGE `project.dataset.sales_agg` T<br>USING `project.dataset.new_15min_agg` S<br>ON T.window_start = S.window_start<br>WHEN MATCHED THEN<br> UPDATE SET<br> total_sales = S.total_sales,<br> order_count = S.order_count<br>WHEN NOT MATCHED THEN<br> INSERT (window_start, total_sales, order_count)<br> VALUES (S.window_start, S.total_sales, S.order_count);</pre><p>Benefits of using Merge over Append Only</p><ul><li>Deduplication</li><li>Corrections</li><li>Idempotency</li></ul><p><strong>This leads to — Designing Idempotent Pipelines</strong></p><h4>#4 Partition by Event Date</h4><p>Recommended:</p><pre>PARTITION BY DATE(event_timestamp)</pre><p>Not:</p><pre>PARTITION BY ingestion_timestamp</pre><p><strong>Why? — Analytics usually cares about when event occurred. Not when it arrived.</strong></p><h3>Streaming Pipelines Need Watermarks</h3><p>If you are using</p><ul><li>Dataflow,</li><li>Kafka</li><li>Spark Streaming</li></ul><p>You must understand ‘Watermarks’. Watermarks help define:</p><blockquote>How long should system wait for late events?</blockquote><p>This creates tradeoff between ‘low latency’ and ‘correctness’</p><h3>Real BigQuery Pattern That Worked Well</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WZ6sjxd7IyidGWkjMEGdhA.png" /></figure><p><strong><em>The above architecture make sure</em></strong></p><ol><li>Data Correctness and completeness</li><li>Replay capabilities</li><li>Resilience</li><li>Operational Stability</li></ol><h3>Monitoring Late Arriving Data</h3><p>Monitoring the data arrival time is as important as monitoring the quality of that data.</p><p>Better design always take into consideration</p><ol><li>Ingestion lag</li><li>Late event percentage</li><li>Replay frequency</li><li>Duplicate rate</li></ol><p><strong>Simple example of monitoring query which measure average lateness. You can add this to monitoring agents such as </strong><a href="https://docs.getmontecarlo.com/docs/bigquery"><strong><em>Monte Carlo</em></strong></a><strong> for alerts</strong></p><pre>SELECT <br>      AVG( <br>           TIMESTAMP_DIFF(ingestion_timestamp, event_timestamp, MINUTE)<br>      ) AS avg_delay_m<br>FROM raw_event_table</pre><p><strong>Late arriving data is not the edge case. It is the usual behavior of the distributed system. Once we adapt to below strategies, pipelines become more resilience and data becomes more trustworthy.</strong></p><ol><li>Separate event time from ingestion time</li><li>Use sliding window reprocessing</li><li>Use MERGE instead of append-only logic</li><li>Preserve raw replayable events</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36128ce2744a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Built a Scalable BigQuery to Salesforce Health Cloud Pipeline Using Cloud Composer, DBT, and…]]></title>
            <link>https://medium.com/@sunilkhairnar777/how-i-built-a-scalable-bigquery-to-salesforce-health-cloud-pipeline-using-cloud-composer-dbt-and-4fbb070d55db?source=rss-e83341cfdb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/4fbb070d55db</guid>
            <category><![CDATA[google-bigquery]]></category>
            <category><![CDATA[bulk-apis]]></category>
            <category><![CDATA[dbt-cloud]]></category>
            <category><![CDATA[salesforce]]></category>
            <category><![CDATA[google-cloud-composer]]></category>
            <dc:creator><![CDATA[Sunil Khairnar]]></dc:creator>
            <pubDate>Sun, 17 May 2026 18:31:11 GMT</pubDate>
            <atom:updated>2026-05-17T18:31:11.847Z</atom:updated>
            <content:encoded><![CDATA[<h3>How I Built a Scalable BigQuery to Salesforce Health Cloud Pipeline Using Cloud Composer, DBT, and Salesforce Bulk API</h3><h3>Introduction</h3><p>Healthcare organizations usually generate massive amount of operational, patient, claims, engagement, procedural, and analytical data across multiple platforms. While analytical workloads are often handled in cloud data warehouses like BigQuery / Snowflake, operational healthcare applications such as Salesforce Health Cloud requires near-real-time or scheduled synchronization of curated datasets.</p><p><strong>One of the most common enterprise requirements is moving cleansed and transformed data from BigQuery to Salesforce Health Cloud efficiently, securely, and at scale.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oARyL99k2eHtpdCUyqUEFg.jpeg" /></figure><p>In this article, we will explore how to implement a production-grade Salesforce Bulk API integration pipeline using:</p><ol><li>BigQuery as the analytical data warehouse.</li><li>Cloud DBT for transformations and business modeling.</li><li>Cloud Composer (Apache Airflow) for orchestration.</li><li><strong>Salesforce Bulk API 2.0 </strong>for high-volume ingestion into Health Cloud.</li><li>Google Cloud Storage for staging and fault tolerance</li></ol><p>We will also cover:</p><ul><li>Architecture design</li><li>Incremental loading strategies</li><li>Error handling</li><li>Retry mechanisms</li><li>Schema evolution handling</li><li>Performance optimization</li><li>Security best practices</li><li>Common Challenges in Real Project and its Resolutions</li></ul><p>But first let’s look at the <strong>Business Use Case:</strong></p><p>Consider a healthcare enterprise maintaining patient engagement and operational analytics in BigQuery. the analytics team prepares curated datasets such as:</p><ul><li>Patient onboarding details</li><li>Care plan assignments</li><li>Insurance mappings</li><li>Provider relationships</li><li>Appointment summaries</li><li>Risk scoring outputs</li></ul><p>These transformed datasets must be periodically pushed into Salesforce Health Cloud so care coordinators, CRM, and support teams can access updated operational data.</p><p>However, Salesforce APIs have:</p><ol><li>API limits</li><li>Payload constraints</li><li>Rate throttling</li><li>Record lock considerations</li><li>Object relationship dependencies (crucial while loading data at bulk)</li></ol><p>This makes direct row-by-row inserts inefficient and unreliable for enterprise-scale data movement.</p><p>Salesforce Bulk API 2.0 solve this challenge.</p><h3>Why Use Salesforce Bulk API?</h3><p>Salesforce Bulk API is specifically desgined for:</p><ol><li>Large-scale data ingestion</li><li>Asynchronous processing</li><li>High-throughput batch operations</li><li>And Bulk insert / upserts / deletes</li></ol><p>Compare to standard REST APIs, BULK API provides:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ox95c0Raq_WZ2BOktmz8yA.png" /></figure><p>For healthcare integration involving millions of records, Bulk API becomes the preferred integration mechanism.</p><h3>High-Level Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S74E3YxxuH5YgpZXfhlPRg.png" /><figcaption>High Level Architecture Diagram</figcaption></figure><h4>End to end flow</h4><ol><li>Raw healthcare dataset lands into BigQuery</li><li>Cloud DBT transforms raw data into Health Cloud ready models</li><li>Cloud Composer orchestrates extraction and API execution</li><li>Transformed data is exported to Cloud Storage as CSV files</li><li>Composer submits jobs to Salesforce Bulk API</li><li>Salesforce processes batches asynchronously</li><li>Failed records are captured and retried</li><li>Monitoring and alerting track pipeline health</li></ol><h4>Architecture Components</h4><p><strong>BigQuery</strong> — It acts as the centralized analytical wearhouse.</p><p>Responsibilities:</p><ul><li>Store raw and curated healthcare datasets</li><li>Support scalable analytical transformations</li><li>Enable incremental extraction logic</li><li>And maintain audit history</li></ul><p><strong>Cloud DBT </strong>— Cloud DBT transforms source data into Salesforce-compatible business models.</p><p>Responsibilities:</p><ul><li>Data cleansing</li><li>Business rule implementation</li><li>Incremental modeling</li><li>Schema standardization</li><li>Surrogate key generation (these are required for salesforce objects)</li><li>Data quality testing</li></ul><p><strong>Why DBT is Important Here — DBT ensures:</strong></p><ul><li>Salesforce-ready schema alignment</li><li>Consistent business transformations</li><li>Reusable SQL models</li><li>Version controlled transformations</li><li>Test-drive pipelines</li></ul><p>This significantly reduces failuers during Salesforce ingestion.</p><p><strong>Cloud Compose</strong>r — Cloud Composer (Airflow) orchestrates the entire workflow.</p><p>Responsibilities:</p><ul><li>Trigger DBT jobs</li><li>Export BigQuery Data</li><li>Chuck large files (Bulk API has a limit on file size)</li><li>Poll job status</li><li>Retry failed jobs</li><li>Trigger alerts</li></ul><p>Typical DAG Flow:</p><pre>Start<br>  ↓<br>Run DBT Models<br>  ↓<br>Export BigQuery Data to GCS<br>  ↓<br>Split Large Files<br>  ↓<br>Authenticate<br>  ↓<br>Create Salesforce Bulk Job<br>  ↓<br>Upload CSV Data<br>  ↓<br>Close Bulk Job<br>  ↓<br>Poll Job Status<br>  ↓<br>Fetch Success / Failed Records<br>  ↓<br>Retry Failed Records (optional)<br>  ↓<br>Archive Processed Files<br>  ↓<br>End</pre><h3>Salesforce Bulk API 2.0 Workflow</h3><p>Salesforce Bulk API operates asynchronously.</p><h4>Step 1: Authenticate with Salesforce</h4><p>Before calling the API, generate an OAuth access token</p><p>Example</p><pre>import requests<br><br>auth_url = &quot;https://login.salesforce.com/services/oauth2/token&quot;<br><br>payload = {<br>    &quot;grant_type&quot;: &quot;password&quot;,<br>    &quot;client_id&quot;: &quot;YOUR_CLIENT_ID&quot;,<br>    &quot;client_secret&quot;: &quot;YOUR_CLIENT_SECRET&quot;,<br>    &quot;username&quot;: &quot;YOUR_USERNAME&quot;,<br>    &quot;password&quot;: &quot;YOUR_PASSWORD + SECURITY_TOKEN&quot;<br>}<br><br>response = requests.post(auth_url, data=payload)<br>auth_data = response.json()<br>access_token = auth_data[&quot;access_token&quot;]<br>instance_url = auth_data[&quot;instance_url&quot;]<br><br>print(&quot;Authenticated Successfully&quot;)</pre><h4>Step 2: Create Bulk API Job</h4><p>Create an ingestion job for insert, update, upsert, or delete operations.</p><p><strong>Purpose — </strong>Tell Salesforce:</p><ul><li>which object to load</li><li>operation type</li><li>file format</li><li>external ID field (for upserts)</li></ul><p>Example</p><pre>headers = {<br>    &quot;Authorization&quot;: f&quot;Bearer {access_token}&quot;,<br>    &quot;Content-Type&quot;: &quot;application/json&quot;<br>}<br><br>job_payload = {<br>    &quot;object&quot;: &quot;Contact&quot;,<br>    &quot;operation&quot;: &quot;upsert&quot;,<br>    &quot;externalIdFieldName&quot;: &quot;External_Id__c&quot;,<br>    &quot;contentType&quot;: &quot;CSV&quot;,<br>    &quot;lineEnding&quot;: &quot;LF&quot;<br>}<br><br>job_url = f&quot;{instance_url}/services/data/v58.0/jobs/ingest&quot;<br><br>response = requests.post(<br>    job_url,<br>    headers=headers,<br>    json=job_payload<br>)<br><br>job_info = response.json()<br>job_id = job_info[&quot;id&quot;]<br>print(f&quot;Job Created: {job_id}&quot;)</pre><h4>Step 3: Upload CSV Data</h4><p>Upload the CSV file into the created job and send bulk records to the processing.</p><p>Example</p><pre>upload_url = f&quot;{instance_url}/services/data/v58.0/jobs/ingest/{job_id}/batches&quot;<br><br>with open(&quot;contacts.csv&quot;, &quot;rb&quot;) as file:<br><br>    response = requests.put(<br>        upload_url,<br>        headers={<br>            &quot;Authorization&quot;: f&quot;Bearer {access_token}&quot;,<br>            &quot;Content-Type&quot;: &quot;text/csv&quot;<br>        },<br>        data=file<br>    )<br><br>print(&quot;CSV Uploaded Successfully&quot;)</pre><h4>Step 4: Close the Job</h4><p>After uploading data, close the job so Salesforce can start processing, which trigger asynchronous execution</p><p>Example</p><pre>close_url = f&quot;{instance_url}/services/data/v58.0/jobs/ingest/{job_id}&quot;<br><br>close_payload = {<br>    &quot;state&quot;: &quot;UploadComplete&quot;<br>}<br><br>response = requests.patch(<br>    close_url,<br>    headers=headers,<br>    json=close_payload<br>)<br><br>print(&quot;Job Closed Successfully&quot;)</pre><h4>Step 5: Salesforce Processes Data Asynchronously</h4><p>Once the execution starts:</p><ul><li>Salesforce validates records</li><li>Processes batches internally</li><li>Applies inserts/upserts</li><li>Generates success/failure logs</li></ul><p><strong>Possible Job States</strong></p><ul><li><strong>Open</strong> ⇒ Job created</li><li><strong>UploadComplete</strong> ⇒ Ready for processing</li><li><strong>InProgress</strong> ⇒ Salesforce processing</li><li><strong>JobComplete</strong> ⇒ Successfully completed</li><li><strong>Failed</strong> ⇒ Job failed</li><li><strong>Aborted</strong> ⇒ Job manually stopped</li></ul><h4>Step 6: Poll Job Status</h4><p>Monitor the job until processing completes.</p><p>Example</p><pre>import time<br><br>status_url = f&quot;{instance_url}/services/data/v58.0/jobs/ingest/{job_id}&quot;<br><br>while True:<br><br>    response = requests.get(<br>        status_url,<br>        headers=headers<br>    )<br><br>    status = response.json()[&quot;state&quot;]<br><br>    print(f&quot;Current Status: {status}&quot;)<br><br>    if status in [&quot;JobComplete&quot;, &quot;Failed&quot;, &quot;Aborted&quot;]:<br>        break<br><br>    time.sleep(10)</pre><h4>Step 7: Fetch Failed Records (Optional)</h4><p>Retrieve records that failed during processing. Capture errors for retry or debugging. <strong><em>Note — Retry cycle may follow similar steps mentioned in this workflow</em></strong></p><p>Example</p><pre>failed_url = f&quot;{instance_url}/services/data/v58.0/jobs/ingest/{job_id}/failedResults&quot;<br><br>response = requests.get(<br>    failed_url,<br>    headers=headers<br>)<br><br>print(response.text)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8_TmBlNPBNYYLhsYw-8wMw.png" /><figcaption><strong>Common Failure Reasons</strong></figcaption></figure><h3>Handling Salesforce API Limits</h3><p>Salesforce imposes below limits</p><ul><li>Daily API limits</li><li>Concurrency limits</li><li>Batch processing constraints</li></ul><p>Best practices while working with data ingestion into Salesforce Health Cloud</p><ol><li>Use Bulk API 2.0 — Avoid row by row REST inserts</li><li>Control Batch Sizes — Recommeded 10k-50k records per batch</li><li>Parallelism control — Avoid excessive parallel uploads for related objects</li></ol><h3>Error Handling Strategy</h3><p>Enterprise integrations must be resilient. Recommended Failure Handling</p><h4><strong>Retry-able Errors</strong></h4><p><strong>Examples:</strong></p><ul><li>Network timeout</li><li>Salesforce temporary unavailability</li><li>API throttling</li><li>Bulk API throws INVALID_FIELD (Foreign Key Not Found) error</li></ul><p><strong>Action:</strong></p><ul><li>Retry automatically</li><li>Use exponential backoff</li></ul><h4>NonRetry-able Errors</h4><p><strong>Examples:</strong></p><ul><li>Invalid field mapping</li><li>Missing mandatory fields</li><li>Validation rule failure</li><li>Data type mismatch</li></ul><p><strong>Action:</strong></p><ul><li>Capture failed rows (using failed record endpoint)</li><li>Store in error bucket/table</li><li>Notify support teams</li></ul><h3>Schema Evolution Handling</h3><p>Healthcare systems evolve continuously. New fields may be added frequently. Instead of hardcoding, use Config-Driven Mapping</p><pre>mapping = {<br>&#39;patient_id&#39;: &#39;External_Id__c&#39;<br>}</pre><p>Maintain metadata-driven mappings:</p><pre>Source Column           Salesforce Column<br>-----------------------------------------<br>patient_id              external_id__c<br>email                   Email<br>care_status             care_status__pc<br>patient_code            patient_code__c</pre><p>This enables:</p><ul><li>Easier onboarding of fields</li><li>Reduced deployment effort</li><li>Dynamic transformations</li></ul><h3>Data Security Best Practices</h3><h4>Secret Manager</h4><p>Never hardcore credentials in code. Store them inside secret manager such as Google Secret Manager. Use it to store:</p><ul><li>Salesforce token</li><li>Client secrets</li><li>OAuth credentials</li></ul><h4>IAM Controls</h4><p>Apply least-privilege accesses to</p><ul><li>Composer Service Accounts</li><li>BigQuery access</li><li>GCS permissions</li><li>Secret access</li></ul><h4>Audit Logging</h4><p>Enable audit loagging for:</p><ul><li>Composer logs</li><li>BigQuery audit logs</li><li>Salesforce API logs</li><li>Access tracking</li></ul><h3>Common Challenges in Real Projects</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rprJKIvltctZcTwN7Rd9_A.png" /></figure><h3>End-to-End Benefits of This Architecture</h3><p>This architecture provides:</p><ul><li>Scalable enterprise ingestion</li><li>Reduced operational overhead</li><li>Reliable retry handling</li><li>Better observability</li><li>Secure healthcare data movement</li><li>Faster Salesforce synchronization</li><li>Modular and reusable design</li></ul><p>Most importantly, <strong><em>it establishes a production-ready framework that can scale across multiple Salesforce objects and healthcare domains.</em></strong></p><h3>Conclusion</h3><p>Integrating BigQuery with Salesforce Health Cloud at enterprise scale requires much more than simply calling APIs.</p><p>A robust implementation must handle:</p><ul><li>Large data volumes</li><li>Incremental processing</li><li>API limits</li><li>Schema evolution</li><li>Retry handling</li><li>Security requirements</li><li>Monitoring and operational resilience</li></ul><p>This approach not only improves operational efficiency but also enables healthcare teams to access accurate and timely patient data directly inside Salesforce Health Cloud.</p><h3>Final Thoughts</h3><p>As healthcare organizations continue modernizing their data platforms, the combination of cloud-native orchestration, transformation frameworks, and asynchronous API integrations will become increasingly important.</p><p>The architecture discussed here can also be extended to:</p><ul><li>Near real-time streaming integrations</li><li>Multi-region deployments</li><li>Multi-cloud synchronization</li><li>Event-driven architectures</li></ul><p>Building these integrations with strong engineering standards today creates a scalable foundation for future healthcare data ecosystems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fbb070d55db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving Schema Evolution in Data Pipelines: Standards Every Data Engineer Should Follow]]></title>
            <link>https://medium.com/@sunilkhairnar777/solving-schema-evolution-in-data-pipelines-standards-every-data-engineer-should-follow-0cf00bde6d1d?source=rss-e83341cfdb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/0cf00bde6d1d</guid>
            <category><![CDATA[google-bigquery]]></category>
            <category><![CDATA[schema-evolution]]></category>
            <category><![CDATA[data-pipeline]]></category>
            <dc:creator><![CDATA[Sunil Khairnar]]></dc:creator>
            <pubDate>Tue, 12 May 2026 05:33:04 GMT</pubDate>
            <atom:updated>2026-05-12T05:33:04.131Z</atom:updated>
            <content:encoded><![CDATA[<p>Most data pipelines don’t fail because of infrastructure. They fail because somebody upstream changed the data.</p><ul><li>New column appears.</li><li>Datatype changes.</li><li>Nested JSON structure evolves.</li><li>Producer silently renames a field.</li></ul><p>And suddenly:</p><ul><li>DBT models fail</li><li>MERGE jobs break (In my case BigQuery)</li><li>Dashboards show incorrect numbers</li><li>Streaming pipelines start lagging</li></ul><p>If you’ve worked on production-grade data platforms long enough, you realize something important:</p><blockquote><strong><em>Schema evolution is not a rare problem. It is a certainty.</em></strong></blockquote><p>The real challenge is not preventing schema changes. The challenge is designing pipelines that survive schema evolution gracefully.</p><p>In this article, I’ll explain:</p><ul><li>Why schema evolution breaks pipelines</li><li>Common mistakes data engineers make</li><li>Engineering standards that actually work</li><li>Real-world examples using modern data platforms</li><li>How to design robust and scalable pipelines</li></ul><h3>What is Schema Evolution?</h3><p>In simple terms, <strong>Schema Evolution</strong> is the ability of a data system to change its structure (adding, renaming, or modifying columns) over time without breaking the entire pipeline or losing historical data.</p><h4><strong>A Real-World Production Example: The “E-Commerce Discount” Disaster</strong></h4><p>Imagine you work for a major e-commerce platform. Your production database has a Sales table that tracks every purchase.</p><h4>The Starting Point (Version 1)</h4><p>Your schema is simple and strict:</p><pre>order_id : INT64<br>price : FLOAT64<br>discount_code : STRING</pre><h4><strong>The Change (The Evolution)</strong></h4><p>The Marketing team launches a new “Loyalty Program.” Instead of one discount code, they now allow users to stack multiple discounts.</p><p><strong>The Upstream Change:</strong> The backend developers change the discount_code field from a single <strong>String</strong> to an <strong>Array of Strings</strong> (e.g., [&#39;SUMMER24&#39;, &#39;WELCOME10&#39;]).</p><h4>The “Production Crisis”</h4><p>If you don’t have a schema evolution strategy, here is what happens:</p><ul><li><strong>In Batch Pipelines:</strong> Your nightly load job from the app database to BigQuery hits that first array. BigQuery says: <em>“Wait, I expected a String, but you gave me a List.”</em> The job <strong>fails</strong>. The dashboard for the stakeholders is empty the next morning.</li><li><strong>In Real-Time Pipelines:</strong> Your streaming connector (like Datastream) keeps trying to push the array into the string column. It gets rejected. The “backlog” of messages grows, the system slows down, and eventually, the whole pipeline crashes.</li></ul><h3>Common Mistakes Data Engineers Make</h3><h4><strong>Mistake 1 — </strong>Tight Coupling Between Source and Curated Tables</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QplBy5j9q2XpnR9vJY9Cmg.png" /></figure><p>Why this fails:</p><ul><li>Any schema change directly impacts analytics</li><li>No protection layer exists</li><li>Downstream systems break immediately</li></ul><h4>Mistake 2 — Assuming Datatypes Never Change</h4><p>Real-world example:</p><p>Original:</p><pre>&quot;discount_code&quot;: &quot;WELCOME-10&quot;</pre><p>Later:</p><pre>&quot;discount_code&quot;: [&quot;WELCOME-10&quot;, &quot;NEW_YEAR-10&quot;]</pre><p>This breaks:</p><ul><li>JOIN logic</li><li>MERGE operations</li><li>Incremental pipelines</li></ul><h4>Mistake 3— Using SELECT *</h4><p>This is one of the most dangerous patterns.</p><p>Example:</p><pre>SELECT *<br>FROM raw_orders</pre><p>Problems:</p><ul><li>Unexpected columns propagate downstream</li><li>Renamed fields silently break transformations</li><li>Analytics becomes unpredictable</li></ul><h4>Mistake 4: No Schema Ownership Standards</h4><p>Many teams:</p><ul><li>Change APIs freely</li><li>Don’t communicate schema updates</li><li>Don’t maintain contracts</li></ul><p>Result: <strong>downstream chaos.</strong></p><h3>Standards That Actually Make Pipelines Robust</h3><p>Now let’s discuss what works in real production systems.</p><h4>Standard 1: Separate Raw and Curated Layers</h4><p>This is foundational. The raw layer should be schema flexible. Store data as is and preserve original payload. One can relate this with the <strong>Medallion Architecture</strong> (Bronze/Silver/Gold)</p><h4>Standard 2: Auto-Evolution (I use this most often in BigQuery)</h4><p>When using BigQuery for batch or streaming ingestion, you can programmatically allow the schema to evolve.</p><pre>bq load \<br>--source_format=CSV \<br>--autodetect \<br>--schema_update_option=ALLOW_FIELD_ADDITION \<br>--schema_update_option=ALLOW_FIELD_RELAXATION \<br>your_dataset.your_table \<br>gs://your-bucket/data.csv</pre><h4>Key Configurations Explained</h4><ul><li><strong>ALLOW_FIELD_ADDITION</strong>: This is what enables &quot;Schema Evolution.&quot; If your source file has a column new_marketing_tag that doesn&#39;t exist in your BigQuery table, BigQuery will add it to the schema automatically instead of failing the job.</li><li><strong>ALLOW_FIELD_RELAXATION</strong>: Very useful for production. If your BigQuery table has a column marked as REQUIRED, but a new batch of data is missing that column, this option &quot;relaxes&quot; the constraint to NULLABLE so the pipeline doesn&#39;t break. <strong><em>Warning — schema relaxation is a one-way street. Y</em></strong><em>ou can’t easily go back to </em><em>REQUIRED without a table recreate.</em></li><li><strong>autodetect=True</strong>: Essential for discovery. It tells BigQuery to scan the source file and compare its structure to the existing table. Works well for evolving schemas, but for production pipelines, explicit schema management is usually safer.</li></ul><h4>Important Limitation</h4><p>BigQuery <strong>cannot</strong> automatically change a data type of an existing column (e.g., changing STRING to INT64). If a source field has a conflicting type compared to the existing table, the job will still fail. <strong>Pro-Tip</strong> — This is why using the <strong>JSON Data Type</strong> for volatile fields remains the &quot;Best Practice&quot; for high-frequency evolution.</p><h4>Standard 3: Use Backward-Compatible Changes Whenever Possible</h4><p>In production environments, <strong>Backward Compatibility</strong> means your schema changes should never break existing “consumers” — whether those are dbt models, Looker dashboards, or Python scripts.</p><p><strong>Good schema changes:</strong><br> ✅ Add nullable fields<br> ✅ Add optional attributes</p><p><strong>Dangerous changes:</strong><br> ❌ Rename columns<br> ❌ Remove fields<br> ❌ Change datatypes</p><h4>Standard 4: Quarantine Invalid Records</h4><p>Do not fail entire pipelines because of few bad records. Instead isolate problematic events. Use DLQ if using Dataflow or separate out the bad records into different table in DBT before applying the transformation rules.</p><h4>Standard 5: Add Data Validation Layer</h4><p>Your stakeholders don’t care about your pipeline; they care about their Looker or Tableau dashboards. Add a validation layer and data contract before making the data available for end users.</p><p>Validation layer should check:</p><ul><li>Required fields</li><li>Datatypes</li><li>Value ranges</li><li>Null spikes</li></ul><h4>Standard 6: Schema Contracts Between Producers and Consumers</h4><p>One of the biggest operational improvements — <strong>explicit contracts</strong>. Instead of ‘<em>Teams will coordinate manually</em>’</p><p>Define:</p><ul><li>Required fields</li><li>Allowed datatypes</li><li>Backward compatibility rule</li></ul><p>Example contract. This creates accountability.</p><pre>{<br>  &quot;event_name&quot;: &quot;order_created&quot;,<br>  &quot;schema_version&quot;: 2,<br>  &quot;required_fields&quot;: [<br>    &quot;order_id&quot;,<br>    &quot;customer_id&quot;,<br>    &quot;order_create_datetime&quot;<br>  ]<br>}</pre><p>Use tools like <a href="https://docs.confluent.io/platform/current/schema-registry/fundamentals/schema-evolution.html#schema-evolution"><strong>Confluent Schema Registry</strong></a> or <a href="https://docs.aws.amazon.com/glue/latest/dg/schema-registry.html"><strong>AWS Glue Schema Registry</strong></a><strong> </strong>to enforce these json contacts.</p><h3>Realistic Production Scenario</h3><p>Imagine an e-commerce platform add new field to the existing data stream. This should NOT:<br> ❌ break ingestion<br> ❌ fail analytics<br> ❌ crash streaming jobs</p><p>A robust pipeline should:<br> ✅ ingest successfully<br> ✅ preserve raw payload<br> ✅ validate schema<br> ✅ update curated models safely</p><p><strong>Robust Pipelines Actually Optimize For Not perfection. Robust pipelines optimize for:</strong></p><ul><li>Recoverability</li><li>Flexibility</li><li>Observability</li><li>Controlled evolution</li></ul><p><strong><em>Modern data engineering is less about preventing change and more about surviving change safely.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0cf00bde6d1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[BigQuery Partitioning vs Clustering: What Actually Improves Performance?]]></title>
            <link>https://medium.com/@sunilkhairnar777/bigquery-partitioning-vs-clustering-what-actually-improves-performance-3ff2c19ae5ec?source=rss-e83341cfdb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ff2c19ae5ec</guid>
            <category><![CDATA[partitioning]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[google-bigquery]]></category>
            <category><![CDATA[gcp]]></category>
            <dc:creator><![CDATA[Sunil Khairnar]]></dc:creator>
            <pubDate>Fri, 08 May 2026 08:51:15 GMT</pubDate>
            <atom:updated>2026-05-08T08:51:15.986Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve worked with BigQuery long enough, you’ve probably heard this advice:</p><blockquote><em>“</em>Use partitioning and clustering to optimize performance.<em>”</em></blockquote><p>Sounds simple, but here’s the problem:<br>We all know <em>what</em> partitioning and clustering are — very few can answer:</p><ul><li><strong>When they actually help</strong></li><li><strong>When they don’t</strong></li><li><strong>And which one saves more money in real production workloads</strong></li></ul><p>Poor use of partitioning and clustering can be just as bad as not using them at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IBEF1zb0qwBol4tX3xylKw.png" /><figcaption>When your data strategy is… less than optimal.</figcaption></figure><p>So let’s break this down properly to avoid poor use of partitioning and clustering.</p><p>Start with high level difference between Partitioning and Clustering as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/970/1*AdcV0-VX9wHDw4F2y6wxlQ.png" /></figure><h3>What is Partitioning?</h3><p>Partitioning splits a large table into smaller segments based on a column. Instead of scanning the entire table, BigQuery scans only relevant partitions.</p><p>❌ Non-Partitioned Table Query — BigQuery must perform a <strong>Full Table Scan</strong>, reading every single column block to find the rows that match your date.</p><pre>SELECT <br>    order_id, <br>    customer_id, <br>    total_amount<br>FROM <br>    `my_project.my_dataset.sales_data_non_partitioned`<br>WHERE <br>    transaction_date = &#39;2025-07-04&#39;;</pre><ul><li><strong>Data Scanned:</strong> <strong>500 GB</strong> (The entire table is read to find the filter match).</li><li><strong>Cost:</strong> <strong>~$3.12</strong> (Based on $6.25 per TB).</li><li><strong>Performance:</strong> Slower execution as it reads 100% of the data.</li></ul><p>✅ Partitioned Table Query — If the table is partitioned by the transaction_date column, BigQuery uses <strong>Partition Pruning</strong>. It knows exactly which storage blocks contain data for &#39;2025-07-04&#39; and ignores the rest.</p><pre>SELECT <br>    order_id, <br>    customer_id, <br>    total_amount<br>FROM <br>    `my_project.my_dataset.sales_data_partitioned`<br>WHERE <br>    transaction_date = &#39;2025-07-04&#39;;</pre><ul><li><strong>Data Scanned:</strong> <strong>~300 MB</strong> (Only the data for that specific day is read).</li><li><strong>Cost:</strong> <strong>&lt;$0.02</strong> (Virtually free).</li><li><strong>Performance:</strong> Extremely fast because it skips 99.9% of the table.</li></ul><h4>Best Use Cases for Partitioning</h4><p>Partitioning works best when:</p><ul><li>Data is time-series based</li><li>Queries frequently filter by date</li></ul><p>Common columns:</p><ul><li>created_at</li><li>transaction_date</li><li>ingestion_date</li><li>last_modified_datetime</li></ul><h3>Avoid below Partitioning Mistakes</h3><h4><em>1. Wrong Partition Filter</em></h4><p>This is the most frequent error. If you wrap the partition column in a function, BigQuery cannot use the partition index because it has to execute that function on every single row first.</p><p>Below is the example of wrong partition filter (full table scan)</p><pre>SELECT<br>    order_id, <br>    customer_id, <br>    total_amount<br>FROM `my_project.dataset.orders`<br>WHERE DATE(transaction_timestamp) = &quot;2026-01-15&quot;;</pre><p><strong>Why:</strong> BigQuery has to extract the date from every single timestamp in the table before it can compare it.</p><p>Instead update your query to make use of correct partition filter as below</p><pre>SELECT<br>    order_id, <br>    customer_id, <br>    total_amount<br>FROM `my_project.dataset.orders`<br>WHERE transaction_timestamp &gt;= &quot;2026-01-15 00:00:00&quot; <br>      AND transaction_timestamp &lt; &quot;2026-01-16 00:00:00&quot;</pre><h4>2. Over-Partitioning</h4><p>While partitioning is a powerful tool for cost-saving, you can have “<em>too much of a good thing.</em>” <strong>Over-partitioning</strong> occurs when you divide your data into so many small segments that the overhead of managing the metadata outweighs the benefits of scanning less data.</p><h4>When is it Over-Partitioning?</h4><ol><li><strong>Tiny Datasets:</strong> If your total table size is under <strong>1 GB</strong>, partitioning often makes queries <em>slower</em> because the overhead of managing partitions is greater than just reading the whole 1 GB in one go.</li><li><strong>High Cardinality Columns:</strong> Partitioning by something like user_id or order_id is impossible (and wrong). BigQuery only supports partitioning by <strong>Time/Date</strong>, <strong>Integer Range</strong>, or <strong>Ingestion Time</strong>. For high-cardinality filtering, you should use <strong>Clustering</strong> instead (we will discuss more in detail).</li><li><strong>Frequent Small Loads:</strong> If you stream tiny amounts of data into thousands of different partitions, you can hit “Rate Limits” for metadata updates in BigQuery.</li></ol><h4>The Golden Rule</h4><p>Aim for partitions that are at least <strong>100 MB to 1 GB</strong> in size. If your partitions are only a few kilobytes or megabytes, you are likely over-partitioning and should consider a broader partition grain (e.g., switching from HOUR to DAY or DAY to MONTH).</p><h3>What is Clustering?</h3><p>Clustering organizes data <em>within partitions</em> based on selected columns. Think of it as, sorting related data closer together. It is most effective when used for high-cardinality columns (columns with many unique values) like user_id, product_id, or country_code.</p><h4>The Scenario</h4><p>Imagine a table of <strong>Global Web Logs</strong> that is already partitioned by date. You frequently run queries to analyze specific users or specific countries.</p><p>❌ Table Without Clustering — Data is added in the order it arrives. User IDs and Country codes are scattered randomly throughout the storage blocks for that day.</p><pre>SELECT<br>    event_date,<br>    event_timestamp,<br>    event_name,<br>    event_parms,<br>    user_id,<br>    user_properties<br>FROM `my_project.dataset.web_logs`<br>WHERE date = &#39;2026-05-01&#39; <br>  AND country_code = &#39;IN&#39;;</pre><ul><li><strong>Performance:</strong> BigQuery prunes the partition for May 1st, but then it must perform a <strong>linear scan</strong> of every single block in that partition to find the ‘IN’ rows.</li><li><strong>Data Scanned:</strong> 100% of the May 1st partition.</li></ul><p>✅ Table With Clustering — You cluster the table by country_code. Within each date partition, BigQuery now keeps all &#39;IN&#39; rows physically next to each other.</p><pre>SELECT<br>    event_date,<br>    event_timestamp,<br>    event_name,<br>    event_parms,<br>    user_id,<br>    user_properties<br>FROM `my_project.dataset.web_logs`<br>WHERE date = &#39;2026-05-01&#39; <br>  AND country_code = &#39;IN&#39;;</pre><ul><li><strong>Performance:</strong> BigQuery prunes the date partition <strong>AND</strong> uses the cluster index to jump straight to the blocks containing ‘IN’. It “skips” the blocks containing ‘US’, ‘UK’, or ‘FR’.</li><li><strong>Data Scanned:</strong> <strong>~10–20%</strong> of the May 1st partition (depending on how much ‘IN’ data exists).</li></ul><h4>Best Use Cases for Clustering</h4><p>Clustering works best when:</p><ul><li>Columns are frequently filtered</li><li>High cardinality exists</li></ul><p>Great clustering columns:</p><ul><li>customer_id</li><li>product_id</li><li>region</li><li>status</li></ul><h3>Avoid below Clustering Mistakes</h3><h4>1. Clustering Low Cardinality Columns</h4><p>In BigQuery, <strong>Low Cardinality</strong> refers to columns with very few unique values (e.g., gender, status_active, or boolean_flag).</p><p>While clustering is usually a “best practice,” using it on low cardinality columns is often a waste of resources — or worse, it can actually <strong>increase your slot usage</strong> without saving you a single cent.</p><p>Below is the example of clustering low cardinality column</p><pre>#Imagine a table with 100 million rows of user data. <br>#You decide to cluster it by a column called is_active (TRUE or FALSE).<br><br>SELECT <br>    user_id,<br>    user_name.<br>    address,<br>    email_id<br>FROM `my_project.dataset.users` <br>WHERE is_active = TRUE;</pre><p><strong>Why:</strong></p><p><strong>1. The “50/50” Data Distribution</strong> If 50% of your users are active and 50% are inactive, BigQuery still has to scan <strong>half the table</strong>. Clustering works by skipping “blocks” of data. Because the values are so coarse, nearly every storage block will likely contain at least <em>some</em> TRUE values and <em>some</em> FALSE values.</p><ul><li><strong>The Issue:</strong> BigQuery cannot “skip” a block unless it is 100% free of the value you are looking for. In low cardinality sets, the data is rarely “pure” enough to skip entire blocks.</li></ul><p><strong>2. Metadata Overhead vs. Gain</strong> BigQuery performs “Automatic Re-clustering” in the background to keep your data sorted.</p><ul><li><strong>The Issue:</strong> You are paying (in background resources/slot time) for BigQuery to sort a column that only has two options. The effort to sort TRUE vs FALSE results in almost zero reduction in the &quot;Bytes Billed.&quot;</li></ul><p><strong>3. Block Overlap</strong> In BigQuery, clustering is “best effort.” If you have 10 TB of data and a column with only 3 values (Low, Medium, High), those values are spread across thousands of blocks.</p><ul><li><strong>The Issue:</strong> You might find that every single 1GB storage block contains all three values. If every block contains the value you are filtering for, <strong>you scan 100% of the data</strong>, and the clustering was useless.</li></ul><h4>The Better Alternative for Low Cardinality Columns</h4><p>If you have a low-cardinality column that you filter on constantly, do not cluster by it alone. Use one of these strategies:</p><p><strong>Composite Clustering:</strong> Cluster by the low-cardinality column <strong>first</strong>, and a high-cardinality column <strong>second</strong>.</p><ul><li><em>Example:</em> CLUSTER BY country_code, user_id. This groups all &quot;IN&quot; data together, and <em>within</em> the &quot;IN&quot; group, it sorts by user_id, making the blocks much more specific.</li></ul><p><strong>Partitioning:</strong> If the low cardinality column is a category you use to split your entire business (e.g., region_id), and there are fewer than 10,000 of them (partition limit per table), use <strong>Integer Range Partitioning</strong> instead. This creates a hard physical barrier that guarantees data skipping.</p><h4>2. Too many Cluster Columns</h4><p>While BigQuery allows you to specify up to <strong>4 columns</strong> for clustering, adding too many columns (or adding them in the wrong order) creates a “diminishing returns” effect. The primary problem is that <strong>clustering is hierarchical</strong>. The order of the columns matters significantly, and each additional column is only effective within the sorted groups of the previous column.</p><h3>When to Use What</h3><h4>Use Partitioning When:</h4><p>✔ Table is large<br>✔ Date filtering is common<br>✔ Cost reduction matters</p><h4>Use Clustering When:</h4><p>✔ Queries filter specific columns<br>✔ Data has high cardinality<br>✔ You already partitioned the table</p><h4>Use BOTH together</h4><p>Example:</p><pre>PARTITION BY DATE(created_at)<br>CLUSTER BY customer_id, region</pre><p>This gives:</p><ul><li>Lower scan cost</li><li>Faster filtering</li><li>Better performance</li></ul><h3>How to Verify Optimization</h3><p>In BigQuery UI:</p><ul><li>Open Query → Execution Details</li></ul><p>Check:</p><ul><li>Bytes scanned</li><li>Partition pruning</li><li>Shuffle size</li></ul><p>Always validate with actual execution stats.</p><h4>Biggest Lesson I Learned</h4><p>Most BigQuery optimization problems are not about SQL syntax.</p><p>They’re about:</p><ul><li>Data layout</li><li>Partition strategy</li><li>Query patterns</li></ul><p>Once you optimize storage design everything becomes faster and cheaper.</p><h3>Final Thoughts</h3><p>Partitioning and clustering are not “optional optimizations” in BigQuery. At scale, they are foundational design decisions.</p><p>If you use them correctly:</p><ul><li>Queries become dramatically faster</li><li>Costs drop significantly</li><li>Pipelines scale better</li></ul><p>If you ignore them, BigQuery bills can get ugly very quickly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ff2c19ae5ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[I Reduced My BigQuery Cost by 70% Using These 7 Proven Techniques]]></title>
            <link>https://medium.com/@sunilkhairnar777/i-reduced-my-bigquery-cost-by-70-using-these-7-proven-techniques-363a22a94b73?source=rss-e83341cfdb68------2</link>
            <guid isPermaLink="false">https://medium.com/p/363a22a94b73</guid>
            <category><![CDATA[query-optimization]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Sunil Khairnar]]></dc:creator>
            <pubDate>Mon, 30 Mar 2026 13:02:21 GMT</pubDate>
            <atom:updated>2026-03-30T13:02:21.545Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re using <a href="https://support.google.com/cloud/answer/9113366?hl=en"><strong>BigQuery</strong></a> on Google Cloud, you’ve probably had at least one moment where you checked your billing dashboard and thought:</p><blockquote><em>“How did this query cost </em>that much<em>?”</em></blockquote><p>I’ve been there.</p><p>In one of my recent projects, our monthly BigQuery cost was steadily increasing — without a proportional increase in business value. After a deep dive and a series of optimizations, I managed to reduce our costs by <strong>~70%</strong>, without sacrificing performance.</p><p>Here are the <strong>7 techniques that made the biggest difference</strong> 👇</p><h3>1. Stop Using SELECT * (This Alone Saves Money)</h3><p>This is the most common mistake.</p><p>BigQuery charges based on <strong>data scanned</strong>, not rows returned. So even if you return 10 rows, scanning unnecessary columns costs money.</p><h4>❌ Bad</h4><pre>SELECT * FROM patients;</pre><h4>✅ Better</h4><pre>SELECT patient_id, first_name, last_name, email_id<br>FROM patients;</pre><p>👉 <strong>Impact:</strong> Reduced scanned data by ~45% in some queries</p><h3>2. Use Partitioned Tables (Game Changer)</h3><p>Partitioning allows BigQuery to scan only relevant data.</p><p><strong>Example:</strong> Partition by transaction_date</p><pre>WHERE transaction_date BETWEEN &#39;2026-03-01&#39; AND &#39;2026-03-31&#39;</pre><p>Without partitioning → full table scan<br>With partitioning → only relevant partitions scanned</p><p>👉 <strong>Impact:</strong> 60–70% reduction in query cost</p><h3>3. Cluster Your Tables for Better Performance</h3><p>After partitioning, <strong>clustering</strong> further optimizes how data is stored.</p><p>Example:</p><pre>CLUSTER BY customer_id, order_id</pre><p>This helps BigQuery skip irrelevant blocks of data.</p><p>👉 Works best for:</p><ul><li><em>Large tables</em></li><li><em>Frequently filtered columns</em></li></ul><h3>4. Avoid Repeated Full Table Scans</h3><p>We found multiple dashboards running the <strong>same heavy queries repeatedly</strong>.</p><h4>Solution:</h4><ul><li>Create <strong>materialized tables</strong></li><li>Schedule jobs using Apache Airflow (via <a href="https://cloud.google.com/composer?hl=en">Composer</a>)</li></ul><p><strong>Instead of:</strong></p><ul><li><em>Running expensive queries 100 times/day</em></li></ul><p><strong>Do:</strong></p><ul><li><em>Precompute once → reuse results</em></li></ul><p>👉 <strong>Impact:</strong> Massive cost + performance improvement. Big Win.</p><h3>5. Use Approximate Functions When Precision Isn’t Critical</h3><p>BigQuery provides functions like <a href="https://docs.cloud.google.com/looker/docs/studio/approxcountdistinct"><em>APPROX_COUNT_DISTINCT</em></a>:</p><pre>APPROX_COUNT_DISTINCT(patient_id)</pre><p>instead of:</p><pre>COUNT(DISTINCT patient_id)</pre><p>👉 These are significantly cheaper and faster</p><p>👉 Ideal for:</p><ul><li>Dashboards</li><li>Trend analysis</li><li>Large datasets</li></ul><p>Don’t forget to checkout limitations of approx_count_distinct <a href="https://docs.cloud.google.com/looker/docs/studio/approxcountdistinct#limits_of_approx_count_distinct"><em>here</em></a>.</p><h3>6. Monitor Query Costs Before Running Them</h3><p>Use <strong>Query Validator</strong> in BigQuery UI.</p><p>Before running:</p><ul><li>Check “Bytes to be processed”</li></ul><p>If it looks huge → optimize before execution</p><p>👉 Pro Tip:<br>Set <strong>cost controls &amp; quotas</strong> in your project to avoid surprises</p><h3>7. Optimize Joins (hidden cost killer)</h3><p>Joins can silently explode your costs.</p><h4>Common issues:</h4><ul><li>Joining large tables without filters</li><li>Using CROSS JOIN accidentally</li></ul><h4>Fix:</h4><ul><li>Filter data <em>before</em> join</li><li>Use proper join keys</li><li>Avoid unnecessary joins</li></ul><pre>-- Filter first, then join<br>WITH filtered_appointments AS (<br>  SELECT appointment_id, patient_id, appointment_date, appointment_time<br>  FROM appointments<br>  WHERE appointment_date between &#39;2026-01-05&#39; and &#39;2026-01-10&#39;<br>)<br>SELECT appt.*, pat.first_name, pat.last_name, pat.email_id<br>FROM filtered_appointments appt<br>JOIN patients pat<br>ON appt.patient_id = pat.patient_id;</pre><p>👉 <strong>Impact:</strong> Reduced query cost by 30–50% in some pipelines</p><h4>📊 Final Results</h4><p>After applying these optimizations:</p><ul><li>💰 <strong>Cost reduced by ~70%</strong></li><li>⚡ <strong>Query performance improved</strong></li><li>📉 <strong>More predictable billing</strong></li></ul><h4>🚀 Bonus: Tools That Help</h4><ul><li><a href="https://docs.cloud.google.com/bigquery/docs/query-plan-explanation">BigQuery Query Plan Explanation</a></li><li><a href="https://docs.cloud.google.com/bigquery/docs/best-practices-costs">Cost breakdown</a></li><li><a href="https://docs.cloud.google.com/bigquery/docs/monitoring">Monitoring via Cloud Logging</a></li></ul><h4>🎯 Key Takeaways</h4><p>If you remember just 3 things:</p><ol><li>Don’t use SELECT *</li><li>Always partition large tables</li><li>Avoid repeated heavy queries</li></ol><h4>👋 Final Thoughts</h4><p>BigQuery is incredibly powerful — but also very easy to misuse.</p><p>A few smart optimizations can save <strong>thousands of dollars</strong> <strong>every month</strong>, especially at scale.</p><p>If you’re working with <strong>GCP + BigQuery</strong>, these techniques are not optional — they’re essential.</p><h4>💬 Let’s Connect</h4><p>If you found this useful, feel free to:</p><ul><li>Share your own optimization tricks</li><li>Ask questions in the comments</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=363a22a94b73" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>