<?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 Hitesh on Medium]]></title>
        <description><![CDATA[Stories by Hitesh on Medium]]></description>
        <link>https://medium.com/@hiteshkhk0105?source=rss-cd5a029c558f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*PzFsEICT03bYIS2adyLkIQ@2x.jpeg</url>
            <title>Stories by Hitesh on Medium</title>
            <link>https://medium.com/@hiteshkhk0105?source=rss-cd5a029c558f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 21:22:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hiteshkhk0105/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[Databricks Query Is Slow? Guide to reading through Query plan]]></title>
            <link>https://medium.com/@hiteshkhk0105/databricks-query-is-slow-guide-to-reading-through-query-plan-5c1cb400c1f9?source=rss-cd5a029c558f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c1cb400c1f9</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[query-optimization]]></category>
            <dc:creator><![CDATA[Hitesh]]></dc:creator>
            <pubDate>Wed, 10 Jun 2026 09:31:23 GMT</pubDate>
            <atom:updated>2026-06-10T09:31:23.870Z</atom:updated>
            <content:encoded><![CDATA[<p>Most slow-query conversations start too late.</p><p>Someone sees a dashboard timeout or a query running for minutes. The first suggestion is often, “Can we make the warehouse bigger?”</p><p>Sometimes that is the answer. But it should not be the first answer.</p><p>In Databricks, a slow query can mean:</p><ul><li>The query waited for warehouse capacity.</li><li>The scan read too much data.</li><li>The join multiplied rows.</li><li>A shuffle, sort, or aggregate spilled to disk.</li><li>A small number of tasks were skewed.</li><li>The SQL selected too many columns.</li><li>The dashboard is doing modeling work at runtime.</li><li>The query is hitting raw tables instead of curated marts.</li></ul><p>Those are different problems. Query Profile and Query History help you separate them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AUCwLBlbJCs7KIgvxF62tQ.gif" /></figure><h3>The Databricks Slow Query Workflow</h3><p>Here is the path I would follow:</p><ol><li>Check Query History.</li><li>Sort by total_duration_ms.</li><li>Split time into execution, compilation, and queue wait.</li><li>Open Query Profile.</li><li>Check summary metrics and top operators.</li><li>Inspect scan, join, shuffle, aggregate, sort, and filter nodes.</li><li>Look for spill, skew, exploding join, wide projection, or weak pruning.</li><li>Check whether filters are applied early.</li><li>Check whether the query reads raw tables instead of curated marts.</li><li>Decide between SQL rewrite, table layout, materialization, warehouse concurrency, or model redesign.</li></ol><p>The point is not to memorize every operator. The point is to know where to look first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5aJg76vWhDbDA2SiH1-t5A.gif" /></figure><h3>Step 1: Start In Query History</h3><p>Query History answers the first practical question:</p><p>Which query are we actually debugging?</p><p>If you are using Databricks SQL, start with system.query.history:</p><pre>SELECT<br>  statement_id,<br>  executed_by,<br>  statement_type,<br>  execution_status,<br>  total_duration_ms,<br>  execution_duration_ms,<br>  compilation_duration_ms,<br>  waiting_at_capacity_duration_ms,<br>  read_rows,<br>  produced_rows,<br>  start_time,<br>  statement_text<br>FROM system.query.history<br>WHERE compute.warehouse_id = &#39;&lt;warehouse-id&gt;&#39;<br>  AND start_time &gt;= NOW() - INTERVAL 7 DAY<br>ORDER BY total_duration_ms DESC<br>LIMIT 50;</pre><p>Now separate the problem:</p><p>MetricWhat It Tells Youtotal_duration_msFull wall-clock pain.execution_duration_msTime spent actually running.compilation_duration_msPlanning and optimization cost.waiting_at_capacity_duration_msWarehouse queue pressure.read_rowsScan/input volume.produced_rowsOutput volume and possible grain issues.</p><p>If queue wait dominates, Query Profile is not your first fix. You need to look at SQL warehouse concurrency, max clusters, workload isolation, or scheduling.</p><p>If execution dominates, open Query Profile.</p><h3>Step 2: Read Query Profile Like A Trace</h3><p>Databricks Query Profile shows an operator DAG. Think of it like a trace of the query:</p><p>Scan -&gt; Filter -&gt; Join -&gt; Exchange -&gt; Aggregate -&gt; Sort -&gt; Result</p><p>Your job is to find the operator where the query became expensive.</p><p>Start with:</p><p>Profile AreaAskSummaryIs the query IO-bound, compute-bound, queued, or planning-heavy?Top operatorsWhich node consumed the most time?DAGWhere do row counts expand or spill?Node detailsWhat rows, bytes, memory, and spill metrics prove the issue?</p><p>Do not stare at the whole DAG at once. Find the hot node, then inspect its inputs and outputs.</p><h3>Step 3: Check For Too Much Data Scanned</h3><p>This is the Databricks version of “bytes scanned” in Snowflake.</p><p>In Query Profile, start with scan nodes. Ask:</p><ul><li>How many rows were read?</li><li>How many files or bytes were scanned?</li><li>Did filters appear early?</li><li>Is file pruning effective?</li><li>Is the query selecting only the needed columns?</li><li>Is the query reading a raw table when a curated mart exists?</li></ul><p>Bad pattern:</p><p>SELECT * FROM raw.events WHERE event_name = &#39;purchase&#39;;</p><p>Better pattern:</p><pre>SELECT<br>  event_date,<br>  customer_id,<br>  order_id,<br>  revenue<br>FROM gold.fct_orders<br>WHERE event_date &gt;= DATE &#39;2026-06-01&#39;<br>  AND event_name = &#39;purchase&#39;;</pre><p>The better query gives the optimizer more help:</p><ul><li>A curated table.</li><li>Selective date predicate.</li><li>Narrow projection.</li><li>Columns that can benefit from stats and clustering.</li></ul><h3>Step 4: Check Joins And Join Cardinality</h3><p>Slow queries often hide in joins.</p><p>The profile question is simple:</p><p>Did the join output far more rows than expected?</p><p>If yes, you may have a grain problem.</p><p>Example:</p><pre>-- Risky: customer_promotions may contain many rows per customer.<br>SELECT<br>  o.order_id,<br>  c.segment,<br>  p.campaign_id<br>FROM gold.fct_orders o<br>JOIN gold.dim_customer c<br>  ON o.customer_id = c.customer_id<br>JOIN raw.customer_promotions p<br>  ON o.customer_id = p.customer_id;</pre><p>Safer:</p><pre>WITH promo_one_row_per_customer AS (<br>  SELECT<br>    customer_id,<br>    max_by(campaign_id, updated_at) AS latest_campaign_id<br>  FROM raw.customer_promotions<br>  GROUP BY customer_id<br>)<br>SELECT<br>  o.order_id,<br>  c.segment,<br>  p.latest_campaign_id<br>FROM gold.fct_orders o<br>JOIN gold.dim_customer c<br>  ON o.customer_id = c.customer_id<br>LEFT JOIN promo_one_row_per_customer p<br>  ON o.customer_id = p.customer_id;</pre><p>The Query Profile proof is the join node’s input and output row counts. If output rows multiply unexpectedly, fix the model grain before touching compute.</p><h3>Step 5: Look For Spill</h3><p>Spill means intermediate data exceeded available memory and was written to disk.</p><p>You can look for spill in Query History:</p><pre>SELECT<br>  statement_id,<br>  executed_by,<br>  spilled_local_bytes / (1024 * 1024) AS spilled_mb,<br>  read_bytes / (1024 * 1024) AS read_mb,<br>  total_duration_ms,<br>  start_time,<br>  statement_text<br>FROM system.query.history<br>WHERE compute.warehouse_id = &#39;&lt;warehouse-id&gt;&#39;<br>  AND start_time &gt;= NOW() - INTERVAL 7 DAY<br>  AND spilled_local_bytes &gt; 0<br>ORDER BY spilled_local_bytes DESC<br>LIMIT 50;</pre><p>Then confirm in Query Profile.</p><p>Common causes:</p><p>Spill AreaLikely CauseJoinToo many rows, wrong grain, heavy shuffle.AggregateGrouping too much data at runtime.Sort/windowWide rows, large ordered set, no pre-aggregation.Shuffle/exchangeData movement too large or skewed.</p><p>Spill can justify larger compute, but only after SQL shape and model shape are reasonable.</p><h3>Step 6: Check Queueing Separately</h3><p>Queueing is not the same as a slow query.</p><p>If waiting_at_capacity_duration_ms is high, the query waited for warehouse capacity. The fix may be:</p><ul><li>Increase max clusters.</li><li>Separate BI and ETL workloads.</li><li>Schedule heavy jobs away from dashboard peaks.</li><li>Use a different warehouse for ad hoc analysis.</li></ul><p>This is where resizing can be appropriate, but the evidence is queue wait, not an expensive join node.</p><h3>Step 7: Check Filter Timing</h3><p>Filters should reduce rows before expensive operations.</p><p>Bad pattern:</p><pre>WITH joined AS (<br>  SELECT *<br>  FROM raw.events e<br>  JOIN raw.sessions s<br>    ON e.session_id = s.session_id<br>)<br>SELECT *<br>FROM joined<br>WHERE event_date &gt;= DATE &#39;2026-06-01&#39;;</pre><p>Better:</p><pre>WITH filtered_events AS (<br>  SELECT<br>    event_date,<br>    session_id,<br>    customer_id,<br>    event_name<br>  FROM raw.events<br>  WHERE event_date &gt;= DATE &#39;2026-06-01&#39;<br>),<br>filtered_sessions AS (<br>  SELECT<br>    session_id,<br>    device_type,<br>    country<br>  FROM raw.sessions<br>  WHERE session_date &gt;= DATE &#39;2026-06-01&#39;<br>)<br>SELECT *<br>FROM filtered_events e<br>JOIN filtered_sessions s<br>  ON e.session_id = s.session_id;</pre><p>In Query Profile, this should reduce input rows before joins and exchanges.</p><h3>Step 8: Decide The Fix Family</h3><p>Do not jump to the prettiest fix. Match evidence to action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0EtfwFGMt6TkA9c8DJYdlQ.jpeg" /></figure><h3>Step 9: Validate Before Closing</h3><p>After a fix, compare:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b0SM9wg-9hEuvunBBVaHlw.jpeg" /></figure><p>You are not done when the query “feels faster.” You are done when the profile proves the old bottleneck is gone or no longer dominates.</p><h3>Final Checklist</h3><p>Use this when someone asks, “Why is this Databricks query slow?”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XLmkjPVFChVpAjW0NgpAhg.jpeg" /></figure><p>The most senior move is to diagnose before prescribing. Bigger compute is a tool, not a personality trait.</p><p>Sources:</p><ul><li>Databricks Query Profile: <a href="https://docs.databricks.com/aws/en/sql/user/queries/query-profile">https://docs.databricks.com/aws/en/sql/user/queries/query-profile</a></li><li>Databricks Query Performance Insights:</li><li><a href="https://docs.databricks.com/aws/en/sql/user/queries/performance-insights">https://docs.databricks.com/aws/en/sql/user/queries/performance-insights</a></li><li>Databricks SQL warehouse monitoring:</li><li><a href="https://docs.databricks.com/aws/en/compute/sql-warehouse/monitor/queries">https://docs.databricks.com/aws/en/compute/sql-warehouse/monitor/queries</a></li><li>Databricks SQL warehouse behavior:</li><li><a href="https://docs.databricks.com/aws/en/compute/sql-warehouse/warehouse-behavior">https://docs.databricks.com/aws/en/compute/sql-warehouse/warehouse-behavior</a></li><li>Databricks Data Skipping:</li><li><a href="https://docs.databricks.com/aws/en/delta/data-skipping">https://docs.databricks.com/aws/en/delta/data-skipping</a></li><li>Databricks Liquid Clustering:</li><li><a href="https://docs.databricks.com/aws/en/delta/clustering">https://docs.databricks.com/aws/en/delta/clustering</a></li><li>Databricks Materialized Views:</li><li><a href="https://docs.databricks.com/aws/en/ldp/dbsql/materialized">https://docs.databricks.com/aws/en/ldp/dbsql/materialized</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c1cb400c1f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 3: Building the Spark Consumer That Reads Kafka in Real Time]]></title>
            <link>https://medium.com/@hiteshkhk0105/part-3-building-the-spark-consumer-that-reads-kafka-in-real-time-5abe76d39efb?source=rss-cd5a029c558f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5abe76d39efb</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Hitesh]]></dc:creator>
            <pubDate>Thu, 04 Jun 2026 17:32:14 GMT</pubDate>
            <atom:updated>2026-06-04T17:32:14.869Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3O3JSkaapigHnpVzekwX8Q.jpeg" /></figure><p><em>Part 3 of 4 in the “Learn Kafka in 4 Hours” series. In </em><a href="https://medium.com/@hiteshkhk0105/stop-using-kafka-like-a-slow-database-how-i-hit-40-000-eps-on-a-laptop-15e1aab7eada"><em>Part 1 </em></a><em>we fixed the mental model. In </em><a href="https://medium.com/@hiteshkhk0105/part-2-building-a-kafka-producer-that-pushes-40-000-events-sec-from-a-laptop-77ee253916a2"><em>Part 2 </em></a><em>we built a Python producer that can push 40,000 events/sec from a laptop. Now we build the other half of the system: the consumer that reads those events, aggregates them in event time, and writes rolling metrics into Elasticsearch.</em></p><h3>The consumer’s real job</h3><p>Most first-pass Kafka consumers do one thing:</p><ol><li>read a message</li><li>parse it</li><li>write it somewhere else</li></ol><p>That’s not what we need here.</p><p>This project’s consumer has to do something harder:</p><ul><li>read a continuous stream from Kafka</li><li>parse JSON safely</li><li>reason in <strong>event time</strong>, not “when Spark happened to see it”</li><li>keep bounded state for rolling windows</li><li>update aggregates every trigger interval</li><li>survive crashes without data loss</li><li>write to a serving layer in a way that makes replay safe</li></ul><p>That is exactly the use case Spark Structured Streaming is good at.</p><p>The package we’ll walk is:</p><pre>consumer/<br>├── config.py<br>├── schemas.py<br>├── aggregations.py<br>├── sinks/elasticsearch_sink.py<br>├── alerting.py<br>└── main.py</pre><p>By the end of this article you’ll understand every file, every stateful operator, and every checkpoint in the consumer.</p><h3>The five concepts you need before reading the code</h3><p>If you’re new to streaming, these five ideas matter more than any API call:</p><p><strong>1. Consumer groups</strong></p><p>Kafka lets multiple consumers share one topic. Each partition is assigned to exactly one consumer in a group at a time. Add consumers, Kafka rebalances.</p><p><strong>2. Offsets</strong></p><p>Every consumer remembers its last position per partition. Restart and it keeps going from there.</p><p><strong>3. Event time</strong></p><p>The timestamp that matters is when the event actually happened, not when Spark processed it. If a mobile client buffers for 30 seconds before sending, processing time lies to you.</p><p><strong>4. Watermarks</strong></p><p>A watermark is Spark’s way of saying: “I’ll keep state open for late events up to this limit. After that I assume the window is done.”</p><p><strong>5. Checkpoints</strong></p><p>This is how Spark remembers progress and state across restarts. No checkpoint means no crash recovery.</p><p>Everything in the code is just a concrete implementation of those five ideas.</p><h3>File 1 — consumer/config.py (all the stream knobs)</h3><p>Just like the producer, the consumer starts with env-driven config:</p><pre>from __future__ import annotations<br>import os<br>from dataclasses import dataclass<br><br>@dataclass(slots=True)<br>class ConsumerSettings:<br>    kafka_bootstrap_servers: str = os.getenv(&quot;KAFKA_BOOTSTRAP_SERVERS&quot;, &quot;localhost:9092&quot;)<br>    kafka_topic: str = os.getenv(&quot;KAFKA_TOPIC&quot;, &quot;interactions&quot;)<br>    spark_window_duration: str = os.getenv(&quot;SPARK_WINDOW_DURATION&quot;, &quot;1 minute&quot;)<br>    spark_watermark: str = os.getenv(&quot;SPARK_WATERMARK&quot;, &quot;2 minutes&quot;)<br>    spark_trigger_interval: str = os.getenv(&quot;SPARK_TRIGGER_INTERVAL&quot;, &quot;30 seconds&quot;)<br>    spark_shuffle_partitions: str = os.getenv(&quot;SPARK_SHUFFLE_PARTITIONS&quot;, &quot;8&quot;)<br>    es_host: str = os.getenv(&quot;ES_HOST&quot;, &quot;http://localhost:9200&quot;)<br>    es_bulk_batch_size: int = int(os.getenv(&quot;ES_BULK_BATCH_SIZE&quot;, &quot;500&quot;))<br>    alert_threshold: int = int(os.getenv(&quot;ALERT_THRESHOLD&quot;, &quot;100&quot;))<br>    alert_webhook_url: str = os.getenv(&quot;ALERT_WEBHOOK_URL&quot;, &quot;&quot;)</pre><p>These are the dials that make the whole stream behavior explicit:</p><ul><li>spark_window_duration=&quot;1 minute&quot; means tumbling 1-minute windows</li><li>spark_watermark=&quot;2 minutes&quot; means we tolerate up to 2 minutes of lateness</li><li>spark_trigger_interval=&quot;30 seconds&quot; means Spark emits updates every 30 seconds</li><li>spark_shuffle_partitions=&quot;8&quot; controls downstream parallelism after groupBy/shuffle</li></ul><p>Those four settings are most of the consumer design in one place.</p><h3>File 2 — consumer/schemas.py (never trust raw JSON)</h3><p>The producer emits JSON. Spark reads Kafka bytes. Somewhere in the middle you need a contract.</p><p>That’s this file:</p><pre>from pyspark.sql.types import MapType, StringType, StructField, StructType<br>INTERACTION_SCHEMA = StructType(<br>    [<br>        StructField(&quot;event_id&quot;, StringType(), nullable=False),<br>        StructField(&quot;user_id&quot;, StringType(), nullable=False),<br>        StructField(&quot;item_id&quot;, StringType(), nullable=False),<br>        StructField(&quot;interaction_type&quot;, StringType(), nullable=False),<br>        StructField(&quot;timestamp&quot;, StringType(), nullable=False),<br>        StructField(&quot;session_id&quot;, StringType(), nullable=False),<br>        StructField(&quot;platform&quot;, StringType(), nullable=False),<br>        StructField(&quot;metadata&quot;, MapType(StringType(), StringType()), nullable=True),<br>    ]<br>)</pre><p>Why this matters:</p><ul><li>Spark will parse only what matches this structure.</li><li>Missing required fields become nulls.</li><li>Bad payloads can be filtered before they poison aggregations.</li><li>The consumer side becomes deterministic even if the producer changes.</li></ul><p>For a first version, JSON + explicit schema is perfectly reasonable.</p><p>For a production system that multiple teams evolve independently, you eventually want Schema Registry with Avro or Protobuf. But the discipline starts here: <strong>never let “schema-on-read means no schema” become your design.</strong></p><h3>File 3 — consumer/aggregations.py (this is the stream brain)</h3><p>This file does three jobs:</p><ol><li>normalize raw events into typed event time</li><li>define the per-user aggregation</li><li>define the per-item and global aggregations</li></ol><p>Let’s go function by function.</p><h3>normalize_events()</h3><pre>from __future__ import annotations<br>from pyspark.sql import DataFrame<br>from pyspark.sql import functions as F<br><br>def normalize_events(events: DataFrame) -&gt; DataFrame:<br>    return (<br>        events.withColumn(&quot;event_ts&quot;, F.to_timestamp(&quot;timestamp&quot;))<br>        .withColumn(&quot;event_date&quot;, F.to_date(&quot;event_ts&quot;))<br>        .withColumn(&quot;event_hour&quot;, F.hour(&quot;event_ts&quot;))<br>    )</pre><p>This is small, but it’s where the stream switches from “JSON text” to “typed event time.”</p><p>event_ts is the important column. Everything downstream uses it for watermarking and windows.</p><p>event_date and event_hour are derivations you might use later for partitioning, debugging, or alternate aggregate shapes.</p><p>The key thing is that parsing happens once, centrally, before any stateful logic starts.</p><h3>Per-user aggregation</h3><pre>def build_user_aggregates(events: DataFrame, window_duration: str, watermark: str) -&gt; DataFrame:<br>    return (<br>        events.withWatermark(&quot;event_ts&quot;, watermark)<br>        .groupBy(F.window(&quot;event_ts&quot;, window_duration), &quot;user_id&quot;)<br>        .agg(<br>            F.count(&quot;*&quot;).alias(&quot;interaction_count&quot;),<br>            F.approx_count_distinct(&quot;item_id&quot;).alias(&quot;unique_items&quot;),<br>            F.sum(F.when(F.col(&quot;interaction_type&quot;) == &quot;view&quot;, 1).otherwise(0)).alias(&quot;views&quot;),<br>            F.sum(F.when(F.col(&quot;interaction_type&quot;) == &quot;click&quot;, 1).otherwise(0)).alias(&quot;clicks&quot;),<br>            F.sum(F.when(F.col(&quot;interaction_type&quot;) == &quot;purchase&quot;, 1).otherwise(0)).alias(&quot;purchases&quot;),<br>            F.sum(F.when(F.col(&quot;interaction_type&quot;) == &quot;add_to_cart&quot;, 1).otherwise(0)).alias(&quot;add_to_carts&quot;),<br>        )<br>        .select(<br>            &quot;user_id&quot;,<br>            F.col(&quot;window.start&quot;).alias(&quot;window_start&quot;),<br>            F.col(&quot;window.end&quot;).alias(&quot;window_end&quot;),<br>            &quot;interaction_count&quot;,<br>            &quot;unique_items&quot;,<br>            &quot;views&quot;,<br>            &quot;clicks&quot;,<br>            &quot;purchases&quot;,<br>            &quot;add_to_carts&quot;,<br>        )<br>    )</pre><p>Read this literally:</p><ul><li>withWatermark(&quot;event_ts&quot;, watermark) means late events are allowed for up to 2 minutes</li><li>groupBy(F.window(&quot;event_ts&quot;, &quot;1 minute&quot;), &quot;user_id&quot;) means one state bucket per (minute, user)</li><li>F.count(&quot;*&quot;) counts total interactions</li><li>approx_count_distinct(&quot;item_id&quot;) gives a bounded-memory estimate of unique items</li><li>the F.sum(F.when(...)) expressions turn one event stream into a small metrics table</li></ul><p>This is the first place where streaming feels different from batch:</p><p>Spark is keeping state for all active (window, user) groups behind the scenes. Every new event updates the relevant group. Every trigger emits changed rows.</p><h3>Why approx_count_distinct() instead of exact distinct?</h3><p>Because exact distinct counts are expensive in stateful streaming.</p><p>approx_count_distinct() uses HyperLogLog-style estimation under the hood:</p><ul><li>bounded memory</li><li>fast updates</li><li>low error</li></ul><p>For operational dashboards, that tradeoff is usually right.</p><h3>Per-item and global aggregates</h3><p>The next two functions are the same shape with different grouping keys:</p><pre>def build_item_aggregates(events: DataFrame, window_duration: str, watermark: str) -&gt; DataFrame:<br>    return (<br>        events.withWatermark(&quot;event_ts&quot;, watermark)<br>        .groupBy(F.window(&quot;event_ts&quot;, window_duration), &quot;item_id&quot;)<br>        .agg(<br>            F.count(&quot;*&quot;).alias(&quot;interaction_count&quot;),<br>            F.approx_count_distinct(&quot;user_id&quot;).alias(&quot;unique_users&quot;),<br>            F.sum(F.when(F.col(&quot;interaction_type&quot;) == &quot;view&quot;, 1).otherwise(0)).alias(&quot;views&quot;),<br>            F.sum(F.when(F.col(&quot;interaction_type&quot;) == &quot;click&quot;, 1).otherwise(0)).alias(&quot;clicks&quot;),<br>            F.sum(F.when(F.col(&quot;interaction_type&quot;) == &quot;purchase&quot;, 1).otherwise(0)).alias(&quot;purchases&quot;),<br>            F.sum(F.when(F.col(&quot;interaction_type&quot;) == &quot;add_to_cart&quot;, 1).otherwise(0)).alias(&quot;add_to_carts&quot;),<br>        )<br>    )</pre><pre>def build_global_aggregates(events: DataFrame, window_duration: str, watermark: str) -&gt; DataFrame:<br>    return (<br>        events.withWatermark(&quot;event_ts&quot;, watermark)<br>        .groupBy(F.window(&quot;event_ts&quot;, window_duration))<br>        .agg(<br>            F.count(&quot;*&quot;).alias(&quot;total_events&quot;),<br>            F.approx_count_distinct(&quot;user_id&quot;).alias(&quot;unique_users&quot;),<br>            F.approx_count_distinct(&quot;item_id&quot;).alias(&quot;unique_items&quot;),<br>            F.sum(F.when(F.col(&quot;interaction_type&quot;) == &quot;view&quot;, 1).otherwise(0)).alias(&quot;views&quot;),<br>            F.sum(F.when(F.col(&quot;interaction_type&quot;) == &quot;click&quot;, 1).otherwise(0)).alias(&quot;clicks&quot;),<br>            F.sum(F.when(F.col(&quot;interaction_type&quot;) == &quot;purchase&quot;, 1).otherwise(0)).alias(&quot;purchases&quot;),<br>            F.sum(F.when(F.col(&quot;interaction_type&quot;) == &quot;add_to_cart&quot;, 1).otherwise(0)).alias(&quot;add_to_carts&quot;),<br>        )<br>        .withColumn(&quot;avg_interactions_per_user&quot;, F.col(&quot;total_events&quot;) / F.col(&quot;unique_users&quot;))<br>    )</pre><p>Now you have three materialized views of the same stream:</p><ul><li>user-level behavior</li><li>item-level behavior</li><li>global system health</li></ul><p>That’s the Bronze → Silver → Gold mental model from data warehousing, just expressed continuously instead of in batches.</p><h3>File 4 — consumer/sinks/elasticsearch_sink.py (replay safety happens here)</h3><p>This file is much more important than it looks. It decides whether retries and replays create duplicates or safe overwrites.</p><pre>from __future__ import annotations<br>from datetime import datetime, timezone<br>from elasticsearch import Elasticsearch, helpers<br>from pyspark.sql import DataFrame<br>from consumer.alerting import send_slack_alert<br><br>def _window_day(value) -&gt; str:<br>    if isinstance(value, datetime):<br>        return value.astimezone(timezone.utc).strftime(&quot;%Y-%m-%d&quot;)<br>    return datetime.now(timezone.utc).strftime(&quot;%Y-%m-%d&quot;)</pre><p>The helper computes the date suffix for daily Elasticsearch indices such as:</p><ul><li>user_aggregates_2026-05-01</li><li>item_aggregates_2026-05-01</li><li>global_metrics_2026-05-01</li></ul><p>Now the sink itself:</p><pre>class ElasticsearchSink:<br>    def __init__(self, es_host: str, batch_size: int, alert_threshold: int, alert_webhook_url: str) -&gt; None:<br>        self.es = Elasticsearch(es_host)<br>        self.batch_size = batch_size<br>        self.alert_threshold = alert_threshold<br>        self.alert_webhook_url = alert_webhook_url<br><br>    def write_batch(self, kind: str, df: DataFrame, entity_field: str | None = None) -&gt; None:<br>            rows = df.collect()<br>            if not rows:<br>                return<br>            actions = []<br>            alerts = []<br>            for row in rows:<br>                payload = row.asDict(recursive=True)<br>                window_start = payload[&quot;window_start&quot;]<br>                index_name = f&quot;{kind}_{_window_day(window_start)}&quot;<br>                entity_id = payload.get(entity_field, kind) if entity_field else kind<br>                doc_id = f&quot;{entity_id}_{int(window_start.timestamp())}&quot;<br>                actions.append({&quot;_index&quot;: index_name, &quot;_id&quot;: doc_id, &quot;_source&quot;: payload})</pre><p>The critical line is:</p><pre>doc_id = f&quot;{entity_id}_{int(window_start.timestamp())}&quot;</pre><p>That is the replay-safety trick.</p><p>For a given entity and window start, the document ID is deterministic.</p><p>So if Spark reprocesses the same window because:</p><ul><li>the job restarted</li><li>the batch retried</li><li>you intentionally replayed the topic</li></ul><p>Elasticsearch doesn’t get duplicates. The same document is overwritten.</p><p>That is not full end-to-end transactional exactly-once across Kafka, Spark, and Elasticsearch.</p><p>But it <strong>is</strong> practical idempotence, which is what most real pipelines rely on.</p><h3>Bulk write and alerting</h3><p>The rest of the file does two things:</p><pre>helpers.bulk(self.es, actions, chunk_size=self.batch_size, refresh=False)</pre><p>Use Elasticsearch bulk writes, not one document at a time. This is the sink equivalent of producer batching.</p><p>And then:</p><pre>if kind == &quot;item_aggregates&quot; and payload.get(&quot;interaction_count&quot;, 0) &gt;= self.alert_threshold:<br>    alerts.append(payload)</pre><p>Later each alert gets indexed and optionally sent to Slack:</p><pre>self.es.index(index=f&quot;alerts_{_window_day(alert[&#39;window_start&#39;])}&quot;, document=alert_doc)<br>send_slack_alert(<br>    self.alert_webhook_url,<br>    {&quot;text&quot;: f&quot;Alert: {alert[&#39;item_id&#39;]} crossed threshold with {alert[&#39;interaction_count&#39;]} events.&quot;},<br>)</pre><p>This is a nice pattern for small systems:</p><ul><li>the main metric stream lands in serving indices</li><li>alert-worthy rows are forked into a dedicated alert index</li><li>an optional webhook turns them into notifications</li></ul><p>You don’t need a separate stream processor just to demonstrate alerting logic.</p><h3>File 5 — consumer/alerting.py (tiny, but correct)</h3><pre>from __future__ import annotations<br>import logging<br>import requests<br><br>LOGGER = logging.getLogger(__name__)<br><br>def send_slack_alert(webhook_url: str, payload: dict[str, object]) -&gt; None:<br>    if not webhook_url:<br>        return<br>    response = requests.post(webhook_url, json=payload, timeout=5)<br>    response.raise_for_status()<br>    LOGGER.info(&quot;Alert sent for %s&quot;, payload.get(&quot;item_id&quot;))</pre><p>This is intentionally minimal:</p><ul><li>no webhook configured → do nothing</li><li>webhook configured → post JSON with a timeout</li><li>non-200 response → fail loudly</li></ul><p>That’s the right default for a small, explicit project.</p><h3>File 6 — consumer/main.py (the whole streaming job)</h3><p>Now the full wiring:</p><pre>from __future__ import annotations<br>from pyspark.sql import SparkSession<br>from pyspark.sql import functions as F<br>from consumer.aggregations import (<br>    build_global_aggregates,<br>    build_item_aggregates,<br>    build_user_aggregates,<br>    normalize_events,<br>)<br>from consumer.config import ConsumerSettings<br>from consumer.schemas import INTERACTION_SCHEMA<br>from consumer.sinks.elasticsearch_sink import ElasticsearchSink</pre><h3>Spark session setup</h3><pre>def create_spark_session(settings: ConsumerSettings) -&gt; SparkSession:<br>    return (<br>        SparkSession.builder.appName(&quot;avrioc-streaming&quot;)<br>        .config(&quot;spark.sql.shuffle.partitions&quot;, settings.spark_shuffle_partitions)<br>        .config(&quot;spark.sql.streaming.forceDeleteTempCheckpointLocation&quot;, &quot;true&quot;)<br>        .config(&quot;spark.jars.packages&quot;, &quot;org.apache.spark:spark-sql-kafka-0-10_2.12:3.5.1&quot;)<br>        .getOrCreate()<br>    )</pre><p>Three things matter here:</p><ol><li>spark.sql.shuffle.partitions</li><li>This controls parallelism after the groupBy and window operations.</li><li>spark-sql-kafka-0-10</li><li>This is the connector that lets Spark read Kafka directly.</li><li>forceDeleteTempCheckpointLocation</li><li>Useful for local/demo environments where temporary checkpoint cleanup would otherwise be annoying.</li></ol><h3>Reading from Kafka</h3><pre>source = (<br>    spark.readStream.format(&quot;kafka&quot;)<br>    .option(&quot;kafka.bootstrap.servers&quot;, settings.kafka_bootstrap_servers)<br>    .option(&quot;subscribe&quot;, settings.kafka_topic)<br>    .option(&quot;startingOffsets&quot;, &quot;latest&quot;)<br>    .load()<br>)</pre><p>This gives you the raw Kafka stream as a DataFrame.</p><p>Two notable choices:</p><ul><li>.option(&quot;subscribe&quot;, settings.kafka_topic) subscribes by topic name</li><li>.option(&quot;startingOffsets&quot;, &quot;latest&quot;) means a fresh run starts from the head, not from history</li></ul><p>That second choice is right for an always-on live pipeline.</p><p>If you want a backfill or replay, you’d change the consumer group and use earliest.</p><h3>Parsing and normalization</h3><pre>parsed = (<br>    source.select(F.from_json(F.col(&quot;value&quot;).cast(&quot;string&quot;), INTERACTION_SCHEMA).alias(&quot;payload&quot;))<br>    .select(&quot;payload.*&quot;)<br>    .transform(normalize_events)<br>    .filter(F.col(&quot;event_ts&quot;).isNotNull())<br>)</pre><p>This is a very clean pipeline:</p><ul><li>Kafka value is bytes, so cast to string</li><li>parse JSON against INTERACTION_SCHEMA</li><li>explode the struct back into columns</li><li>derive event_ts</li><li>drop anything with an invalid timestamp</li></ul><p>Bad timestamps are one of the fastest ways to corrupt time-window logic. Filtering them here is the right call.</p><h3>Build the three aggregate streams</h3><pre>user_aggregates = build_user_aggregates(parsed, settings.spark_window_duration, settings.spark_watermark)<br>item_aggregates = build_item_aggregates(parsed, settings.spark_window_duration, settings.spark_watermark)<br>global_aggregates = build_global_aggregates(parsed, settings.spark_window_duration, settings.spark_watermark)</pre><p>This is where one raw stream becomes three serving tables.</p><h3>Start the queries</h3><pre>queries = [<br>    user_aggregates.writeStream.outputMode(&quot;update&quot;)<br>    .trigger(processingTime=settings.spark_trigger_interval)<br>    .foreachBatch(lambda df, _: sink.write_batch(&quot;user_aggregates&quot;, df, &quot;user_id&quot;))<br>    .option(&quot;checkpointLocation&quot;, &quot;/checkpoints/user&quot;)<br>    .start(),</pre><p>The same pattern repeats for item and global metrics.</p><p>This deserves careful reading.</p><h4>outputMode(&quot;update&quot;)</h4><p>Spark can emit:</p><ul><li>append — only final new rows</li><li>complete — rewrite the whole result table every trigger</li><li>update — emit only rows that changed</li></ul><p>For rolling aggregates, update is the right middle ground. You don&#39;t want to rewrite everything every 30 seconds.</p><h4>trigger(processingTime=&quot;30 seconds&quot;)</h4><p>This is micro-batching: every 30 seconds Spark processes whatever arrived since the last trigger and pushes updates to Elasticsearch.</p><h4>foreachBatch(...)</h4><p>Instead of using Spark’s built-in Elasticsearch connector, the repo writes with a custom sink per batch.</p><p>This is useful because:</p><ul><li>you control document IDs</li><li>you control alert side effects</li><li>you can keep sink logic explicit and testable</li></ul><h4>checkpointLocation</h4><pre>.option(&quot;checkpointLocation&quot;, &quot;/checkpoints/user&quot;)</pre><p>This is the crash-recovery anchor.</p><p>Spark writes:</p><ul><li>source progress</li><li>state-store metadata</li><li>enough execution state to resume correctly</li></ul><p>The repo mounts /checkpoints from Docker Compose onto the host so those files survive container restarts.</p><p>Without persistent checkpoints, restarting the consumer is basically starting over.</p><h3>Why this design works</h3><p>The consumer is simple for a reason.</p><p>It makes three very good tradeoffs:</p><h3>1. Event time + watermarking over naive arrival-time counting</h3><p>This keeps your aggregates semantically correct when events arrive late.</p><h3>2. Deterministic sink IDs over “hope retries don’t duplicate”</h3><p>This makes replay safe in practice.</p><h3>3. Three focused aggregates over one giant denormalized sink</h3><p>This makes Kibana and downstream querying straightforward.</p><p>The overall data path is:</p><pre>Kafka bytes<br>  -&gt; JSON parse<br>  -&gt; typed event timestamps<br>  -&gt; watermarked windows<br>  -&gt; user/item/global aggregate tables<br>  -&gt; Elasticsearch indices<br>  -&gt; optional alerts</pre><p>That’s a real streaming pipeline, not a toy consumer loop.</p><h3>Run it and verify it</h3><p>Bring the stack up:</p><pre>docker compose up -d<br>docker compose logs -f consumer</pre><p>Then run the smoke check from the repo:</p><pre>python scripts/smoke_check.py</pre><p>The script checks that these index families exist and have data:</p><ul><li>user_aggregates_*</li><li>item_aggregates_*</li><li>global_metrics_*</li></ul><p>That is a much better signal than “the Spark process is alive.”</p><h3>What I learned in Part 3</h3><ul><li>Structured Streaming is the cleanest way to express Kafka → windowed aggregates when the target stack is Spark/Databricks.</li><li>Event time is not optional. Processing time gives you wrong answers as soon as messages arrive late.</li><li>Watermarks are how you bound state without giving up reasonable lateness tolerance.</li><li>update mode is the right sink mode for rolling aggregates.</li><li>Checkpoints are not an optimization. They are the difference between recovery and reprocessing chaos.</li><li>Deterministic document IDs give you practical idempotence in Elasticsearch.</li><li>approx_count_distinct() is one of the best streaming tradeoffs you can make for dashboard metrics.</li></ul><h3>What’s next</h3><p>In Part 4 we leave local Docker behind and talk about the production path:</p><ul><li>how the exact same code gets deployed with env vars</li><li>what the Kubernetes manifests do and don’t solve</li><li>how to reason about scaling</li><li>what replay safety really means</li><li>which production gaps were intentionally left out of this repo</li></ul><p><em>Tags: #Kafka #ApacheSpark #StructuredStreaming #DataEngineering #Elasticsearch</em></p><p><em>Previous:</em><a href="https://medium.com/@hiteshkhk0105/part-2-building-a-kafka-producer-that-pushes-40-000-events-sec-from-a-laptop-77ee253916a2"><em> Part 2 — Producer at scale</em></a><em> ·</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5abe76d39efb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Part 2: Building a Kafka Producer That Pushes 40,000 Events/Sec From a Laptop]]></title>
            <link>https://medium.com/@hiteshkhk0105/part-2-building-a-kafka-producer-that-pushes-40-000-events-sec-from-a-laptop-77ee253916a2?source=rss-cd5a029c558f------2</link>
            <guid isPermaLink="false">https://medium.com/p/77ee253916a2</guid>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kafka]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Hitesh]]></dc:creator>
            <pubDate>Wed, 27 May 2026 14:15:26 GMT</pubDate>
            <atom:updated>2026-05-27T14:15:26.980Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Part 2 of 4 in the “</em><strong><em>Learn Kafka in 4 Hours</em></strong><em>” series. We pick up where </em><a href="https://medium.com/@hiteshkhk0105/stop-using-kafka-like-a-slow-database-how-i-hit-40-000-eps-on-a-laptop-15e1aab7eada"><em>Part 1</em></a><em> left off Kafka is running in Docker, the topic exists, we proved it with the CLI. Now we replace the CLI with a production-grade Python producer.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YmDBKrBTk7R3kfib5vAkvg.jpeg" /></figure><h3>The four files we’ll write</h3><pre>producer/<br>├── generator.py        # synthesizes events with Zipf-distributed keys<br>├── rate_limiter.py     # token bucket for precise rate control<br>├── producer.py         # confluent-kafka wrapper, librdkafka tuning<br>├── main.py             # multiprocess fan-out, the actual entry point<br>└── config.py           # env-driven defaults</pre><p>By the end of this article, python -m producer.main --workers 8 --rate 5000 will push 40,000 events per second to Kafka. We&#39;ll explain every line.</p><p>Dependencies (producer/requirements.txt):</p><pre>confluent-kafka==2.5.3<br>faker==25.9.2<br>numpy==1.26.4</pre><p>Three packages. That’s it. confluent-kafka wraps librdkafka, the C library that&#39;s the fastest Python Kafka client by a wide margin.</p><h3>File 1 — producer/config.py (settings as env vars)</h3><p>Always start with config. If your code is going to run in Docker, in K8s, on someone else’s laptop — every knob needs to be an env var with a sane default.</p><pre>from __future__ import annotations<br>import os<br>from dataclasses import dataclass<br>@dataclass(slots=True)<br>class ProducerSettings:<br>    bootstrap_servers: str = os.getenv(&quot;KAFKA_BOOTSTRAP_SERVERS&quot;, &quot;localhost:9092&quot;)<br>    topic: str = os.getenv(&quot;KAFKA_TOPIC&quot;, &quot;interactions&quot;)<br>    rate_per_worker: int = int(os.getenv(&quot;PRODUCER_RATE_PER_WORKER&quot;, &quot;250&quot;))<br>    workers: int = int(os.getenv(&quot;PRODUCER_NUM_WORKERS&quot;, &quot;2&quot;))<br>    num_users: int = int(os.getenv(&quot;PRODUCER_NUM_USERS&quot;, &quot;5000&quot;))<br>    num_items: int = int(os.getenv(&quot;PRODUCER_NUM_ITEMS&quot;, &quot;1000&quot;))<br>    zipf_alpha: float = float(os.getenv(&quot;PRODUCER_ZIPF_ALPHA&quot;, &quot;1.2&quot;))<br>    duration_seconds: int = int(os.getenv(&quot;PRODUCER_DURATION_SECONDS&quot;, &quot;0&quot;))<br></pre><p>@dataclass(slots=True) because we want a tight, immutable settings object. slots=True is Python 3.10+ — it makes attribute access faster and prevents accidental field additions.</p><p>Every field has both a type and a default. This is your contract. When someone runs the container in K8s, they set PRODUCER_RATE_PER_WORKER=2000 in the ConfigMap and they&#39;re done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vpKoo_IcCU-tjEeExyacTA.jpeg" /></figure><h3>File 2 — producer/generator.py (the most important file)</h3><p>The generator is what makes this project a <em>realistic</em> simulator instead of a toy. If you generate IDs uniformly at random, every consumer test will show perfectly balanced partitions, and you’ll be shocked when production traffic creates hot keys.</p><p>The fix: Zipf distribution. A few users do most of the activity. Most users do almost nothing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGegFZfKhNVWrvKYu_3Aow.jpeg" /></figure><pre>from __future__ import annotations<br>import random<br>import uuid<br>from dataclasses import dataclass<br>from datetime import datetime, timezone<br>import numpy as np<br>from faker import Faker<br>INTERACTION_TYPES = (&quot;view&quot;, &quot;click&quot;, &quot;purchase&quot;, &quot;add_to_cart&quot;)<br>INTERACTION_WEIGHTS = (0.70, 0.25, 0.04, 0.01)<br>PLATFORMS = (&quot;web&quot;, &quot;ios&quot;, &quot;android&quot;)<br><br>@dataclass(slots=True)<br>class GeneratorConfig:<br>    num_users: int<br>    num_items: int<br>    zipf_alpha: float = 1.2<br>    seed: int = 42<br><br>class EventGenerator:<br>    def __init__(self, config: GeneratorConfig) -&gt; None:<br>        self.config = config<br>        self._faker = Faker()<br>        self._random = random.Random(config.seed)<br>        self._rng = np.random.default_rng(config.seed)<br>    def _zipf_id(self, prefix: str, upper_bound: int) -&gt; str:<br>        while True:<br>            value = int(self._rng.zipf(self.config.zipf_alpha))<br>            if value &lt;= upper_bound:<br>                return f&quot;{prefix}_{value}&quot;<br>    def build_event(self) -&gt; dict[str, object]:<br>        user_id = self._zipf_id(&quot;user&quot;, self.config.num_users)<br>        item_id = self._zipf_id(&quot;item&quot;, self.config.num_items)<br>        interaction_type = self._random.choices(<br>            INTERACTION_TYPES, weights=INTERACTION_WEIGHTS, k=1<br>        )[0]<br>        session_id = f&quot;session_{self._faker.uuid4()[:12]}&quot;<br>        return {<br>            &quot;event_id&quot;: str(uuid.uuid4()),<br>            &quot;user_id&quot;: user_id,<br>            &quot;item_id&quot;: item_id,<br>            &quot;interaction_type&quot;: interaction_type,<br>            &quot;timestamp&quot;: datetime.now(timezone.utc).isoformat(),<br>            &quot;session_id&quot;: session_id,<br>            &quot;platform&quot;: self._random.choice(PLATFORMS),<br>            &quot;metadata&quot;: {<br>                &quot;country&quot;: self._faker.country_code(),<br>                &quot;device_family&quot;: self._random.choice((&quot;mobile&quot;, &quot;desktop&quot;, &quot;tablet&quot;)),<br>                &quot;campaign&quot;: self._random.choice((&quot;organic&quot;, &quot;promo&quot;, &quot;referral&quot;)),<br>            },<br>        }</pre><p>Five Things to notice here:</p><ol><li><strong>INTERACTION_WEIGHTS = (0.70, 0.25, 0.04, 0.01)</strong> — this is the e-commerce funnel. 70% views, 25% clicks, 4% adds-to-cart, 1% purchases. If you have data from your own product, plug those numbers in instead. The point is: don&#39;t generate uniform random interaction types unless your domain actually is uniform.</li></ol><p><strong>2. </strong><strong>np.random.default_rng(config.seed)</strong> — NumPy&#39;s modern RNG, vectorized and fast. Each worker gets its own seed (we&#39;ll see this in main.py) so the workers produce different streams without coordination.</p><p><strong>3. The </strong><strong>_zipf_id rejection sampling loop</strong> — np.random.zipf(α) returns integers from a Zipf distribution which has no upper bound (in theory the value can be huge). We re-sample until it falls inside our population cap. With α=1.2 and a cap of 5000, this rejects maybe 5% of draws — cheap.</p><p><strong>4. Why Zipf matters</strong> — α=1.2 gives realistic skew. α=1.5 gives brutal skew where the top 10 users dominate. Use the higher α to stress-test your consumer’s hot-partition handling.</p><p><strong>5. </strong><strong>datetime.now(timezone.utc).isoformat()</strong> — always UTC, always ISO-8601. Spark needs to parse this back into a timestamp, and any other format will make you regret it.</p><h3>File 3 — producer/rate_limiter.py (smooth, not bursty)</h3><p>The naive way to limit rate is time.sleep(1.0 / target_rate) between calls. This works at low rates but is cumulatively wrong because your event-handling work takes nonzero time, and the sleep doesn&#39;t account for it. You always under-shoot the target.</p><p>The right way is a token bucket:</p><pre>from __future__ import annotations<br>import time<br>class TokenBucket:<br>    def __init__(self, refill_rate: float, bucket_size: float | None = None) -&gt; None:<br>        self.refill_rate = refill_rate<br>        self.bucket_size = bucket_size or refill_rate<br>        self.tokens = self.bucket_size<br>        self.updated_at = time.monotonic()<br>    def acquire(self, tokens: float = 1.0) -&gt; None:<br>        while True:<br>            now = time.monotonic()<br>            elapsed = now - self.updated_at<br>            self.updated_at = now<br>            self.tokens = min(self.bucket_size, self.tokens + elapsed * self.refill_rate)<br>            if self.tokens &gt;= tokens:<br>                self.tokens -= tokens<br>                return<br>            missing = tokens - self.tokens<br>            time.sleep(missing / self.refill_rate)</pre><p><strong>How it works:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VDpuBkz1Y15aqOYxtDtVgg.jpeg" /></figure><ul><li>refill_rate is your target events per second. bucket_size is your burst tolerance — how many events you&#39;ll allow back-to-back if you&#39;ve been quiet. We default it equal to the rate (1 second of burst).</li><li>Every call to acquire() first refills the bucket based on real elapsed time. time.monotonic() is critical — it&#39;s immune to wall-clock changes (NTP adjustments, daylight saving, manual clock changes).</li><li>If we have enough tokens, take one and return. If we don’t, sleep exactly the time we need to refill.</li></ul><p><strong>Why it’s better than </strong><strong>sleep(1/rate):</strong></p><p>A token bucket gives you smooth, near-constant-bit-rate output, <em>and</em> lets you absorb short bursts. You hit your rate target precisely because every acquire() accounts for whatever the real clock did since last time.</p><h3>File 4 — producer/producer.py (the librdkafka wrapper)</h3><p>This is the file that decides whether you push 200 EPS or 40,000.</p><pre>from __future__ import annotations<br>import json<br>import logging<br>from confluent_kafka import Producer<br>LOGGER = logging.getLogger(__name__)<br><br>class KafkaEventProducer:<br>    def __init__(self, bootstrap_servers: str) -&gt; None:<br>        self._producer = Producer(<br>            {<br>                &quot;bootstrap.servers&quot;: bootstrap_servers,<br>                &quot;linger.ms&quot;: 10,<br>                &quot;batch.size&quot;: 32768,<br>                &quot;compression.type&quot;: &quot;lz4&quot;,<br>                &quot;acks&quot;: &quot;1&quot;,<br>                &quot;client.id&quot;: &quot;avrioc-producer&quot;,<br>            }<br>        )<br>    def produce(self, topic: str, key: str, payload: dict[str, object]) -&gt; None:<br>        self._producer.produce(<br>            topic=topic,<br>            key=key.encode(&quot;utf-8&quot;),<br>            value=json.dumps(payload).encode(&quot;utf-8&quot;),<br>            on_delivery=self._delivery_report,<br>        )<br>        self._producer.poll(0)<br>    def flush(self) -&gt; None:<br>        self._producer.flush()<br>    @staticmethod<br>    def _delivery_report(error, message) -&gt; None:<br>        if error is not None:<br>            LOGGER.error(&quot;Delivery failed for %s: %s&quot;, message.key(), error)</pre><p>Twenty-five lines. Let’s go through every config value.</p><h3>linger.ms = 10</h3><p>Wait up to 10ms to fill a batch before sending. The default is 0, which means “send immediately.” Setting it to 10ms costs you 10ms of latency and gains you a 10–50× throughput multiplier because you’re sending fewer, larger network requests. For most use cases this is the single biggest win.</p><h3>batch.size = 32768</h3><p>32KB. The producer fills a per-partition buffer up to this size, then sends. With JSON events around 500 bytes each, that’s ~60 events per batch. Combined with linger.ms, you get either a full batch in 10ms or whatever accumulated in 10ms — whichever happens first.</p><h3>compression.type = &quot;lz4&quot;</h3><p>LZ4 is the fastest compression algorithm (~500 MB/s on a single core) and reduces JSON by 3–5×. The CPU cost is invisible compared to the network bytes saved.</p><p>Other options: gzip (slower, slightly higher ratio), snappy (similar speed to LZ4), zstd (best ratio, slightly slower). LZ4 is the right default unless you have a specific reason.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Wsl4aDy5677xcjSJfk-VQ.jpeg" /></figure><h3>acks = &quot;1&quot;</h3><p>This is the durability dial. Three settings:</p><ul><li>acks=0 — fire and forget. The producer doesn&#39;t wait for any acknowledgement. Fastest. Loses data if the broker is down.</li><li>acks=1 — leader-only ack. The producer waits for the partition leader to write the message. Loses data if the leader dies before replicating to followers.</li><li>acks=all — every in-sync replica acks. Slowest. Survives any single broker failure.</li></ul><p>We use 1 because this is a telemetry simulator losing a few thousand synthetic events on broker failover is fine. For payments, audit logs, anything you can&#39;t reconstruct, use all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*asKgamCmWskmRLX4tEQY3Q.jpeg" /></figure><h3>produce() is non-blocking</h3><p>The most surprising thing about librdkafka: producer.produce() doesn&#39;t actually send. It enqueues the message into an in-memory buffer that a background C thread drains. producer.poll(0) services delivery callbacks (success/failure notifications) without waiting.</p><p>This is why you must call flush() before exit. Otherwise messages sitting in the in-memory buffer are silently lost when the process dies.</p><h3>Why key=user_id?</h3><p>Same key → same partition → ordered. The consumer can build per-user state in parallel. We talked about this in Part 1 — this is where it gets implemented.</p><h3>File 5 — producer/main.py (multiprocess fan-out)</h3><p>Single Python process maxes out at maybe 5–10k EPS due to the GIL. To go higher you need multiple processes, each with their own Python interpreter and their own librdkafka instance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKzO_t-xooUDyiD521VNbA.jpeg" /></figure><pre>from __future__ import annotations<br>import argparse<br>import logging<br>import multiprocessing as mp<br>import time<br>from producer.config import ProducerSettings<br>from producer.generator import EventGenerator, GeneratorConfig<br>from producer.producer import KafkaEventProducer<br>from producer.rate_limiter import TokenBucket<br><br>logging.basicConfig(level=logging.INFO, format=&quot;%(asctime)s %(levelname)s %(name)s %(message)s&quot;)<br>LOGGER = logging.getLogger(__name__)<br><br>def worker_main(worker_id: int, settings: ProducerSettings) -&gt; None:<br>    generator = EventGenerator(<br>        GeneratorConfig(<br>            num_users=settings.num_users,<br>            num_items=settings.num_items,<br>            zipf_alpha=settings.zipf_alpha,<br>            seed=42 + worker_id,<br>        )<br>    )<br>    limiter = TokenBucket(refill_rate=settings.rate_per_worker)<br>    producer = KafkaEventProducer(settings.bootstrap_servers)<br>    deadline = time.monotonic() + settings.duration_seconds if settings.duration_seconds &gt; 0 else None<br>    emitted = 0<br>    try:<br>        while deadline is None or time.monotonic() &lt; deadline:<br>            limiter.acquire()<br>            event = generator.build_event()<br>            producer.produce(settings.topic, str(event[&quot;user_id&quot;]), event)<br>            emitted += 1<br>            if emitted % 1000 == 0:<br>                LOGGER.info(&quot;worker=%s emitted=%s&quot;, worker_id, emitted)<br>    finally:<br>        producer.flush()<br><br>def parse_args() -&gt; argparse.Namespace:<br>    defaults = ProducerSettings()<br>    parser = argparse.ArgumentParser(description=&quot;Emit interaction events into Kafka.&quot;)<br>    parser.add_argument(&quot;--rate&quot;, type=int, default=defaults.rate_per_worker)<br>    parser.add_argument(&quot;--workers&quot;, type=int, default=defaults.workers)<br>    parser.add_argument(&quot;--duration&quot;, type=int, default=defaults.duration_seconds)<br>    parser.add_argument(&quot;--num-users&quot;, type=int, default=defaults.num_users)<br>    parser.add_argument(&quot;--num-items&quot;, type=int, default=defaults.num_items)<br>    parser.add_argument(&quot;--zipf-alpha&quot;, type=float, default=defaults.zipf_alpha)<br>    return parser.parse_args()<br><br>def main() -&gt; int:<br>    args = parse_args()<br>    settings = ProducerSettings(<br>        rate_per_worker=args.rate,<br>        workers=args.workers,<br>        duration_seconds=args.duration,<br>        num_users=args.num_users,<br>        num_items=args.num_items,<br>        zipf_alpha=args.zipf_alpha,<br>    )<br>    processes = [mp.Process(target=worker_main, args=(worker_id, settings)) for worker_id in range(settings.workers)]<br>    for process in processes:<br>        process.start()<br>    for process in processes:<br>        process.join()<br>    return 0<br><br>if __name__ == &quot;__main__&quot;:<br>    raise SystemExit(main())</pre><p>The shape of this file matters. Let’s go through it:</p><p><strong>worker_main is the per-process loop.</strong> Each worker creates its own EventGenerator, TokenBucket, and KafkaEventProducer. No shared state, no locks. The seed=42 + worker_id ensures workers produce different streams (deterministic but distinct).</p><p><strong>The loop is small on purpose.</strong> limiter.acquire() → generator.build_event() → producer.produce(). Three lines. Every line of fluff in here costs you throughput.</p><p><strong>The </strong><strong>try/finally with </strong><strong>producer.flush()</strong> drains the in-memory buffer on exit. Without this you lose the last second or two of events on shutdown.</p><p><strong>mp.Process, not </strong><strong>Thread.</strong> Threads in Python share the GIL, which means only one thread runs Python bytecode at a time. For CPU-bound work like JSON serialization and Zipf sampling, this is a hard ceiling. Processes get their own interpreter and their own GIL.</p><p><strong>Both CLI args and env vars work.</strong> The CLI overrides env defaults. This means the same image works in dev (CLI flags), in Compose (env_file), and in K8s (ConfigMap). No code changes between environments.</p><h3>File 6 — producer/Dockerfile</h3><pre>FROM python:3.11-slim<br>WORKDIR /app<br>COPY producer/requirements.txt /tmp/requirements.txt<br>RUN pip install --no-cache-dir -r /tmp/requirements.txt<br>COPY producer /app/producer<br>CMD [&quot;python&quot;, &quot;-m&quot;, &quot;producer.main&quot;]</pre><p>Six lines. Slim base image. Install requirements first (so COPY producer doesn&#39;t bust the layer cache when source changes). Run as a module so relative imports work.</p><p>In docker-compose.yml:</p><pre>producer:<br>  build:<br>    context: .<br>    dockerfile: producer/Dockerfile<br>  container_name: producer<br>  depends_on:<br>    kafka-init:<br>      condition: service_completed_successfully<br>  env_file:<br>    - .env</pre><p>depends_on: kafka-init: service_completed_successfully waits for the topic to exist before starting the producer. Without this, the first run dies because the topic doesn&#39;t exist yet.</p><h3>Run it</h3><pre>docker compose up -d<br>docker compose logs -f producer</pre><p>You’ll see worker=0 emitted=1000, worker=1 emitted=1000 lines.</p><p>To push harder:</p><pre>docker compose stop producer<br>docker compose run --rm producer python -m producer.main \<br>  --workers 8 --rate 5000 --duration 30 --zipf-alpha 1.5</pre><p>40,000 EPS for 30 seconds, with brutal Zipf skew so the consumer side has to deal with hot keys. That’s 1.2 million events into Kafka in half a minute, on a laptop, with five files of Python.</p><p>Verify it worked:</p><pre>docker exec kafka kafka-run-class kafka.tools.GetOffsetShell \<br>  --broker-list localhost:9092 --topic interactions</pre><p>You’ll see offsets across all 6 partitions, distributed unevenly because of the Zipf keys (which is exactly what we wanted).</p><h3>What I learned in Part 2</h3><ul><li>linger.ms=10 + batch.size=32768 is the single biggest throughput lever.</li><li>LZ4 compression is essentially free CPU-wise and saves 3–5× network bytes.</li><li>acks=1 is fine for telemetry. Use acks=all + enable.idempotence=true for anything you can&#39;t reconstruct.</li><li>librdkafka’s produce() is async. You must call flush() before exit.</li><li>Use multiprocessing, not threads, for Python producers. The GIL is real.</li><li>Keys decide partitions. Pick keys that match how your consumer wants to aggregate.</li><li>Token bucket beats sleep(1/rate) for smooth, accurate rate limiting.</li></ul><h3>What’s next</h3><p>Part 3 builds the consumer side. We’ll write a Spark Structured Streaming job that:</p><ul><li>Reads from Kafka and parses JSON against a strict schema.</li><li>Does event-time windowed aggregations with watermarks.</li><li>Writes per-user, per-item, and global aggregates to Elasticsearch.</li><li>Handles crashes via checkpoints with zero data loss.</li></ul><p><a href="https://medium.com/@hiteshkhk0105/stop-using-kafka-like-a-slow-database-how-i-hit-40-000-eps-on-a-laptop-15e1aab7eada">Read Part 1→</a></p><p><em>Tags: #Kafka #DataEngineering #Python #BackendEngineering #DistributedSystems</em></p><p><em>Previous: </em><a href="https://medium.com/@hiteshkhk0105/stop-using-kafka-like-a-slow-database-how-i-hit-40-000-eps-on-a-laptop-15e1aab7eada"><em>Part 1 — The mental model</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77ee253916a2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stop Using Kafka Like a Slow Database: How I Hit 40,000 EPS on a Laptop]]></title>
            <link>https://medium.com/@hiteshkhk0105/stop-using-kafka-like-a-slow-database-how-i-hit-40-000-eps-on-a-laptop-15e1aab7eada?source=rss-cd5a029c558f------2</link>
            <guid isPermaLink="false">https://medium.com/p/15e1aab7eada</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[real-time-analytics]]></category>
            <category><![CDATA[apache-kafka]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[kafka]]></category>
            <dc:creator><![CDATA[Hitesh]]></dc:creator>
            <pubDate>Thu, 21 May 2026 15:06:07 GMT</pubDate>
            <atom:updated>2026-05-21T15:06:07.913Z</atom:updated>
            <content:encoded><![CDATA[<p><em>We’ll build a complete event-streaming pipeline <br> </em><strong><em>generator → Kafka → Spark → Elasticsearch → Kibana</em></strong></p><p><em>with every line of code and every config decision explained. By the end of Part 4 you’ll have a repo that pushes 40,000 events/sec on a laptop.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ncfC2t0ETTAL5S6LGO5Ngw.png" /></figure><p><em>All code in this series is on GitHub: Kafka-learn (will share the </em><strong><em>link</em></strong><em> in part-2 once we build the 40,000EPS producer ).</em></p><h3>The problem I was trying to solve</h3><p>I had to learn kafka fast! and have the depth to answer all the questions that might come in any interview about real-time streaming</p><p><strong>Simple use-case</strong></p><p>Build a scalable event simulator that publishes to Kafka, runs real-time aggregations, and surfaces insights on a dashboard.” Four sentences.</p><p>Three weeks of cluster-config rabbit holes if you don’t know what you’re doing.</p><p>Three weekends later I had a working repo. This series is the version of the docs I wish I’d had on day one!</p><p>By the end of Part 4 you’ll be able to:</p><ol><li>Spin up a 5-component streaming stack with one command (docker compose up).</li><li>Push 40,000 synthetic events per second from a Python producer all from your laptop</li><li>Consume them in Spark Structured Streaming with event-time windowed aggregations. (we only build things that scale here!)</li><li>Land everything in Elasticsearch and visualize it in Kibana.</li><li>Explain every single tuning knob to any interviewer.</li></ol><p>Nothing in this series is paraphrased. Every code block is copied directly from the repo. If you want to follow along, clone the repo and cd into it now.</p><h3>Part 1’s job: Get the mental model right</h3><p>Most Kafka tutorials skip this and jump straight to producer.send(topic, msg). That&#39;s how people end up using <strong>Kafka as a slow database</strong>, or pushing one message at a time and getting <strong>200 events per second</strong>. (we want <em>40,000 events/sec</em>)</p><p>Before we write a single line of code, we need to agree on what Kafka actually is.</p><h3>Kafka is a postbox, not a queue</h3><p>Forget “distributed log” for a second. Forget RabbitMQ. Forget SQS.</p><p><strong>Kafka is a postbox</strong>. Producers drop letters in. The postbox keeps every letter, in order, for as long as you tell it to.</p><p>Consumers come pick up letters at their own pace, and they each remember where they stopped.</p><p>That’s the whole abstraction. Once you have that, every other Kafka concept is a tuning knob on top.</p><p>The two implications that surprised me most when I first internalized this:</p><p><strong>1. Letters stay around.</strong> A consumer can come back tomorrow and read everything from yesterday. This is why Kafka is called a “log” it’s append-only, retained by time or size, and any number of independent readers can replay it. This is fundamentally different from a queue, where reading deletes.</p><p><strong>2. Consumers are independent.</strong> Producer A doesn’t know about Consumer B. They can scale separately. They can fail separately. The postbox doesn’t care.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjZ5hiX4wgm8poAXs960Lw.jpeg" /></figure><h3>The 5 words you actually need</h3><p>These are the only Kafka terms you have to internalize. Everything else can be looked up.</p><p><strong>Topic</strong> — a named stream. In our project, it’s called interactions. A topic is created by name; producers write to it, consumers subscribe to it.</p><p><strong>Partition</strong> — a topic is split into N ordered logs called partitions. This is the unit of parallelism. If a topic has 6 partitions, up to 6 consumers can read it in parallel. We use 6 in this project.</p><p><strong>Broker</strong> — a Kafka server. One broker is enough for development (we run that). Production setups run 3 or more for replication and fault tolerance.</p><p><strong>Producer</strong> — code that writes events to a topic.</p><p><strong>Consumer</strong> — code that reads events from a topic.</p><p>That’s it. There are more terms (offsets, consumer groups, ISR, controller…) but they’re refinements of these five. We’ll meet them as needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hYlr1HsAh_yMXyBJsITRBg.jpeg" /></figure><h3>How partitions actually work — the part that always trips people up</h3><p>A topic isn’t literally a single ordered list. It’s N independent ordered lists called partitions. Order is guaranteed <em>within</em> a partition, not across partitions.</p><p>When a producer writes an event, Kafka has to decide which partition it goes to. Two strategies:</p><ol><li><strong>No key (round-robin)</strong> — events get spread evenly. Fastest, but you lose per-entity ordering.</li><li><strong>With a key</strong> — Kafka hashes the key, and the same key always lands on the same partition.</li></ol><p>This second one is the entire trick of Kafka. In our project, we key every event by user_id. That means:</p><ul><li>All events for user_42 land on the same partition.</li><li>They arrive at the consumer in the order they were produced.</li><li>The consumer can build per-user state in parallel — partition 0 handles its users, partition 1 handles its users, with no coordination needed.</li></ul><p>If you remember one thing from Part 1: <strong>keys decide partitions, partitions decide parallelism, parallelism decides scale.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dG6KS68_g-Ls-zJcmVyWjQ.jpeg" /></figure><h3>The stack we’re building</h3><p>Here’s what we’ll have running on docker compose up by the end of Part 4:</p><pre>+----------+     +-------+     +----------+     +---------------+     +--------+<br>| Producer | --&gt; | Kafka | --&gt; | Spark    | --&gt; | Elasticsearch | --&gt; | Kibana |<br>| (Python) |     |(KRaft)|     |(Streaming|     |  (aggregates) |     | (dash) |<br>+----------+     +-------+     +----------+     +---------------+     +--------+</pre><p>Five containers, defined in a single docker-compose.yml. Each one is independently scalable, replaceable, and fails independently.</p><p>Here’s the actual compose file’s Kafka definition — this is real, copy it:</p><pre>kafka:<br>  image: confluentinc/cp-kafka:7.6.1<br>  container_name: kafka<br>  ports:<br>    - &quot;9092:9092&quot;<br>  environment:<br>    KAFKA_NODE_ID: 1<br>    KAFKA_PROCESS_ROLES: broker,controller<br>    KAFKA_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://0.0.0.0:9092,CONTROLLER://kafka:29093<br>    KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092<br>    KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT,CONTROLLER:PLAINTEXT<br>    KAFKA_CONTROLLER_QUORUM_VOTERS: 1@kafka:29093<br>    KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER<br>    KAFKA_INTER_BROKER_LISTENER_NAME: PLAINTEXT<br>    KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1<br>    CLUSTER_ID: MkU3OEVBNTcwNTJENDM2Qk<br>  healthcheck:<br>    test: [&quot;CMD-SHELL&quot;, &quot;kafka-topics --bootstrap-server localhost:9092 --list &gt;/dev/null 2&gt;&amp;1&quot;]<br>    interval: 10s</pre><p>Three things to call out so you don’t get lost when you write your own:</p><ol><li><strong>KRaft mode</strong>, not ZooKeeper. KAFKA_PROCESS_ROLES: broker,controller makes one container play both roles. ZooKeeper is officially deprecated as of Kafka 4.0 — don&#39;t use it for new projects.</li><li><strong>Two listeners</strong>. PLAINTEXT://kafka:29092 is for other Docker containers (they reach Kafka through the docker network using the hostname kafka). PLAINTEXT_HOST://0.0.0.0:9092 is for your laptop (you reach Kafka through localhost:9092). Getting this wrong is the #1 reason &quot;I can produce from inside Docker but not outside&quot; tickets exist.</li><li><strong>Healthcheck</strong>. The init container that creates topics waits on this. Always wire healthchecks — without them, services race and fail in confusing ways.</li></ol><p>Topic creation runs as a one-shot init container:</p><pre>kafka-init:<br>  image: confluentinc/cp-kafka:7.6.1<br>  depends_on:<br>    kafka:<br>      condition: service_healthy<br>  entrypoint: [&quot;/bin/sh&quot;, &quot;-c&quot;]<br>  command:<br>    - &gt;<br>      kafka-topics --bootstrap-server kafka:29092 --create --if-not-exists<br>      --topic ${KAFKA_TOPIC:-interactions}<br>      --partitions ${KAFKA_NUM_PARTITIONS:-6}<br>      --replication-factor 1<br>  restart: &quot;no&quot;</pre><p>Notice --partitions 6. You should pick this number deliberately because <strong>you can grow partitions but not shrink them, and growing them re-keys everything</strong>. Pick high (6, 12, 24) for a future-proof topic, or pick the minimum that handles your read parallelism.</p><h3>Your first interaction with Kafka — produce one event by hand</h3><p>Before we write any Python, let’s prove the mental model with the CLI.</p><p>Spin up the stack:</p><pre>docker compose up -d kafka kafka-init</pre><p>In one terminal, start a console consumer:</p><pre>docker exec -it kafka kafka-console-consumer \<br>  --bootstrap-server localhost:9092 \<br>  --topic interactions \<br>  --from-beginning</pre><p>In another, produce a message:</p><pre>docker exec -it kafka kafka-console-producer \<br>  --bootstrap-server localhost:9092 \<br>  --topic interactions<br>&gt; {&quot;user_id&quot;: &quot;user_1&quot;, &quot;interaction_type&quot;: &quot;click&quot;}</pre><p>The consumer prints the line. That’s a Kafka pipeline. Two tools that ship in the broker image, no Python, no libraries.</p><p>Now stop the consumer (Ctrl-C), restart it, and produce another message. The consumer prints <strong>only the new one</strong> — because by default it tracks its position. Restart it with --from-beginning and it replays everything. <strong>That&#39;s the offset behavior at work, and it&#39;s the most underrated feature of Kafka.</strong></p><h3>What’s next</h3><p>In Part 2 we replace the manual CLI producer with a real Python producer that:</p><ul><li>Generates synthetic events with realistic Zipf-distributed user IDs.</li><li>Uses a token bucket to enforce a precise rate (e.g. 1000 EPS).</li><li>Spawns multiple processes for true parallelism.</li><li>Tunes librdkafka with batching, compression, and the right acks setting.</li></ul><p>We’ll go from 200 EPS to 40,000 EPS, line by line.</p><h3>Repo structure for the curious</h3><p>If you want to peek ahead, here’s the layout:</p><pre>.<br>├── docker-compose.yml          ← all 5 services<br>├── producer/<br>│   ├── generator.py            ← Zipf event synthesis<br>│   ├── producer.py             ← librdkafka wrapper<br>│   ├── rate_limiter.py         ← token bucket<br>│   ├── main.py                 ← multiprocess fan-out<br>│   ├── config.py               ← env-driven settings<br>│   └── Dockerfile<br>├── consumer/<br>│   ├── main.py                 ← Spark Structured Streaming<br>│   ├── aggregations.py         ← windowed reduce<br>│   ├── schemas.py              ← strict JSON schema<br>│   ├── sinks/elasticsearch_sink.py<br>│   ├── alerting.py<br>│   └── Dockerfile<br>├── dashboards/kibana_export.ndjson<br>├── k8s/                        ← Kubernetes manifests<br>├── scripts/                    ← smoke tests, dashboard provisioning<br>└── tests/                      ← pytest suite</pre><p>In Parts 2, 3, and 4 we’ll walk every file in producer/, consumer/, and the K8s manifests respectively.</p><h3>What I learned in Part 1</h3><ul><li>Kafka is a postbox, not a queue. Letters stay until retention expires; readers are independent.</li><li>Five words: topic, partition, broker, producer, consumer. Internalize these.</li><li>Keys decide partitions. Same key → same partition → ordered. This is the whole game.</li><li>KRaft mode (no ZooKeeper) is the default for new projects in 2026.</li><li>Listeners trip everyone up. Internal hostname for containers, localhost for the host machine.</li><li>You can grow partitions but not shrink them. Pick the count deliberately.</li></ul><p><em>Tags: #Kafka #DataEngineering #DistributedSystems #StreamingData #BackendEngineering</em></p><p><em>Next: Part 2 — Producing 40k events/sec from a laptop</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15e1aab7eada" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Real ETL Pipeline from Scratch with Lakeflow Declarative Pipelines]]></title>
            <link>https://medium.com/@hiteshkhk0105/build-a-real-etl-pipeline-from-scratch-with-lakeflow-declarative-pipelines-ae3aaabf7274?source=rss-cd5a029c558f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae3aaabf7274</guid>
            <category><![CDATA[etl]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[databricks-lakeflow]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Hitesh]]></dc:creator>
            <pubDate>Thu, 19 Mar 2026 07:47:07 GMT</pubDate>
            <atom:updated>2026-03-19T07:47:07.028Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Traditional Spark ETL buries you in orchestration boilerplate. Here’s how to describe what you want ! and let the framework handle the rest.</em></p><p>Before you go though this strongly suggest to skim through the Part-1 first!</p><p><a href="https://medium.com/@hiteshkhk0105/databricks-lakeflow-foundations-58579ab30068">DataBricks LakeFlow Foundations</a></p><p>Follow me on <a href="https://www.linkedin.com/in/h-kaushik/">linkedin</a> for more updates on the next article, let’s learn this together</p><blockquote><strong>What you’ll build:</strong> A complete ETL pipeline that ingests raw e-commerce data, cleans it, enforces quality rules, and produces analytics-ready tables all <strong>declaratively</strong>.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xub7Zf1VdozW3E3lQszO6Q.jpeg" /></figure><p>Traditional Spark ETL requires you to manually orchestrate execution order, handle retries, manage state, and write hundreds of lines of boilerplate.</p><p><strong>Lakeflow Declarative Pipelines (SDP)</strong> lets you <em>describe</em> <strong><em>what</em> you want</strong>, and the <strong>framework handles <em>how</em></strong>.</p><p>Befote that here are core concepts we will use in action, in this article</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nHduXKWziIAh7fceVawp3w.png" /></figure><h3>The architecture we’re building</h3><p>The pipeline follows the medallion pattern three tiers of increasing refinement, each serving a distinct purpose.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z1R8d4JnYT65ipkB2ZKAOA.png" /></figure><h3><strong><em>Step 0:</em></strong></h3><p><em>Setup Create Your Catalog and Schema</em></p><p>Before we write pipeline code, we need a home for our tables.</p><pre># -- Run this ONCE in a regular notebook or SQL editor before creating the pipeline --<br><br># Replace with your own catalog name<br>CATALOG = &quot;learn_lakeflow&quot;<br>SCHEMA  = &quot;ecommerce&quot;<br><br>spark.sql(f&quot;CREATE CATALOG IF NOT EXISTS {CATALOG}&quot;)<br>spark.sql(f&quot;USE CATALOG {CATALOG}&quot;)<br>spark.sql(f&quot;CREATE SCHEMA IF NOT EXISTS {SCHEMA}&quot;)<br>spark.sql(f&quot;USE SCHEMA {SCHEMA}&quot;)<br><br>print(f&quot;Ready: {CATALOG}.{SCHEMA}&quot;)</pre><h3><strong>Step 1:</strong></h3><p><strong><em>Generate Sample Data !</em></strong></p><p>We’ll create realistic e-commerce data and write it to a volume. <em>This simulates files landing in cloud storage from upstream systems.</em></p><p>Run this in a regular notebook first it creates the source files your pipeline will ingest.</p><pre><br>from pyspark.sql.types import *<br>from pyspark.sql.functions import *<br>from datetime import datetime, timedelta<br>import random<br><br># Create a volume to store our source files<br>spark.sql(f&quot;CREATE VOLUME IF NOT EXISTS {CATALOG}.{SCHEMA}.raw_files&quot;)<br><br>volume_path = f&quot;/Volumes/{CATALOG}/{SCHEMA}/raw_files&quot;<br><br></pre><p><strong>Orders data</strong> will be ingested as <strong>streaming table</strong></p><pre># ORDERS DATA (will be ingested as streaming table)<br><br>order_data = []<br>for i in range(1, 5001):<br>    order_data.append({<br>        &quot;order_id&quot;: f&quot;ORD-{i:06d}&quot;,<br>        &quot;customer_id&quot;: f&quot;CUST-{random.randint(1, 500):04d}&quot;,<br>        &quot;product_id&quot;: f&quot;PROD-{random.randint(1, 50):03d}&quot;,<br>        &quot;quantity&quot;: random.randint(1, 10),<br>        &quot;unit_price&quot;: round(random.uniform(9.99, 299.99), 2),<br>        &quot;order_status&quot;: random.choice([&quot;completed&quot;, &quot;pending&quot;, &quot;shipped&quot;, &quot;cancelled&quot;, &quot;returned&quot;]),<br>        &quot;order_date&quot;: (datetime(2024, 1, 1) + timedelta(days=random.randint(0, 365))).strftime(&quot;%Y-%m-%d&quot;),<br>        &quot;payment_method&quot;: random.choice([&quot;credit_card&quot;, &quot;debit_card&quot;, &quot;upi&quot;, &quot;wallet&quot;, &quot;cod&quot;]),<br>        &quot;shipping_city&quot;: random.choice([<br>            &quot;Mumbai&quot;, &quot;Delhi&quot;, &quot;Bangalore&quot;, &quot;Chennai&quot;, &quot;Hyderabad&quot;,<br>            &quot;Pune&quot;, &quot;Kolkata&quot;, &quot;Ahmedabad&quot;, &quot;Jaipur&quot;, &quot;Lucknow&quot;<br>        ])<br>    })<br><br>orders_df = spark.createDataFrame(order_data)<br><br># Write as CSV files (simulating file-based ingestion)<br>orders_df.coalesce(3).write.mode(&quot;overwrite&quot;).option(&quot;header&quot;, &quot;true&quot;).csv(f&quot;{volume_path}/orders/&quot;)<br><br>print(f&quot;Wrote {orders_df.count()} orders to {volume_path}/orders/&quot;)</pre><p><strong>CUSTOMERS DATA</strong> (will be ingested as <strong>streaming table</strong>)</p><pre>customer_data = []<br>for i in range(1, 501):<br>    customer_data.append({<br>        &quot;customer_id&quot;: f&quot;CUST-{i:04d}&quot;,<br>        &quot;customer_name&quot;: f&quot;Customer_{i}&quot;,<br>        &quot;email&quot;: f&quot;@example.com&quot;&gt;customer{i}@example.com&quot;,<br>        &quot;signup_date&quot;: (datetime(2022, 1, 1) + timedelta(days=random.randint(0, 730))).strftime(&quot;%Y-%m-%d&quot;),<br>        &quot;tier&quot;: random.choice([&quot;bronze&quot;, &quot;silver&quot;, &quot;gold&quot;, &quot;platinum&quot;]),<br>        &quot;city&quot;: random.choice([<br>            &quot;Mumbai&quot;, &quot;Delhi&quot;, &quot;Bangalore&quot;, &quot;Chennai&quot;, &quot;Hyderabad&quot;,<br>            &quot;Pune&quot;, &quot;Kolkata&quot;, &quot;Ahmedabad&quot;, &quot;Jaipur&quot;, &quot;Lucknow&quot;<br>        ]),<br>        &quot;is_active&quot;: random.choice([True, True, True, False])  # 75% active<br>    })<br><br>customers_df = spark.createDataFrame(customer_data)<br>customers_df.coalesce(1).write.mode(&quot;overwrite&quot;).option(&quot;header&quot;, &quot;true&quot;).csv(f&quot;{volume_path}/customers/&quot;)<br><br>print(f&quot;Wrote {customers_df.count()} customers to {volume_path}/customers/&quot;)</pre><p><strong>CUSTOMER CDC DATA</strong><em> (</em><strong><em>simulates change events</em></strong><em> from a source database)</em></p><pre>cdc_events = []<br>for i in range(1, 201):<br>    cust_id = f&quot;CUST-{random.randint(1, 500):04d}&quot;<br>    op = random.choice([&quot;INSERT&quot;, &quot;UPDATE&quot;, &quot;UPDATE&quot;, &quot;UPDATE&quot;, &quot;DELETE&quot;])<br>    cdc_events.append({<br>        &quot;cdc_timestamp&quot;: (datetime(2024, 6, 1) + timedelta(hours=random.randint(0, 4380))).strftime(&quot;%Y-%m-%d %H:%M:%S&quot;),<br>        &quot;operation&quot;: op,<br>        &quot;customer_id&quot;: cust_id,<br>        &quot;customer_name&quot;: f&quot;Customer_{cust_id.split(&#39;-&#39;)[1]}_v2&quot; if op == &quot;UPDATE&quot; else f&quot;Customer_{cust_id.split(&#39;-&#39;)[1]}&quot;,<br>        &quot;email&quot;: f&quot;updated_{cust_id.split(&#39;-&#39;)[1]}@example.com&quot; if op == &quot;UPDATE&quot; else f&quot;customer{cust_id.split(&#39;-&#39;)[1]}@example.com&quot;,<br>        &quot;tier&quot;: random.choice([&quot;bronze&quot;, &quot;silver&quot;, &quot;gold&quot;, &quot;platinum&quot;]),<br>        &quot;city&quot;: random.choice([&quot;Mumbai&quot;, &quot;Delhi&quot;, &quot;Bangalore&quot;, &quot;Chennai&quot;]),<br>        &quot;is_active&quot;: op != &quot;DELETE&quot;<br>    })<br><br>cdc_df = spark.createDataFrame(cdc_events)<br>cdc_df.coalesce(1).write.mode(&quot;overwrite&quot;).option(&quot;header&quot;, &quot;true&quot;).csv(f&quot;{volume_path}/customer_cdc/&quot;)<br><br>print(f&quot;Wrote {len(cdc_events)} CDC events to {volume_path}/customer_cdc/&quot;)<br>print(&quot;\nSource data is ready! Now let&#39;s build the pipeline.&quot;)</pre><h3>Step 2:</h3><p>THE <strong>PIPELINE CODE SETUP </strong>STARTS HERE</p><p>Everything below this line goes into your <strong>pipeline notebook</strong></p><p><em>When you create the pipeline in the Databricks UI:</em></p><ol><li><strong>Navigate to ETL Pipeline</strong></li></ol><p>From the Databricks home screen, click <strong>+ New</strong> and select <strong>ETL pipeline</strong> from the menu</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uejIJ0F4rQtdSdwfSt4F7w.jpeg" /></figure><p>2.<strong> Set catalog and schema</strong></p><p>The first thing the pipeline editor asks for is where your tables should live. Set <strong>catalog</strong> to learn_lakeflow and <strong>schema</strong> to ecommerce.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0yGVub78BsVDh_vNTb2f1w.jpeg" /><figcaption>Set catalog and schema</figcaption></figure><p><strong>3. Name your pipeline</strong></p><p>Give the pipeline a unique name. In this series we’ll use Pipeline_notebook as the container, then add our transformation files inside it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9Qs9dgOF-iH8ClVo411ebw.jpeg" /><figcaption>Name the pipeline as you like</figcaption></figure><p><strong>4. Choose Python as your language</strong></p><p>When prompted for a starting point, select <strong>Start with sample code in Python</strong>.</p><p>This gets us the folder structure with a transformations/ directory where your pipeline files will live.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HcSgV-Pmc6zfRnhX7CMieA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jBWg4o5PbmPfImjihRb-gQ.jpeg" /><figcaption>Transofrmations (and select python)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*opVhwbXRyKN1FKMnJl8Dgg.jpeg" /></figure><h3>Step 3:</h3><p>THE <strong>PIPELINE CODE </strong>STARTS HERE</p><h3>Configuration</h3><p>At the top of your first file (01_bronze.py), define the shared configuration:</p><pre>from pyspark import pipelines as sdp<br>from pyspark.sql.functions import *<br>from pyspark.sql.types import *<br><br>CATALOG     = &quot;learn_lakeflow&quot;<br>SCHEMA      = &quot;ecommerce&quot;<br>VOLUME_PATH = f&quot;/Volumes/{CATALOG}/{SCHEMA}/raw_files&quot;</pre><h3>Bronze layer — raw ingestion with streaming tables</h3><p><strong>Streaming Tables</strong> are append-only tables optimised for incremental ingestion. On first run they process all existing files; on every subsequent run they only pick up new files, tracked via checkpoint.</p><p><strong>Auto Loader</strong> (cloudFiles format) does the file-detection automatically no manual bookkeeping.</p><pre># --- BRONZE TABLE 1: Raw Orders ---<br>@sdp.table(<br>    comment=&quot;Raw e-commerce orders ingested from CSV files via Auto Loader.&quot;,<br>    table_properties={&quot;quality&quot;: &quot;bronze&quot;}<br>)<br>def bronze_orders():<br>    return (<br>        spark.readStream<br>        .format(&quot;cloudFiles&quot;)<br>        .option(&quot;cloudFiles.format&quot;, &quot;csv&quot;)<br>        .option(&quot;header&quot;, &quot;true&quot;)<br>        .option(&quot;cloudFiles.inferColumnTypes&quot;, &quot;true&quot;)<br>        .option(&quot;cloudFiles.schemaLocation&quot;, f&quot;{VOLUME_PATH}/_schemas/orders&quot;)<br>        .load(f&quot;{VOLUME_PATH}/orders/&quot;)<br>    )<br><br><br># --- BRONZE TABLE 2: Raw Customers ---<br>@sdp.table(<br>    comment=&quot;Raw customer profiles ingested from CSV files via Auto Loader.&quot;,<br>    table_properties={&quot;quality&quot;: &quot;bronze&quot;}<br>)<br>def bronze_customers():<br>    return (<br>        spark.readStream<br>        .format(&quot;cloudFiles&quot;)<br>        .option(&quot;cloudFiles.format&quot;, &quot;csv&quot;)<br>        .option(&quot;header&quot;, &quot;true&quot;)<br>        .option(&quot;cloudFiles.inferColumnTypes&quot;, &quot;true&quot;)<br>        .option(&quot;cloudFiles.schemaLocation&quot;, f&quot;{VOLUME_PATH}/_schemas/customers&quot;)<br>        .load(f&quot;{VOLUME_PATH}/customers/&quot;)<br>    )<br><br><br># --- BRONZE TABLE 3: Customer CDC Events ---<br>@sdp.table(<br>    comment=&quot;Change Data Capture events for customer records.&quot;,<br>    table_properties={&quot;quality&quot;: &quot;bronze&quot;}<br>)<br>def bronze_customer_cdc():<br>    return (<br>        spark.readStream<br>        .format(&quot;cloudFiles&quot;)<br>        .option(&quot;cloudFiles.format&quot;, &quot;csv&quot;)<br>        .option(&quot;header&quot;, &quot;true&quot;)<br>        .option(&quot;cloudFiles.inferColumnTypes&quot;, &quot;true&quot;)<br>        .option(&quot;cloudFiles.schemaLocation&quot;, f&quot;{VOLUME_PATH}/_schemas/customer_cdc&quot;)<br>        .load(f&quot;{VOLUME_PATH}/customer_cdc/&quot;)<br>    )</pre><p>Here’s what this looks like in the Lakeflow editor after pasting in the Bronze tables:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7CWBVcLnQsZGS7gquX4fpA.jpeg" /></figure><h3>Silver layer | cleaned, validated, enriched</h3><p>The Silver layer is where raw data gets shape. <strong>Materialized Views</strong> recompute on each refresh</p><p>(with incremental optimisation where possible), which makes them ideal for transformations, joins, and deduplication.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yRV-kOWOkGLTAKuFcfYIEw.png" /></figure><pre># --- SILVER TABLE 1: Cleaned Orders ---<br>@sdp.materialized_view(<br>    comment=&quot;Cleaned and enriched orders. Invalid records are dropped.&quot;,<br>    table_properties={&quot;quality&quot;: &quot;silver&quot;}<br>)<br>@sdp.expect(&quot;valid_order_id&quot;, &quot;order_id IS NOT NULL&quot;)<br>@sdp.expect_or_drop(&quot;positive_quantity&quot;, &quot;quantity &gt; 0&quot;)<br>@sdp.expect_or_drop(&quot;positive_price&quot;, &quot;unit_price &gt; 0&quot;)<br>@sdp.expect(&quot;valid_date&quot;, &quot;order_date IS NOT NULL&quot;)<br>def silver_orders():<br>    return (<br>        spark.read.table(&quot;bronze_orders&quot;)<br>        .withColumn(&quot;total_amount&quot;, col(&quot;quantity&quot;) * col(&quot;unit_price&quot;))<br>        .withColumn(&quot;order_date&quot;, to_date(col(&quot;order_date&quot;), &quot;yyyy-MM-dd&quot;))<br>        .withColumn(&quot;order_year&quot;, year(col(&quot;order_date&quot;)))<br>        .withColumn(&quot;order_month&quot;, month(col(&quot;order_date&quot;)))<br>        .select(<br>            &quot;order_id&quot;, &quot;customer_id&quot;, &quot;product_id&quot;,<br>            &quot;quantity&quot;, &quot;unit_price&quot;, &quot;total_amount&quot;,<br>            &quot;order_status&quot;, &quot;order_date&quot;, &quot;order_year&quot;, &quot;order_month&quot;,<br>            &quot;payment_method&quot;, &quot;shipping_city&quot;<br>        )<br>    )<br><br><br># --- SILVER TABLE 2: Cleaned Customers ---<br>@sdp.materialized_view(<br>    comment=&quot;Cleaned customer profiles with standardised fields.&quot;,<br>    table_properties={&quot;quality&quot;: &quot;silver&quot;}<br>)<br>@sdp.expect_or_fail(&quot;customer_id_not_null&quot;, &quot;customer_id IS NOT NULL&quot;)<br>@sdp.expect(&quot;valid_email&quot;, &quot;email LIKE &#39;%@%&#39;&quot;)<br>def silver_customers():<br>    # expect_or_fail here: a customer without an ID is a fundamental<br>    # data integrity violation — stop the pipeline so we can investigate.<br>    return (<br>        spark.read.table(&quot;bronze_customers&quot;)<br>        .withColumn(&quot;signup_date&quot;, to_date(col(&quot;signup_date&quot;), &quot;yyyy-MM-dd&quot;))<br>        .withColumn(&quot;tier&quot;, upper(col(&quot;tier&quot;)))<br>        .withColumn(&quot;city&quot;, initcap(col(&quot;city&quot;)))<br>        .select(<br>            &quot;customer_id&quot;, &quot;customer_name&quot;, &quot;email&quot;,<br>            &quot;signup_date&quot;, &quot;tier&quot;, &quot;city&quot;, &quot;is_active&quot;<br>        )<br>    )</pre><h4>Change data capture with apply_changes</h4><p>Your source database sends INSERT, UPDATE, and DELETE events — potentially out of order. apply_changes handles everything automatically: deduplication by key, sequencing by timestamp, out-of-order arrivals, and full SCD Type 2 history.</p><p><strong>How it works:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHnWJaN9ma_DKKIXzs1ajg.jpeg" /></figure><pre>import pyspark.pipelines.flow as flow<br><br># Declare the target table first<br>sdp.create_streaming_table(<br>    name=&quot;silver_customer_dim_scd2&quot;,<br>    comment=&quot;SCD Type 2 for customers. Tracks full history of changes.&quot;<br>)<br><br># Then define the CDC flow<br>flow.apply_changes(<br>    target=&quot;silver_customer_dim_scd2&quot;,<br>    source=&quot;bronze_customer_cdc&quot;,<br>    keys=[&quot;customer_id&quot;],<br>    sequence_by=col(&quot;cdc_timestamp&quot;),<br>    apply_as_deletes=expr(&quot;operation = &#39;DELETE&#39;&quot;),<br>    except_column_list=[&quot;operation&quot;, &quot;cdc_timestamp&quot;],<br>    stored_as_scd_type=2<br>)</pre><h3>Gold layer | business-ready analytics</h3><p>Gold tables are the final output — optimised for dashboards, reports, and ML features.</p><p>Because we validated data in Silver, Gold never sees bad rows. Every aggregation here is computed over clean, trusted data.</p><pre># --- GOLD TABLE 1: Daily Revenue Summary ---<br>@sdp.materialized_view(<br>    comment=&quot;Daily revenue by city and payment method. Powers the revenue dashboard.&quot;,<br>    table_properties={&quot;quality&quot;: &quot;gold&quot;}<br>)<br>@sdp.expect(&quot;has_revenue&quot;, &quot;daily_revenue &gt; 0&quot;)<br>def gold_daily_revenue():<br>    return (<br>        spark.read.table(&quot;silver_orders&quot;)<br>        .filter(col(&quot;order_status&quot;).isin(&quot;completed&quot;, &quot;shipped&quot;))<br>        .groupBy(&quot;order_date&quot;, &quot;shipping_city&quot;, &quot;payment_method&quot;)<br>        .agg(<br>            sum(&quot;total_amount&quot;).alias(&quot;daily_revenue&quot;),<br>            count(&quot;order_id&quot;).alias(&quot;order_count&quot;),<br>            avg(&quot;total_amount&quot;).alias(&quot;avg_order_value&quot;),<br>            sum(&quot;quantity&quot;).alias(&quot;total_items_sold&quot;)<br>        )<br>    )<br><br><br># --- GOLD TABLE 2: Customer 360 View ---<br>@sdp.materialized_view(<br>    comment=&quot;Unified customer profile with order history metrics.&quot;,<br>    table_properties={&quot;quality&quot;: &quot;gold&quot;}<br>)<br>def gold_customer_360():<br>    order_metrics = (<br>        spark.read.table(&quot;silver_orders&quot;)<br>        .filter(col(&quot;order_status&quot;) == &quot;completed&quot;)<br>        .groupBy(&quot;customer_id&quot;)<br>        .agg(<br>            count(&quot;order_id&quot;).alias(&quot;total_orders&quot;),<br>            sum(&quot;total_amount&quot;).alias(&quot;lifetime_value&quot;),<br>            avg(&quot;total_amount&quot;).alias(&quot;avg_order_value&quot;),<br>            min(&quot;order_date&quot;).alias(&quot;first_order_date&quot;),<br>            max(&quot;order_date&quot;).alias(&quot;last_order_date&quot;)<br>        )<br>    )<br>    return (<br>        spark.read.table(&quot;silver_customers&quot;)<br>        .join(order_metrics, &quot;customer_id&quot;, &quot;left&quot;)<br>        .withColumn(&quot;total_orders&quot;, coalesce(col(&quot;total_orders&quot;), lit(0)))<br>        .withColumn(&quot;lifetime_value&quot;, coalesce(col(&quot;lifetime_value&quot;), lit(0.0)))<br>        .withColumn(&quot;days_since_last_order&quot;,<br>            datediff(current_date(), col(&quot;last_order_date&quot;)))<br>        .withColumn(&quot;customer_segment&quot;,<br>            when(col(&quot;lifetime_value&quot;) &gt; 5000, &quot;high_value&quot;)<br>            .when(col(&quot;lifetime_value&quot;) &gt; 1000, &quot;medium_value&quot;)<br>            .when(col(&quot;lifetime_value&quot;) &gt; 0, &quot;low_value&quot;)<br>            .otherwise(&quot;no_purchases&quot;))<br>    )<br><br><br># --- GOLD TABLE 3: Top Products ---<br>@sdp.materialized_view(<br>    comment=&quot;Product performance ranking by revenue and order volume.&quot;,<br>    table_properties={&quot;quality&quot;: &quot;gold&quot;}<br>)<br>def gold_top_products():<br>    return (<br>        spark.read.table(&quot;silver_orders&quot;)<br>        .filter(col(&quot;order_status&quot;).isin(&quot;completed&quot;, &quot;shipped&quot;))<br>        .groupBy(&quot;product_id&quot;)<br>        .agg(<br>            count(&quot;order_id&quot;).alias(&quot;total_orders&quot;),<br>            sum(&quot;total_amount&quot;).alias(&quot;total_revenue&quot;),<br>            sum(&quot;quantity&quot;).alias(&quot;total_quantity&quot;),<br>            avg(&quot;unit_price&quot;).alias(&quot;avg_selling_price&quot;),<br>            countDistinct(&quot;customer_id&quot;).alias(&quot;unique_buyers&quot;)<br>        )<br>        .withColumn(&quot;revenue_rank&quot;,<br>            dense_rank().over(Window.orderBy(desc(&quot;total_revenue&quot;))))<br>    )</pre><h3>Step 3: Run and monitor the pipeline</h3><h3>What happens when you click Run pipeline</h3><p>The framework resolves the dependency graph automatically, then executes in the correct order:</p><p>For this project, <strong>Triggered</strong> mode is the right choice.</p><p>You can find all your pipelines under <strong>Jobs &amp; Pipelines</strong>, where the run history and status for each pipeline is listed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Yfa337jAZI6XzqrBgvviw.jpeg" /></figure><h3>The pipeline DAG live view</h3><p>After a successful run, Databricks renders the full dependency graph. You can see each table, its type (Streaming table vs Materialized view), and the run duration for every node:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QMi-WEAsbh6UbDut4oalcg.jpeg" /></figure><p>All of the lineage is figured out, dependencises run as if it was orchestarted, streaming tables</p><h3>Step 4: Query your results</h3><p>After the pipeline completes, run these in a SQL editor or notebook:</p><pre>-- How many orders passed the quality rules?<br>SELECT count(*) AS total_clean_orders<br>FROM learn_lakeflow.ecommerce.silver_orders;<br><br>-- Top 10 revenue days by city<br>SELECT order_date, shipping_city, daily_revenue, order_count<br>FROM learn_lakeflow.ecommerce.gold_daily_revenue<br>ORDER BY daily_revenue DESC<br>LIMIT 10;<br><br>-- Customer segment distribution<br>SELECT customer_segment,<br>       count(*) AS customer_count,<br>       round(avg(lifetime_value), 2) AS avg_ltv<br>FROM learn_lakeflow.ecommerce.gold_customer_360<br>GROUP BY customer_segment<br>ORDER BY avg_ltv DESC;<br><br>-- SCD Type 2 — full change history for a single customer<br>SELECT *<br>FROM learn_lakeflow.ecommerce.silver_customer_dim_scd2<br>WHERE customer_id = &#39;CUST-0001&#39;<br>ORDER BY __START_AT;<br><br>-- Top 10 products by revenue<br>SELECT product_id, total_revenue, total_orders, unique_buyers, revenue_rank<br>FROM learn_lakeflow.ecommerce.gold_top_products<br>WHERE revenue_rank &lt;= 10<br>ORDER BY revenue_rank;</pre><h3>Step 5: Test incremental processing</h3><p>The real power of Lakeflow shows when new data arrives. Run this in a separate notebook to simulate new files landing in the volume:</p><pre>from pyspark.sql.functions import *<br>from datetime import datetime<br>import random<br><br>CATALOG     = &quot;learn_lakeflow&quot;<br>SCHEMA      = &quot;ecommerce&quot;<br>VOLUME_PATH = f&quot;/Volumes/{CATALOG}/{SCHEMA}/raw_files&quot;<br><br># Generate 500 new orders (simulating the next day&#39;s batch)<br>new_orders = []<br>for i in range(5001, 5501):<br>    new_orders.append({<br>        &quot;order_id&quot;:       f&quot;ORD-{i:06d}&quot;,<br>        &quot;customer_id&quot;:    f&quot;CUST-{random.randint(1, 500):04d}&quot;,<br>        &quot;product_id&quot;:     f&quot;PROD-{random.randint(1, 50):03d}&quot;,<br>        &quot;quantity&quot;:       random.randint(1, 10),<br>        &quot;unit_price&quot;:     round(random.uniform(9.99, 299.99), 2),<br>        &quot;order_status&quot;:   random.choice([&quot;completed&quot;, &quot;pending&quot;, &quot;shipped&quot;]),<br>        &quot;order_date&quot;:     &quot;2025-01-15&quot;,<br>        &quot;payment_method&quot;: random.choice([&quot;credit_card&quot;, &quot;upi&quot;, &quot;wallet&quot;]),<br>        &quot;shipping_city&quot;:  random.choice([&quot;Mumbai&quot;, &quot;Delhi&quot;, &quot;Bangalore&quot;]),<br>    })<br><br>new_orders_df = spark.createDataFrame(new_orders)<br><br># Write a NEW file — Auto Loader will detect it automatically<br>new_orders_df.coalesce(1).write \<br>    .mode(&quot;append&quot;) \<br>    .option(&quot;header&quot;, &quot;true&quot;) \<br>    .csv(f&quot;{VOLUME_PATH}/orders/&quot;)<br><br>print(&quot;Wrote 500 new orders.&quot;)<br>print(&quot;Re-run the pipeline — only these 500 rows will be processed.&quot;)<br>print(&quot;Auto Loader remembers the checkpoint and skips previously processed files.&quot;)</pre><p>Re-run the pipeline after this, and only <strong>the 500 new rows</strong> will be processed.</p><p><strong>First run :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9UbUfDu2M3Fgfw12zWYBWA.jpeg" /></figure><p><strong>Second run:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QwB1rSVtZomNGE3MB7e1gg.jpeg" /></figure><p>The two screenshots are from the same pipeline run — Image 2 is the Bronze layer (06:43 PM) and Image 1 is the Silver layer (06:57 PM). The numbers tell the whole story of how Auto Loader checkpointing works.</p><p>Notice what happened: bronze_orders read <strong>10,000 rows</strong> on the first run, but the Silver layer downstream (silver_orders) only read <strong>34,096 rows</strong> — which is the cumulative dataset it re-materialized. The <em>next</em> time you run the pipeline, bronze_orders will read <strong>0 new rows</strong> unless new files land, and silver_orders will only recompute the delta.</p><p>Here’s the mechanism visually:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aSmf-cSJgvt6_zZJxpMxnA.jpeg" /></figure><p>The pipeline is incremetal by design now, no additional configuration needed</p><p>The Bronze tables skip all previously seen files entirely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dDu-atrbU3ic4cRyXnb7cg.png" /></figure><p>Next article goes more advanced!</p><p>All code in this article was tested on <strong>Databricks Free Edition (March 2026).</strong> The pipeline ran to completion in 1m 17s on Serverless compute with synthetic e-commerce data.</p><p>Follow me on <a href="https://www.linkedin.com/in/h-kaushik/">linkedin</a> for more updates on the next article, let’s learn this together</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae3aaabf7274" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[DataBricks LakeFlow Foundations]]></title>
            <link>https://medium.com/@hiteshkhk0105/databricks-lakeflow-foundations-58579ab30068?source=rss-cd5a029c558f------2</link>
            <guid isPermaLink="false">https://medium.com/p/58579ab30068</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks-lakeflow]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[Hitesh]]></dc:creator>
            <pubDate>Fri, 06 Mar 2026 13:04:00 GMT</pubDate>
            <atom:updated>2026-03-06T13:04:00.834Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Phase: 1</strong></h4><p><strong>Goal:</strong> Let’s just understand the syntax and get ourselves famirilized with key terms we’d be using Databricks Lakeflow with!</p><p>Follow me on <a href="https://www.linkedin.com/in/h-kaushik/">linkedin</a> for more updates on the next article, let’s learn this together</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kn6aTZ0dHksDqRy4xnHt1w.jpeg" /></figure><p><strong>After this phase:</strong> We’ll know</p><ul><li><strong>Streaming tables</strong></li><li><strong>Materialized views and how they are different </strong>a</li><li><strong>Expectations</strong></li><li><strong>Auto Loader</strong></li></ul><p>Then we’ll go build them in Phase 2, later details would be in the next article:</p><h3>Table of Contents</h3><ul><li><em>1.1 What Is Lakeflow SDP and Why Should You Care?</em></li><li><em>1.2 The Import That Changed Everything</em></li><li><em>1.3 Streaming Tables — The Bronze Workhorse</em></li><li><em>1.4 Auto Loader — Every Option Explained</em></li><li><em>1.5 Materialized Views — The Silver &amp; Gold Engine</em></li><li><em>1.6 Expectations — Data Quality as Code</em></li></ul><h3>1.1 What Is Lakeflow SDP and Why Should You Care?</h3><p>Lakeflow Spark Declarative Pipelines (SDP) is Databricks’ framework for building batch and streaming ETL pipelines. The word “<strong><em>declarative</em></strong>” is the key here.</p><p>You describe <strong>what</strong> your tables should contain, and the framework figures out <strong>how</strong> to execute it.</p><p>Ok so what is this declarative way and how did we do it before?</p><p><strong>The old way (procedural Spark):</strong></p><pre># You manage everything yourself<br>orders_df = spark.read.format(&quot;csv&quot;).load(&quot;/data/orders/&quot;)<br>cleaned = orders_df.filter(col(&quot;quantity&quot;) &gt; 0).withColumn(...)<br>cleaned.write.format(&quot;delta&quot;).mode(&quot;overwrite&quot;).saveAsTable(&quot;silver_orders&quot;)<br># Now manually schedule this, handle failures, track what&#39;s processed...</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*21iYJ0s08Fr-cnzuQFtX1A.gif" /></figure><p><strong>The Lakeflow way (declarative):</strong></p><pre>@sdp.materialized_view()<br>def silver_orders():<br>    return spark.read.table(&quot;bronze_orders&quot;).filter(col(&quot;quantity&quot;) &gt; 0)<br></pre><p>Let’s break the code down</p><ul><li>What should the table be ? <strong>Materialized view!</strong></li><li>What’s the name of the table ? <strong>silver_orders!</strong></li><li>what should it do? <strong>Read data incrementally from <em>bronze_orders </em>filtering where the quantity is &gt; 0</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/0*fZ8M8oq0XPIZW1d3.jpg" /></figure><p>SDP handles execution order, retries, incremental processing, everything.<strong>What SDP gives you for free:</strong></p><ul><li>Automatic dependency resolution (no manual DAG building) <strong>What happens after what (the older)</strong></li><li>Automatic retry <strong>(task-level -&gt; flow-level -&gt; pipeline-level)</strong></li><li>Incremental processing (<strong>only process new/changed data)</strong></li><li>Built-in data <strong>quality monitoring</strong></li><li><strong>Unity Catalog </strong>integration</li></ul><h3>1.2 The Import That Changed Everything</h3><p>The import statement is the first thing people get wrong. Here’s the history and current state:</p><pre># OLD WAY (pre-2025, you&#39;ll see this in old blogs/docs)<br># This import is DEPRECATED:<br>import dlt  # &lt;-- Don&#39;t use this anymore</pre><pre># NEW WAY (current, since Lakeflow SDP went GA)<br>from pyspark import pipelines as sdp<br># For CDC/flow operations:<br>import pyspark.pipelines.flow as flow</pre><p><strong>Why did it change?</strong> Databricks contributed the core declarative pipeline technology to Apache Spark as “<strong>Spark Declarative Pipelines</strong>.”</p><p>The dlt module was Databricks-proprietary. The new pyspark.pipelines module is the open standard.</p><p><strong>The mapping from old to new:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fqw_Db0zUhxCSDmShZdWKw.jpeg" /></figure><blockquote><em>If you copy code from a blog written before mid-2025, it will use </em><em>import dlt.</em></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*rG3RpQ0vcd31GkGi.gif" /></figure><blockquote><em>Haha well , still works (</em><strong><em>backward compatible)</em></strong><em> but you should use the new imports for anything new.</em></blockquote><h3>1.3 Streaming Tables — The Bronze Workhorse</h3><p>A streaming table is an <strong>append-only</strong> Delta table managed by Unity Catalog. It’s the default choice for the Bronze layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kObTer8a9_YfuNeV5Ze30g.jpeg" /></figure><h3>Python Syntax — Full Anatomy</h3><pre>from pyspark import pipelines as sdp<br>from pyspark.sql.functions import *<br>from pyspark.sql.types import *<br><br>@sdp.table(<br>    # --- Required: none! But you should always set these ---<br><br>    # Human-readable description (shows in Unity Catalog UI)<br>    comment=&quot;Raw orders from CSV files&quot;,<br><br>    # Custom table properties (arbitrary key-value metadata)<br>    table_properties={<br>        &quot;quality&quot;: &quot;bronze&quot;,<br>        &quot;pipelines.autoOptimize.managed&quot;: &quot;true&quot;<br>    },<br><br>    # Explicit schema (optional — Auto Loader can infer it)<br>    schema=StructType([<br>        StructField(&quot;order_id&quot;, StringType(), True),<br>        StructField(&quot;amount&quot;, DoubleType(), True),<br>    ]),<br><br>    # Partition columns (use sparingly — usually not needed with Delta)<br>    partition_cols=[&quot;order_date&quot;],<br><br>    # Path for external table (omit for managed table — recommended)<br>    # path=&quot;/mnt/external/bronze_orders&quot;,<br><br>    # Temporary table (not persisted in UC, only exists during pipeline run)<br>    # temporary=True,<br>)<br>def bronze_orders():<br>    return (<br>        spark.readStream<br>        .format(&quot;cloudFiles&quot;)<br>        .option(&quot;cloudFiles.format&quot;, &quot;csv&quot;)<br>        .option(&quot;header&quot;, &quot;true&quot;)<br>        .load(&quot;/Volumes/catalog/schema/volume/orders/&quot;)<br>    )<br><br></pre><p>This is a critical syntactic nuance:</p><pre>@sdp.table()<br>def bronze_orders():   # &lt;-- This creates a table NAMED &quot;bronze_orders&quot;<br>    ...</pre><p>The function name becomes the table name in Unity Catalog: &lt;catalog&gt;.&lt;schema&gt;.&lt;function_name&gt;.</p><blockquote>You <strong>cannot</strong> override the table name via a parameter. The function name is the name.</blockquote><h3>What Makes It “Streaming”?</h3><p>The table becomes a streaming table when you return a <strong>streaming DataFrame</strong> (i.e., you use spark.readStream):</p><pre>@sdp.table()<br>def this_is_a_streaming_table():<br>    return spark.readStream.table(&quot;source&quot;)    # readStream = streaming table</pre><blockquote><strong><em>Nuance:</em></strong><em> If you use </em><em>@sdp.table() with </em><em>spark.read (not </em><em>readStream), it still creates a table, but it behaves differently — it&#39;s a full refresh each time, not incremental.</em></blockquote><pre>@sdp.table()<br>def this_is_a_batch_table():<br>    return spark.read.table(&quot;source&quot;) # read = NOT a streaming table (materialized view-like)</pre><h3>1.4 Auto Loader — Every Option Explained</h3><p>Auto Loader (cloudFiles format) is how you ingest files into streaming tables. Here&#39;s every option you&#39;ll commonly use:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UBePfte4g0H6cd72PGI7ng.jpeg" /></figure><pre><br>spark.readStream<br>    .format(&quot;cloudFiles&quot;)<br><br>    # === REQUIRED OPTIONS ===<br><br>    # What format are the source files?<br>    .option(&quot;cloudFiles.format&quot;, &quot;csv&quot;)<br>    # Supported: csv, json, parquet, avro, text, binaryFile, orc<br><br>    # === SCHEMA OPTIONS (pick one strategy) ===<br><br>    # Strategy 1: Let Auto Loader infer the schema<br>    .option(&quot;cloudFiles.inferColumnTypes&quot;, &quot;true&quot;)<br>    # Good for prototyping. Bad for production (schema can drift).<br><br>    # Strategy 2: Provide schema explicitly (recommended for production)<br>    .schema(StructType([<br>        StructField(&quot;order_id&quot;, StringType()),<br>        StructField(&quot;amount&quot;, DoubleType()),<br>    ]))<br><br>    # Strategy 3: Schema location (Auto Loader infers once, then caches)<br>    .option(&quot;cloudFiles.schemaLocation&quot;, &quot;/path/to/_schemas/orders&quot;)<br>    # Best of both worlds: infers once, then uses cached schema.<br>    # REQUIRED when using inferColumnTypes in a pipeline.<br><br>    # === SCHEMA EVOLUTION ===<br><br>    # What happens when new columns appear in source files?<br>    .option(&quot;cloudFiles.schemaEvolutionMode&quot;, &quot;addNewColumns&quot;)<br>    # Options:<br>    #   &quot;addNewColumns&quot; - auto-add new columns (default)<br>    #   &quot;rescue&quot;        - put unknown columns in _rescued_data column<br>    #   &quot;failOnNewColumns&quot; - fail the pipeline<br>    #   &quot;none&quot;          - ignore new columns<br><br>    # === FORMAT-SPECIFIC OPTIONS ===<br><br>    # CSV options<br>    .option(&quot;header&quot;, &quot;true&quot;)          # First row is header<br>    .option(&quot;sep&quot;, &quot;,&quot;)                # Delimiter (default comma)<br>    .option(&quot;multiLine&quot;, &quot;true&quot;)       # Handle multi-line CSV records<br>    .option(&quot;escape&quot;, &quot;\&quot;&quot;)            # Escape character<br><br>    # JSON options<br>    .option(&quot;multiLine&quot;, &quot;true&quot;)       # Handle pretty-printed JSON<br><br>    # === PERFORMANCE OPTIONS ===<br><br>    # File discovery mode<br>    .option(&quot;cloudFiles.useNotifications&quot;, &quot;true&quot;)<br>    # &quot;true&quot;  = event-based (S3 notifications, ADLS events) — faster, requires setup<br>    # &quot;false&quot; = directory listing (default) — simpler, works everywhere<br><br>    # Max files per trigger (throttle ingestion rate)<br>    .option(&quot;cloudFiles.maxFilesPerTrigger&quot;, &quot;1000&quot;)<br><br>    # === FILE FILTERING ===<br><br>    # Only process files matching a glob pattern<br>    .option(&quot;pathGlobFilter&quot;, &quot;*.csv&quot;)  # Only CSV files<br><br>    # Recursively scan subdirectories<br>    .option(&quot;recursiveFileLookup&quot;, &quot;true&quot;)<br><br>    # === THE LOAD PATH ===<br>    .load(&quot;/Volumes/catalog/schema/volume/orders/&quot;)<br>    # Can be:<br>    #   /Volumes/...          (Unity Catalog Volumes)<br>    #   s3://bucket/path/     (S3 directly)<br>    #   abfss://container@account.dfs.core.windows.net/path/  (ADLS Gen2)<br>    #   gs://bucket/path/     (GCS)</pre><h3>The _rescued_data Column</h3><p>When Auto Loader encounters data that doesn’t match the schema, it stashes it in a special column:</p><pre># Enable rescue mode<br>.option(&quot;cloudFiles.schemaEvolutionMode&quot;, &quot;rescue&quot;)</pre><p>This adds a _rescued_data <strong>STRING column containing JSON of any columns that didn&#39;t match</strong>.</p><p><em>Extremely useful for debugging data quality issues without losing data.</em></p><h3>1.5 Materialized Views — The Silver &amp; Gold Engine</h3><p>A materialized view is a <strong>pre-computed query result</strong> stored as a Delta table. Unlike streaming tables, materialized views can handle updates, deletes, aggregations, and joins.</p><h3>Python Syntax — Full Anatomy</h3><pre>@sdp.materialized_view(<br>    comment=&quot;Cleaned orders with computed revenue column&quot;,<br>    table_properties={&quot;quality&quot;: &quot;silver&quot;},<br># Partition columns (optional, rarely needed)<br>    partition_cols=[&quot;order_year&quot;],<br>    # Temporary materialized view (not persisted in UC)<br>    # temporary=True,<br>)<br>def silver_orders():<br>    return (<br>        spark.read.table(&quot;bronze_orders&quot;)  # NOTE: spark.read, NOT spark.readStream<br>        .withColumn(&quot;revenue&quot;, col(&quot;quantity&quot;) * col(&quot;price&quot;))<br>    )</pre><h3>Materialized View vs Streaming Table: What to use when !?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZT4VBvAQpqH3sNpCY612pg.jpeg" /><figcaption>Materialized views vs streeming table</figcaption></figure><p><strong>Key rules:</strong></p><ul><li>Bronze layer: Almost always <strong>streaming tables</strong> (raw data lands as-is)</li><li>Silver layer: Usually <strong>materialized views</strong> (cleaning, enrichment, joins)</li><li>Gold layer: Always <strong>materialized views</strong> (aggregations, business logic)</li><li>CDC targets: <strong>Streaming tables</strong> (required by apply_changes)</li></ul><h3>How Incremental Refresh Works</h3><p>When you refresh a materialized view, SDP doesn’t blindly recompute everything:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uisxXJCyg6eD71GPNf012A.jpeg" /></figure><ol><li>It checks which source tables have changed since the last refresh</li><li>For simple transformations (filter, select, withColumn), it only processes new rows</li><li>For aggregations, it may need to recompute affected groups</li><li>For complex joins, it falls back to full recompute</li></ol><blockquote><strong><em>Nuance:</em></strong><em> This incremental optimization is automatic. You write batch-style code (</em><em>spark.read.table()), and SDP converts it to incremental processing under the hood. You don&#39;t need to think about streaming semantics.</em></blockquote><h3>1.6 Expectations — Data Quality as Code</h3><p>Expectations are data quality rules that run during pipeline execution. They’re the most underrated feature of Lakeflow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4iImEmKKq4EzZVY-_z9puw.jpeg" /></figure><h3>The Three Flavors</h3><pre># 1. EXPECT — Log violations, keep the row<br>@sdp.expect(&quot;rule_name&quot;, &quot;SQL boolean expression&quot;)</pre><pre># 2. EXPECT_OR_DROP — Drop rows that violate<br>@sdp.expect_or_drop(&quot;rule_name&quot;, &quot;SQL boolean expression&quot;)</pre><pre># 3. EXPECT_OR_FAIL — Fail the entire pipeline<br>@sdp.expect_or_fail(&quot;rule_name&quot;, &quot;SQL boolean expression&quot;)</pre><h3>Complete Syntax Reference</h3><pre>@sdp.materialized_view()<br>@sdp.expect(&quot;non_null_id&quot;, &quot;id IS NOT NULL&quot;)<br>@sdp.expect(&quot;positive_amount&quot;, &quot;amount &gt; 0&quot;)<br>@sdp.expect_or_drop(&quot;valid_email&quot;, &quot;email LIKE &#39;%@%.%&#39;&quot;)<br>@sdp.expect_or_drop(&quot;not_future_date&quot;, &quot;order_date &lt;= current_date()&quot;)<br>@sdp.expect_or_fail(&quot;has_customer&quot;, &quot;customer_id IS NOT NULL&quot;)<br>def my_table():<br>    ...</pre><h3>Syntactic Nuances</h3><p><strong>The condition is a SQL expression, not Python:</strong></p><pre># CORRECT — SQL syntax<br>@sdp.expect(&quot;rule&quot;, &quot;amount &gt; 0&quot;)<br>@sdp.expect(&quot;rule&quot;, &quot;name IS NOT NULL&quot;)<br>@sdp.expect(&quot;rule&quot;, &quot;status IN (&#39;active&#39;, &#39;pending&#39;)&quot;)<br>@sdp.expect(&quot;rule&quot;, &quot;email LIKE &#39;%@%&#39;&quot;)<br>@sdp.expect(&quot;rule&quot;, &quot;LEN(phone) &gt;= 10&quot;)</pre><pre># WRONG — Python syntax won&#39;t work<br>@sdp.expect(&quot;rule&quot;, amount &gt; 0)        # NameError<br>@sdp.expect(&quot;rule&quot;, &quot;amount != None&quot;)  # SQL uses IS NOT NULL, not != None</pre><p><strong>Multiple expectations stack (AND logic):</strong></p><pre>@sdp.materialized_view()<br>@sdp.expect(&quot;rule_a&quot;, &quot;a &gt; 0&quot;)        # All three must be true<br>@sdp.expect(&quot;rule_b&quot;, &quot;b IS NOT NULL&quot;) # for a row to be &quot;clean&quot;<br>@sdp.expect_or_drop(&quot;rule_c&quot;, &quot;c IN (&#39;x&#39;, &#39;y&#39;)&quot;)  # This one actually drops<br>def my_table():<br>    ...</pre><p><strong>You can’t mix </strong><strong>expect_or_fail with other types in a meaningful way</strong> — if expect_or_fail triggers, everything stops regardless.</p><p><strong>Decorator order matters for readability, not execution:</strong></p><pre># These are equivalent — decorator order doesn&#39;t affect logic:<br>@sdp.materialized_view()<br>@sdp.expect(&quot;a&quot;, &quot;x &gt; 0&quot;)<br>@sdp.expect_or_drop(&quot;b&quot;, &quot;y &gt; 0&quot;)<br>def t(): ...</pre><pre>@sdp.materialized_view()<br>@sdp.expect_or_drop(&quot;b&quot;, &quot;y &gt; 0&quot;)<br>@sdp.expect(&quot;a&quot;, &quot;x &gt; 0&quot;)<br>def t(): ...</pre><h3>Multiple Expectations as a Dict (Advanced)</h3><pre># For many rules, you can pass a dict:<br>@sdp.expect_all({<br>    &quot;valid_id&quot;: &quot;id IS NOT NULL&quot;,<br>    &quot;valid_amount&quot;: &quot;amount &gt; 0&quot;,<br>    &quot;valid_date&quot;: &quot;date IS NOT NULL&quot;<br>})</pre><pre>@sdp.expect_all_or_drop({<br>    &quot;positive_qty&quot;: &quot;quantity &gt; 0&quot;,<br>    &quot;valid_status&quot;: &quot;status IN (&#39;active&#39;, &#39;inactive&#39;)&quot;<br>})</pre><pre>@sdp.expect_all_or_fail({<br>    &quot;has_pk&quot;: &quot;primary_key IS NOT NULL&quot;,<br>    &quot;unique_check&quot;: &quot;duplicate_flag = false&quot;<br>})</pre><h3>Where Do Quality Metrics Go?</h3><p>Expectation results are logged in the pipeline’s <strong>event log</strong>:</p><pre>SELECT<br>  timestamp,<br>  details:flow_definition.output_dataset AS table_name,<br>  details:flow_progress.data_quality.expectations AS quality_rules<br>FROM event_log(TABLE(catalog.schema.your_table))<br>WHERE event_type = &#39;flow_progress&#39;<br>  AND details:flow_progress.data_quality IS NOT NULL</pre><p>Each entry tells you:</p><ul><li>How many rows passed each expectation</li><li>How many rows failed</li><li>How many were dropped (for expect_or_drop)</li></ul><p>Follow me on <a href="https://www.linkedin.com/in/h-kaushik/">linkedin</a> for updated on the next interesting article! :</p><p><strong>Next step:</strong> Now that we lerned the entire lakeflow concepts and how to use them! Let’s build something in the next article and see it in <strong>Action</strong> ! Stay tuned</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=58579ab30068" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Formula -1 Insights: Real-Time Replay & Historical Analytics ]]></title>
            <link>https://medium.com/@hiteshkhk0105/formula-1-insights-real-time-replay-historical-analytics-81b4c36da5ba?source=rss-cd5a029c558f------2</link>
            <guid isPermaLink="false">https://medium.com/p/81b4c36da5ba</guid>
            <category><![CDATA[dbt]]></category>
            <category><![CDATA[snowflake]]></category>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[analytics-engineering]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Hitesh]]></dc:creator>
            <pubDate>Sat, 31 May 2025 11:57:40 GMT</pubDate>
            <atom:updated>2025-05-31T11:57:40.839Z</atom:updated>
            <content:encoded><![CDATA[<p>Now that we are all at a point to now build out a comprehensive data project! 🏎️</p><p>Do reach out on to me on <a href="https://www.linkedin.com/in/h-kaushik/">linkedin</a> in case of any questions or discussions!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*65NZRAewT9VMsY0eVlVovw.gif" /></figure><blockquote>The first question, where do i even start?</blockquote><blockquote>This question is what i had myself before few months and here’s how i went about it.</blockquote><blockquote>Ok so the first thing! I need data, how do we get good data? Realtime data maybe?</blockquote><blockquote>What’s a great API, how should i shortlist them</blockquote><blockquote>Batch and Realtime , how should both be handled?</blockquote><blockquote>And last but not the least , how do i keep my project live with minial costs</blockquote><p>Over the series of blog posts i’ll go through each of the steps which i followed to get this project live and running</p><p><strong>Current blog scope:</strong></p><p>The project comprises 2 major sections :</p><ul><li>Ideation → API → Source</li><li>Airflow (WAP framework maintaining idempodency) (tips and tricks)</li><li>Data design and context for upcoming blogs!</li></ul><p><strong>Future blog’s scope:</strong></p><p>Over the next two blogs i would be covering the below in detail:</p><ul><li>Historical Trend Analysis using DBT , Snowflake deep dive</li><li>Grafana (Interactive visualizations and deep dive) — Translating questions into interactive visuals (DBT deep dive)</li><li>Real-time Streaming Pipeline using Confluent Kafka, SingleStore , AWS ec2 deployment</li></ul><h3>Process flow</h3><p>Ok so let’s say you are building this project where to you start from ?</p><blockquote>Figure the use-case you’re passionate about (trust me you need the passion part to stay interested for long )</blockquote><ul><li>Find the API’s and narrow down the resources</li><li>Figure out the structure of json , and data model it according to the API offerings</li><li>Write down questions on what are the questions you would want to answer , with the analysis, if you’re able to come up with considerable number of questions . It’s the right one for you.</li><li>Finally do some data modelling and decide on how your data table</li><li>Finally decide on the Airlfow scheduling and backfilling challenges (implement a WAP pattern and make your pipelines and data ingestion idempodent)</li></ul><p><strong>Motivation (Why are we building it?)</strong></p><p>Formula 1 racing represents the pinnacle of motorsport technology, where split-second decisions and minute performance differences determine victory.</p><p>This project presents a comprehensive Formula 1 telemetry analysis system that brings together real-time data streaming and historical insights to unlock the complexities of race strategy and performance.</p><h3>Use-case you’re passionate about?</h3><p>Ok so these can be anything , anything that gets you curious. Which isn’t obvious at a glance</p><p>Here’s a list of API’s you can figure out if you aren’t sure of any:</p><p><a href="https://rapidapi.com/collection/list-of-free-apis">Free Public APIs for Developers</a></p><p><a href="https://dev.to/balrajola/20-free-apis-to-kickstart-your-side-projects-1f7i">20 Free APIs to Kickstart Your Side Projects</a></p><p>Make sure you understand few pain points which always made you wonder?</p><ul><li>Pick a one which you connect with, it’s always fun to answer the questions which you always wanted to answer right?!</li></ul><h3>API’s and narrow down the resources</h3><p>Now that you have decided a domain or a use-case shortlist all the API’s you have in it</p><p>Here is a list of API’s i’ve shortlisted for mine (the columns are the considerations)</p><p><strong>Dataset Choices</strong></p><ul><li>For the most part i came across multiple data sources that help</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qB3_kXSlqVK--H4IKwf8Hw.jpeg" /></figure><p><strong>My choice was OpenF1 for the following reasons:</strong></p><ul><li>The API is directly sourced from <a href="https://www.formula1.com/en/timing/">F1 LiveTiming</a> , So in future after i subscribe the data json would look similar and i can directly source from the official site</li><li>Offers multiple data in depth with different API endpoints. essentially 1 API with multiple API endpoints that give different data (High frequency data and low frequency generic info)</li><li>Had structure and relationships between endpoints, that would let me correlate the effect of one over the other</li></ul><p><em>Here’s the fun-stuff!</em></p><h3>Figure out the structure of json , and data model it according to the API offerings</h3><p>We need two thing here:</p><ul><li>Json responses should easily translate into our staging tables (Silver layer) (if not we need to transform it such way)</li></ul><p><em>These are all the responses i endpoints i had:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u6m4M7KexeAN-0BhVkF1iw.gif" /></figure><p>Multiple api’s must have parameters that can act as foreign keys for our table translations</p><h3>Historical Analysis &amp; Strategic Insights</h3><p>Realtime data is amazing ! But for the most part hidden patterns only emerge out of historical analysis:</p><p>Beyond real-time replay, the system enables comprehensive post-race analysis to understand the intricate factors that influence race outcomes:</p><p><strong>High level Architecture Diagram</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kDt2mhsaJ08JspT0.jpeg" /></figure><p>Let’s only consider the Historical analysis part for the purpose of this job:</p><p><strong>API responses converted into Tables (ERD)</strong></p><p><strong>Data Ingestion</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N7HqIADYbbQ-v4k3.jpeg" /></figure><p>I made sure during my ingestion these 5 properties are always maintained</p><p><strong>Idempodency ( Merge keys )</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lZDc4Nt8gtFgpRxyw_-faw.gif" /><figcaption>Merge and idempodency explained</figcaption></figure><ul><li>No two non-unique recods are added to the table also ensuring upserts only</li><li>Created a dynamic since the structure of the statement remains same</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N2Wb4eetBBy4pYlQ.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*IfEQoZ1KPFS4LuK2.jpeg" /></figure><p><strong>API call retires and Fallbacks</strong></p><ul><li>So API’s are unreliable sometimes, hence having retry feature to make sure, no data is left behind during ingest</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kNfonbLumMo1TKUr.jpeg" /></figure><p>Handling high frequency data</p><ul><li>For telemetry high frequency data, i broke my api calls into 5 min chunks</li><li>Let’s say the API still produces too much data to handle, then it fallback into 1/2 the window size and then continues to maintain 5 min windows for the next call</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*SkKBoRnDPSmbCAlB.jpeg" /><figcaption>Airflow logs of a dag task run</figcaption></figure><p><strong>Always ingest into a temp staging table</strong></p><ul><li>Made sure the production table is not impacted by ingestion issues (always ingesting to a staging table and dropping it immediately after succesful merge)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*YKz8xzv4AcbmCBxg.jpeg" /></figure><p><strong>Compute resources ( save costs)</strong></p><ul><li>There is no Race every single day so i made sure i don’t exhaust the compute resources on a non race day</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uNdl8bqaLlPOiUky.jpeg" /></figure><p>Here’s the code to the entrire Airflow DAG:</p><p>Basic configuration of DBT and all the imports needed:</p><pre># f1_data_pipeline.py<br><br>from airflow.decorators import dag, task<br>from airflow.utils.dates import datetime<br>from datetime import timedelta, timezone<br>import logging<br>from typing import Dict, List, Any<br>from include.hitesh.scripts.f1_snowflake_etl_2 import F1DataIngestion<br>from include.eczachly.snowflake_queries import get_snowpark_session<br>import os<br>from dotenv import load_dotenv<br>from cosmos import DbtTaskGroup, ProjectConfig, ProfileConfig, RenderConfig<br>from airflow.operators.empty import EmptyOperator<br><br><br><br>dbt_env_path = os.path.join(os.environ[&#39;AIRFLOW_HOME&#39;], &#39;hitesh_dbt_project&#39;, &#39;dbt.env&#39;)<br>load_dotenv(dbt_env_path)<br><br># DBT paths<br>airflow_home = os.getenv(&#39;AIRFLOW_HOME&#39;)<br>PATH_TO_DBT_PROJECT = f&#39;{airflow_home}/hitesh_dbt_project&#39;<br>PATH_TO_DBT_PROFILES = f&#39;{airflow_home}/hitesh_dbt_project/profiles.yml&#39;<br><br># DBT profile configuration<br>profile_config = ProfileConfig(<br>    profile_name=&quot;formula_one&quot;,<br>    target_name=&quot;dev&quot;,<br>    profiles_yml_filepath=PATH_TO_DBT_PROFILES,<br>)<br><br></pre><p>This block is to decide on the f1 calender beforehand , so that we don’t run the DAG on days where the race hasn’t</p><pre>def get_f1_calendar(year: int) -&gt; List[Dict]:<br>    &quot;&quot;&quot;Get all race meetings for a given year&quot;&quot;&quot;<br>    try:<br>        session = get_snowpark_session()<br>        ingestion = F1DataIngestion(session)<br><br>        year_params = {&#39;year&#39;: year}<br>        meetings = ingestion._make_request(&#39;meetings&#39;, year_params)<br><br>        if meetings:<br>            meetings.sort(key=lambda x: x[&#39;date_start&#39;])<br>            return meetings<br>        return []<br>    except Exception as e:<br>        logging.error(f&quot;Error getting F1 calendar for year {year}: {str(e)}&quot;)<br>        return []</pre><p>To get the sessions available from the api:</p><pre>def get_all_sessions(year: int) -&gt; List[Dict[str, List]]:<br>    &quot;&quot;&quot;Get all session dates for a given year&quot;&quot;&quot;<br>    try:<br>        session = get_snowpark_session()<br>        ingestion = F1DataIngestion(session)<br><br>        year_params = {&#39;year&#39;: year}<br>        sessions = ingestion._make_request(&#39;sessions&#39;, year_params)<br><br>        if sessions:<br>            sessions.sort(key=lambda x: x[&#39;date_start&#39;])<br>            return [<br>                {datetime.fromisoformat(m[&#39;date_start&#39;].replace(&#39;Z&#39;, &#39;+00:00&#39;)).strftime(&#39;%Y-%m-%d&#39;):<br>                     [m[&#39;meeting_key&#39;], m[&#39;session_key&#39;]]}<br>                for m in sessions<br>            ]<br>        return []<br>    except Exception as e:<br>        logging.error(f&quot;Error getting session dates for year {year}: {str(e)}&quot;)<br>        return []</pre><p>DAG configurations</p><pre>@dag(<br>    dag_id=&#39;f1_data_pipeline_backfill&#39;,<br>    description=&quot;F1 Data Ingestion Pipeline - Session Days Only&quot;,<br>    default_args={<br>        &quot;owner&quot;: &quot;Hitesh Kaushik&quot;,<br>        &quot;retries&quot;: 3,                    # Increased retries<br>        &quot;retry_delay&quot;: timedelta(minutes=2),<br>        &quot;depends_on_past&quot;: False,<br>        &quot;execution_timeout&quot;: timedelta(hours=1),<br>        &quot;email_on_retry&quot;: True,<br>        &quot;max_active_tasks&quot;: 3,        # Limit concurrent tasks<br>        #&quot;start_date&quot;: first_race_date or datetime(2024, 1, 1),<br>        &quot;start_date&quot;: datetime(2024, 12, 7)<br>    },<br>    max_active_runs=1,<br>    schedule_interval=&quot;@daily&quot;,<br>    catchup=True,<br>    tags=[&quot;f1&quot;, &quot;snowpark&quot;, &quot;etl&quot;, &quot;racing</pre><p>Backfill DAG and the code of the logic’s explained above</p><pre>def f1_data_pipeline_backfill():<br><br>    @task<br>    def initialize_ingestion(**context):<br>        execution_date = context[&#39;data_interval_start&#39;]<br>        logging.info(f&quot;Processing date: {execution_date}&quot;)<br><br>        date_str = execution_date.strftime(&#39;%Y-%m-%d&#39;)<br>        logging.info(f&quot;Checking if {date_str} is a session date&quot;)<br><br>        if date_str not in session_dates:<br>            logging.info(f&quot;Skipping non-session day {date_str}&quot;)<br>            return None<br><br>        matching_sessions = []<br>        for session_dict in session_dates_2024:<br>            if date_str in session_dict:<br>                meeting_key = session_dict[date_str][0]<br>                session_key = session_dict[date_str][1]<br>                matching_sessions.append({<br>                    &#39;meeting_key&#39;: meeting_key,<br>                    &#39;session_key&#39;: session_key,<br>                    &#39;execution_date&#39;: execution_date<br>                })<br><br>        if not matching_sessions:<br>            logging.info(f&quot;No sessions found for date {date_str}&quot;)<br>            return None<br><br>        logging.info(f&quot;Found {len(matching_sessions)} sessions for {date_str}&quot;)<br>        return {<br>            &#39;execution_date&#39;: execution_date.isoformat(),<br>            &#39;sessions&#39;: matching_sessions,<br>            &#39;status&#39;: &#39;initialized&#39;,<br>            &#39;is_race_day&#39;: True<br>        }<br><br>    @task<br>    def get_meeting_data(init_status: dict):<br>        if not init_status:<br>            logging.info(&quot;No valid init status, skipping meeting data fetch&quot;)<br>            return None<br><br>        session = get_snowpark_session()<br>        ingestion = F1DataIngestion(session)<br>        ingestion.execution_date = datetime.fromisoformat(init_status[&#39;execution_date&#39;]).date()<br><br>        meetings = []<br>        for session_info in init_status[&#39;sessions&#39;]:<br>            params = {&#39;meeting_key&#39;: session_info[&#39;meeting_key&#39;]}<br><br>            try:<br>                data = ingestion._make_request(&#39;meetings&#39;, params)<br>                if data:<br>                    meeting = data[0]<br>                    if not ingestion.record_exists(&#39;F1_MEETINGS&#39;, meeting[&#39;meeting_key&#39;]):<br>                        ingestion.create_table(&#39;F1_MEETINGS&#39;, meeting)<br>                        ingestion.load_data(&#39;F1_MEETINGS&#39;, [meeting])<br>                        logging.info(f&quot;Loaded new meeting {meeting[&#39;meeting_key&#39;]}&quot;)<br>                    meetings.append(meeting)<br>            except Exception as e:<br>                logging.error(f&quot;Error processing meeting {session_info[&#39;meeting_key&#39;]}: {str(e)}&quot;)<br><br>        return meetings if meetings else None<br><br>    @task<br>    def get_sessions(meetings: list):<br>        if not meetings:<br>            logging.info(&quot;No meeting data provided, skipping sessions fetch&quot;)<br>            return []<br><br>        session = get_snowpark_session()<br>        ingestion = F1DataIngestion(session)<br><br>        all_sessions = []<br>        for meeting in meetings:<br>            try:<br>                sessions = ingestion.get_session_data(meeting[&#39;meeting_key&#39;])<br>                if sessions:<br>                    ingestion.create_table(&#39;F1_SESSIONS&#39;, sessions[0])<br>                    for sess in sessions:<br>                        if not ingestion.record_exists(&#39;F1_SESSIONS&#39;, meeting[&#39;meeting_key&#39;], sess[&#39;session_key&#39;]):<br>                            ingestion.load_data(&#39;F1_SESSIONS&#39;, [sess])<br>                            logging.info(f&quot;Loaded new session {sess[&#39;session_key&#39;]}&quot;)<br>                    all_sessions.extend(sessions)<br>            except Exception as e:<br>                logging.error(f&quot;Error processing sessions for meeting {meeting[&#39;meeting_key&#39;]}: {str(e)}&quot;)<br><br>        return all_sessions<br><br>    @task(trigger_rule=&#39;none_failed&#39;)<br>    def process_endpoint(sessions_list: List[dict], init_data: dict, endpoint: str) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;Process endpoint data for race sessions&quot;&quot;&quot;<br>        if init_data is None:<br>            return {<br>                &#39;endpoint&#39;: endpoint,<br>                &#39;processed&#39;: False,<br>                &#39;reason&#39;: &#39;no_init_data&#39;,<br>                &#39;results&#39;: []<br>            }<br><br>        results = []<br>        session = get_snowpark_session()<br>        ingestion = F1DataIngestion(session)<br>        execution_date = datetime.fromisoformat(init_data[&#39;execution_date&#39;]).date()<br>        ingestion.execution_date = execution_date<br><br>        table_name = f&#39;F1_{endpoint.upper()}&#39;<br><br>        for session_info in sessions_list:<br>            session_key = session_info[&#39;session_key&#39;]<br>            meeting_key = session_info[&#39;meeting_key&#39;]<br><br>            try:<br>                if ingestion.record_exists(table_name, meeting_key, session_key):<br>                    results.append({<br>                        &#39;session_key&#39;: session_key,<br>                        &#39;status&#39;: &#39;skipped&#39;,<br>                        &#39;reason&#39;: &#39;data_exists&#39;,<br>                        &#39;records&#39;: 0<br>                    })<br>                    continue<br><br>                data = ingestion.get_session_endpoint_data(session_info, endpoint)<br><br>                if not data:<br>                    results.append({<br>                        &#39;session_key&#39;: session_key,<br>                        &#39;status&#39;: &#39;skipped&#39;,<br>                        &#39;reason&#39;: &#39;no_data&#39;,<br>                        &#39;records&#39;: 0<br>                    })<br>                    continue<br><br>                if not ingestion.table_exists(table_name):<br>                    ingestion.create_table(table_name, data[0])<br><br>                ingestion.load_data(table_name, data)<br><br>                results.append({<br>                    &#39;session_key&#39;: session_key,<br>                    &#39;status&#39;: &#39;success&#39;,<br>                    &#39;records&#39;: len(data),<br>                    &#39;meeting_key&#39;: meeting_key<br>                })<br><br>            except Exception as e:<br>                results.append({<br>                    &#39;session_key&#39;: session_key,<br>                    &#39;status&#39;: &#39;error&#39;,<br>                    &#39;reason&#39;: str(e),<br>                    &#39;meeting_key&#39;: meeting_key<br>                })<br><br>        return {<br>            &#39;endpoint&#39;: endpoint,<br>            &#39;processed&#39;: True,<br>            &#39;execution_date&#39;: execution_date.isoformat(),<br>            &#39;results&#39;: results<br>        }<br><br>    @task(trigger_rule=&#39;none_failed&#39;)<br>    def process_race_data(sessions_list: List[dict], init_data: dict) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;Process race-specific data (positions, intervals) sequentially&quot;&quot;&quot;<br>        if not init_data or not init_data.get(&#39;is_race_day&#39;):<br>            return {<br>                &#39;processed&#39;: False,<br>                &#39;reason&#39;: &#39;not_race_day&#39;,<br>                &#39;results&#39;: []<br>            }<br><br>        results = []<br>        session = get_snowpark_session()<br>        ingestion = F1DataIngestion(session)<br>        execution_date = datetime.fromisoformat(init_data[&#39;execution_date&#39;]).date()<br>        ingestion.execution_date = execution_date<br><br>        # Process intervals first, then positions<br>        for session_info in sessions_list:<br>            session_key = session_info[&#39;session_key&#39;]<br>            meeting_key = session_info[&#39;meeting_key&#39;]<br><br>            # Process intervals data<br>            try:<br>                if not ingestion.record_exists(&#39;F1_INTERVALS&#39;, meeting_key, session_key):<br>                    data = ingestion.get_intervals_data(session_key)<br>                    if data:<br>                        if not ingestion.table_exists(&#39;F1_INTERVALS&#39;):<br>                            ingestion.create_table(&#39;F1_INTERVALS&#39;, data[0])<br>                        ingestion.load_data(&#39;F1_INTERVALS&#39;, data)<br>                        results.append({<br>                            &#39;endpoint&#39;: &#39;intervals&#39;,<br>                            &#39;session_key&#39;: session_key,<br>                            &#39;status&#39;: &#39;success&#39;,<br>                            &#39;records&#39;: len(data)<br>                        })<br>            except Exception as e:<br>                results.append({<br>                    &#39;endpoint&#39;: &#39;intervals&#39;,<br>                    &#39;session_key&#39;: session_key,<br>                    &#39;status&#39;: &#39;error&#39;,<br>                    &#39;error&#39;: str(e)<br>                })<br><br>            # Process position data only after intervals are done<br>            try:<br>                if not ingestion.record_exists(&#39;F1_POSITION&#39;, meeting_key, session_key):<br>                    data = ingestion.get_position_data(session_key)<br>                    if data:<br>                        if not ingestion.table_exists(&#39;F1_POSITION&#39;):<br>                            ingestion.create_table(&#39;F1_POSITION&#39;, data[0])<br>                        ingestion.load_data(&#39;F1_POSITION&#39;, data)<br>                        results.append({<br>                            &#39;endpoint&#39;: &#39;position&#39;,<br>                            &#39;session_key&#39;: session_key,<br>                            &#39;status&#39;: &#39;success&#39;,<br>                            &#39;records&#39;: len(data)<br>                        })<br>            except Exception as e:<br>                results.append({<br>                    &#39;endpoint&#39;: &#39;position&#39;,<br>                    &#39;session_key&#39;: session_key,<br>                    &#39;status&#39;: &#39;error&#39;,<br>                    &#39;error&#39;: str(e)<br>                })<br><br>        return {<br>            &#39;processed&#39;: True,<br>            &#39;execution_date&#39;: execution_date.isoformat(),<br>            &#39;results&#39;: results<br>        }<br><br><br>    @task(trigger_rule=&#39;none_failed&#39;)<br>    def process_technical_data(sessions_list: List[dict], init_data: dict) -&gt; Dict[str, Any]:<br>        &quot;&quot;&quot;Process technical data (stints, pit stops, race control)&quot;&quot;&quot;<br>        if not init_data:<br>            return {<br>                &#39;processed&#39;: False,<br>                &#39;reason&#39;: &#39;no_init_data&#39;,<br>                &#39;results&#39;: []<br>            }<br><br>        results = []<br>        session = get_snowpark_session()<br>        ingestion = F1DataIngestion(session)<br>        execution_date = datetime.fromisoformat(init_data[&#39;execution_date&#39;]).date()<br>        ingestion.execution_date = execution_date<br><br>        technical_endpoints = [&#39;stints&#39;, &#39;pit&#39;, &#39;race_control&#39;]<br><br>        for session_info in sessions_list:<br>            session_key = session_info[&#39;session_key&#39;]<br>            meeting_key = session_info[&#39;meeting_key&#39;]<br><br>            for endpoint in technical_endpoints:<br>                table_name = f&#39;F1_{endpoint.upper()}&#39;<br>                try:<br>                    if ingestion.record_exists(table_name, meeting_key, session_key):<br>                        continue<br><br>                    # Call appropriate method based on endpoint<br>                    if endpoint == &#39;stints&#39;:<br>                        data = ingestion.get_stints_data(session_key)<br>                    elif endpoint == &#39;pit&#39;:<br>                        data = ingestion.get_pit_data(session_key)<br>                    else:  # race_control<br>                        data = ingestion.get_race_control_data(session_key)<br><br>                    if data:<br>                        if not ingestion.table_exists(table_name):<br>                            ingestion.create_table(table_name, data[0])<br>                        ingestion.load_data(table_name, data)<br><br>                        results.append({<br>                            &#39;endpoint&#39;: endpoint,<br>                            &#39;session_key&#39;: session_key,<br>                            &#39;status&#39;: &#39;success&#39;,<br>                            &#39;records&#39;: len(data)<br>                        })<br><br>                except Exception as e:<br>                    results.append({<br>                        &#39;endpoint&#39;: endpoint,<br>                        &#39;session_key&#39;: session_key,<br>                        &#39;status&#39;: &#39;error&#39;,<br>                        &#39;error&#39;: str(e)<br>                    })<br><br>        return {<br>            &#39;processed&#39;: True,<br>            &#39;execution_date&#39;: execution_date.isoformat(),<br>            &#39;results&#39;: results<br>        }<br><br>    @task(trigger_rule=&#39;all_done&#39;)<br>    def cleanup_staging():  # Changed name to avoid conflicts<br>        &quot;&quot;&quot;Clean up any remaining staging tables&quot;&quot;&quot;<br>        try:<br>            session = get_snowpark_session()<br>            ingestion = F1DataIngestion(session)<br>            ingestion.cleanup_staging_tables()<br>            logging.info(&quot;Completed staging table cleanup&quot;)<br>        except Exception as e:<br>            logging.error(f&quot;Error in staging table cleanup task: {str(e)}&quot;)<br><br>    pre_dbt_workflow = EmptyOperator(<br>        task_id=&quot;pre_dbt_workflow&quot;,<br>        trigger_rule=&quot;all_done&quot;<br>    )<br><br>    # DBT transformation group<br>    dbt_transformations = DbtTaskGroup(<br>        group_id=&quot;f1_dbt_transformations&quot;,<br>        project_config=ProjectConfig(PATH_TO_DBT_PROJECT),<br>        profile_config=profile_config,<br>        render_config=RenderConfig(<br>            select=[<br>                &quot;staging.stg_f1_*&quot;,  # All staging models<br>                &quot;intermediate.int_*&quot;,  # All intermediate models<br>                &quot;marts.f1_*&quot;  # All final models<br>            ],<br>        ),<br>        operator_args={<br>            &quot;retries&quot;: 2,<br>            &quot;retry_delay&quot;: timedelta(minutes=2),<br>            &quot;execution_timeout&quot;: timedelta(minutes=30)<br>        }<br>    )<br><br>    # Final checkpoint<br>    post_dbt_workflow = EmptyOperator(<br>        task_id=&quot;post_dbt_workflow&quot;,<br>        trigger_rule=&quot;all_done&quot;,<br>        retries = 2<br>    )<br><br><br><br><br><br>    # To Execute the pipeline<br>    init_data = initialize_ingestion() # Here it skips races if it is not a race day (SAVE COMPUTE !! )<br>    meeting_data = get_meeting_data(init_data)<br>    sessions_data = get_sessions(meeting_data)<br><br>    # Process original endpoints<br>    endpoints = [&#39;drivers&#39;, &#39;car_data&#39;, &#39;laps&#39;, &#39;team_radio&#39;, &#39;weather&#39;]<br>    endpoint_tasks = []<br><br>    for endpoint_name in endpoints:<br>        task_id = f&#39;process_{endpoint_name}&#39;<br>        current_task = process_endpoint.override(task_id=task_id)(<br>            sessions_data,<br>            init_data,<br>            endpoint_name<br>        )<br>        endpoint_tasks.append(current_task)<br><br>    # Add new data processing tasks<br>    race_data = process_race_data(sessions_data, init_data)<br>    technical_data = process_technical_data(sessions_data, init_data)<br>    cleanup = cleanup_staging()<br><br>    # Set dependencies<br>    init_data &gt;&gt; meeting_data &gt;&gt; sessions_data<br><br>    # Set individual dependencies for each endpoint task<br>    for endpoint_task in endpoint_tasks:<br>        sessions_data &gt;&gt; endpoint_task &gt;&gt; cleanup<br><br>    # Set dependencies for race and technical data<br>    sessions_data &gt;&gt; race_data &gt;&gt; cleanup<br>    sessions_data &gt;&gt; technical_data &gt;&gt; cleanup<br><br>    # Connect DBT workflow<br>    cleanup &gt;&gt; pre_dbt_workflow &gt;&gt; dbt_transformations  &gt;&gt; post_dbt_workflow<br><br><br># Create DAG instance<br>dag = f1_data_pipeline_backfill()</pre><blockquote>Stay tuned for the upcoming articles !</blockquote><ul><li>Historical Trend Analysis using DBT , Snowflake deep dive</li><li>Real-time Streaming Pipeline using Confluent Kafka, SingleStore , AWS ec2 deployment</li></ul><p>Do reach out on to me on <a href="https://www.linkedin.com/in/h-kaushik/">linkedin</a> in case of any questions or discussions! Looking forward to some data talks! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81b4c36da5ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>