<?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 Monty Poddar on Medium]]></title>
        <description><![CDATA[Stories by Monty Poddar on Medium]]></description>
        <link>https://medium.com/@montypoddar08?source=rss-412283251922------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vaN5YEwz1T8vbIYCkBnr_A.png</url>
            <title>Stories by Monty Poddar on Medium</title>
            <link>https://medium.com/@montypoddar08?source=rss-412283251922------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 18:13:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@montypoddar08/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[❗    “--”]]></title>
            <link>https://medium.com/@montypoddar08/-0675c3c7b107?source=rss-412283251922------2</link>
            <guid isPermaLink="false">https://medium.com/p/0675c3c7b107</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Monty Poddar]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 03:04:02 GMT</pubDate>
            <atom:updated>2025-08-13T03:04:02.601Z</atom:updated>
            <content:encoded><![CDATA[<p>“We’ll just use schema-on-read. That way, we don’t have to worry about schema changes.”<br>I’ve heard this so many times in data projects…</p><p>𝗛𝗲𝗿𝗲’𝘀 𝘁𝗵𝗲 𝘁𝗿𝘂𝘁𝗵:<br>Schema-on-read doesn’t remove schema enforcement — it simply postpones it until query time.<br>And when that moment comes… it can be brutal.</p><p>𝗔 𝗿𝗲𝗮𝗹 𝗲𝘅𝗮𝗺𝗽𝗹𝗲 𝗜 𝘀𝗮𝘄 𝗿𝗲𝗰𝗲𝗻𝘁𝗹𝘆:</p><p>• We were reading from a JSON API into a Data Lake without defining strict schemas.<br> • One day, the upstream system quietly changed customer_id from string to an array.<br> • All our dashboards kept running… but the joins silently failed.<br> • Weeks later, business users started complaining about “missing customers” in reports.<br> • Root cause? A delayed schema explosion caused by schema-on-read.</p><p>𝗪𝗵𝘆 𝘀𝗰𝗵𝗲𝗺𝗮-𝗼𝗻-𝗿𝗲𝗮𝗱 𝗳𝗲𝗲𝗹𝘀 𝘀𝗮𝗳𝗲 𝗯𝘂𝘁 𝗶𝘀𝗻’𝘁:</p><p>• Silent Failures — Queries run but return wrong data.<br> • Late Discovery — You only detect schema drift when a consumer queries it.<br> • Hidden Complexity — Every downstream consumer must now handle every possible schema variant.</p><p>𝗛𝗼𝘄 𝘁𝗼 𝗮𝘃𝗼𝗶𝗱 𝘁𝗵𝗶𝘀 𝘁𝗿𝗮𝗽:<br> • Use schema-on-read selectively — great for exploratory analysis, bad for production pipelines.<br> • Implement schema contracts with tools like Delta Lake, Iceberg, or Glue Data Catalog.<br> • Automate compatibility checks in your ingestion pipeline to fail fast when schema drifts.<br> • Version your schemas so changes are deliberate, not accidental.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FTkQfXR8tK8xSE5cCtgIOQ.png" /></figure><h3>Schema-on-Read</h3><ol><li><strong>Unstructured Data</strong> is stored as-is (e.g., raw JSON, CSV, XML, logs).</li><li>The <strong>schema</strong> is only applied <strong>when you query</strong> the data.</li><li>This gives flexibility — the same raw data can be read in different ways by different consumers.</li><li><strong>Risk:</strong> If the data shape changes unexpectedly, queries may fail or return incorrect results, and the issue will only surface at query time.</li></ol><h3>Right Side — Schema-on-Write</h3><ol><li><strong>Structured Data</strong> is enforced <strong>before</strong> storing it (e.g., data loaded into a table with predefined column types).</li><li>Queries then run on <strong>validated, structured</strong> datasets.</li><li>This approach catches schema errors early (at write time) and ensures downstream consumers get consistent data.</li><li><strong>Trade-off:</strong> Less flexibility — you must decide and maintain the schema upfront.</li></ol><p>💡 <strong>Summary:</strong></p><ul><li><strong>Schema-on-read</strong> → Flexible, but errors are found late.</li><li><strong>Schema-on-write</strong> → Rigid, but errors are caught early.</li></ul><p>💡 Schema-on-read isn’t evil — but treating it as a free pass from data modeling is.<br>If you wouldn’t accept “code will compile eventually” from a developer… why accept “schema will work eventually” from a data pipeline?</p><p>#DataEngineering #DataQuality #Schema #BigData #MedallionArchitecture</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0675c3c7b107" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Parse Nested XML Using PySpark]]></title>
            <link>https://medium.com/@montypoddar08/parse-nested-xml-using-pyspark-b59356dfacab?source=rss-412283251922------2</link>
            <guid isPermaLink="false">https://medium.com/p/b59356dfacab</guid>
            <category><![CDATA[xml]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Monty Poddar]]></dc:creator>
            <pubDate>Wed, 28 May 2025 20:40:32 GMT</pubDate>
            <atom:updated>2025-05-28T20:40:32.087Z</atom:updated>
            <content:encoded><![CDATA[<p>We’ll walk through a real-world scenario: extracting deeply nested XML data from an Oracle database, transforming it with PySpark, and writing the clean, structured output back into another Oracle table.</p><h4>Problem Statement</h4><p>We have a source Oracle table with the following columns:</p><ul><li>seq_no: Sequence number (primary key)</li><li>customer_id: Customer identifier</li><li>account_data: XML string containing one or more &lt;item&gt; elements, each with details such as:</li></ul><p>A single customer may have multiple accounts or debit cards in a single XML blob.</p><h4>Requirement</h4><p>Transform the raw XML into a flattened table like this:</p><p>seq_no, customer_id, acc_no, isdebitcard, debitcardnumber</p><h4>Step 1: Read Source Data from Oracle</h4><p>We start by connecting to the source Oracle database using JDBC.</p><pre>from pyspark.sql import SparkSession<br>spark = SparkSession.builder \<br>    .appName(&quot;OracleXMLParser&quot;) \<br>    .getOrCreate()</pre><pre>oracle_url = &quot;jdbc:oracle:thin:@&lt;HOST&gt;:&lt;PORT&gt;:&lt;SID&gt;&quot;  # Replace with actual<br>properties = {<br>    &quot;user&quot;: &quot;&lt;USERNAME&gt;&quot;,<br>    &quot;password&quot;: &quot;&lt;PASSWORD&gt;&quot;,<br>    &quot;driver&quot;: &quot;oracle.jdbc.driver.OracleDriver&quot;<br>}</pre><pre>df_raw = spark.read.jdbc(<br>    url=oracle_url,<br>    table=&quot;SOURCE_TABLE_NAME&quot;,<br>    properties=properties<br>)</pre><h4>Step 2: Filter Invalid XML Records</h4><pre>from pyspark.sql.functions import udf<br>from pyspark.sql.types import StringType<br>import xml.etree.ElementTree as ET</pre><pre>def is_valid_xml(xml_str):<br>    try:<br>        ET.fromstring(xml_str)<br>        return &#39;True&#39;<br>    except:<br>        return &#39;False&#39;</pre><pre>is_valid_xml_udf = udf(is_valid_xml, StringType())</pre><h4>df_valid = df_raw.filter(is_valid_xml_udf(&quot;account_data&quot;) == &#39;True&#39;)</h4><h4>Step 3: Parse XML and Extract Repeating Elements</h4><p>We now extract all &lt;item&gt; nodes and flatten them into individual rows.</p><pre>from pyspark.sql.functions import col, explode<br>from pyspark.sql.types import StructType, StructField, StringType, ArrayType</pre><pre>def extract_account_items(xml_str):<br>    try:<br>        root = ET.fromstring(xml_str)<br>        items = root.findall(&quot;.//item&quot;)<br>        result = []<br>        for item in items:<br>            acc_no = item.findtext(&quot;acc_no&quot;) or &#39;&#39;<br>            isdebitcard = item.findtext(&quot;isdebitcard&quot;) or &#39;&#39;<br>            debitcardnumber = item.findtext(&quot;debitcardnumber&quot;) or &#39;&#39;<br>            result.append({<br>                &quot;acc_no&quot;: acc_no,<br>                &quot;isdebitcard&quot;: isdebitcard,<br>                &quot;debitcardnumber&quot;: debitcardnumber<br>            })<br>        return result<br>    except:<br>        return []</pre><pre>schema = ArrayType(<br>    StructType([<br>        StructField(&quot;acc_no&quot;, StringType(), True),<br>        StructField(&quot;isdebitcard&quot;, StringType(), True),<br>        StructField(&quot;debitcardnumber&quot;, StringType(), True)<br>    ])<br>)</pre><pre>extract_udf = udf(extract_account_items, schema)</pre><pre># Apply UDF to extract account items<br>df_with_items = df_valid.withColumn(&quot;account_items&quot;, extract_udf(&quot;account_data&quot;))</pre><pre># Explode each &lt;item&gt; into a row<br>df_exploded = df_with_items.withColumn(&quot;item&quot;, explode(&quot;account_items&quot;))</pre><h3>Step 4: Select Final Columns</h3><p>Now let’s select the original columns and exploded data for the final table.</p><pre>df_final = df_exploded.select(<br>    col(&quot;seq_no&quot;),<br>    col(&quot;customer_id&quot;),<br>    col(&quot;item.acc_no&quot;).alias(&quot;acc_no&quot;),<br>    col(&quot;item.isdebitcard&quot;).alias(&quot;isdebitcard&quot;),<br>    col(&quot;item.debitcardnumber&quot;).alias(&quot;debitcardnumber&quot;)<br>)</pre><h3>Step 5: Write Output Back to Oracle</h3><p>Finally, we write the clean, flattened data into the target Oracle table.</p><pre>df_final.write.jdbc(<br>    url=oracle_url,<br>    table=&quot;TARGET_TABLE_NAME&quot;,  # Replace with your target table name<br>    mode=&quot;append&quot;,  # Or &quot;overwrite&quot; based on requirement<br>    properties=properties<br>)</pre><h4>Catch1: Why Not Use xpath_string()?</h4><p>We might be tempted to use Spark’s xpath_string() for XML extraction — but it’s limited to shallow paths and doesn’t handle multiple &lt;item&gt; nodes cleanly. That’s why we went with ElementTree, which gives us full control.</p><p><strong>Catch2: Why not xpath()?</strong></p><p>The behaviour of xpath was giving null values for exploded columns.</p><p>Note: I have implemented the look-a-like code in my on-premises setup and ran the pyspark job using spark-submit. But if someone is using Azure Databricks or other cloud ETL platform, they might have other options to solve this.</p><p><strong>Sample XML Data (Not exact):</strong></p><pre>&lt;variable accountDetails&gt;<br>  &lt;item&gt;<br>    &lt;acc_no&gt;12345&lt;/acc_no&gt;<br>    &lt;isdebitcard&gt;true&lt;/isdebitcard&gt;<br>    &lt;debitcardnumber&gt;1111-2222-3333-4444&lt;/debitcardnumber&gt;<br>  &lt;/item&gt;<br>  &lt;item&gt;<br>    &lt;acc_no&gt;67890&lt;/acc_no&gt;<br>    &lt;isdebitcard&gt;false&lt;/isdebitcard&gt;<br>    &lt;debitcardnumber&gt;&lt;/debitcardnumber&gt;<br>  &lt;/item&gt;<br>&lt;/variable&gt;</pre><p>Let’s discuss in the comments if you have come across other ways to solve this problem apart from Python libraries in a Spark environment, since ElementTree will slow down the performance of the Spark job.</p><p>#DataEngineering #BigData #Spark #ETL #CloudComputing #DataPipeline #Optimization #Dataset #xml #SQL</p><p>If you found this post helpful, follow me on <a href="https://www.linkedin.com/in/monty-poddar-46b832142/"><strong>LinkedIn</strong></a> for more insights on Data Engineering! Let’s connect! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b59356dfacab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CAP Theorem in Data Engineering: The Hidden Trade-offs]]></title>
            <link>https://medium.com/@montypoddar08/cap-theorem-in-data-engineering-the-hidden-trade-offs-d0bbef35fe6d?source=rss-412283251922------2</link>
            <guid isPermaLink="false">https://medium.com/p/d0bbef35fe6d</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Monty Poddar]]></dc:creator>
            <pubDate>Fri, 21 Mar 2025 05:57:25 GMT</pubDate>
            <atom:updated>2025-03-21T05:57:25.989Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of <strong>distributed systems and data engineering</strong>, one fundamental principle shapes how we design databases and data pipelines — the <strong>CAP Theorem</strong>. Whether you’re working with <strong>real-time streaming, NoSQL databases, or cloud-based data lakes</strong>, understanding <strong>CAP trade-offs</strong> can help you make better architectural decisions.</p><p>But here’s the catch — <strong>CAP is not as simple as “choosing two out of three”</strong> anymore! This blog will uncover:</p><p>✅ <strong>What CAP Theorem is and why it matters</strong><br>✅ <strong>How it changed the way we design distributed systems</strong><br>✅ <strong>What trade-offs modern data engineering teams make</strong><br>✅ <strong>Why PACELC is an even better model for today’s architectures</strong><br>✅ <strong>How CAP applies to Medallion Architecture in data lakes</strong></p><p><strong>Let’s break it down! 👇</strong></p><h4>📌 What is the CAP Theorem?</h4><p>In <strong>2000, Eric Brewer</strong> introduced the <strong>CAP Theorem</strong>, which states that in any <strong>distributed data system</strong>, we can only achieve <strong>two out of three guarantees</strong>:</p><p>1️⃣ <strong>Consistency ©</strong> — All nodes always return the same, up-to-date data.<br>2️⃣ <strong>Availability (A)</strong> — The system responds to every request, even if some nodes fail.<br>3️⃣ <strong>Partition Tolerance (P)</strong> — The system continues to work despite network failures.</p><h4><strong>Key insight?</strong> 💡 If a network partition (P) happens (which is inevitable in distributed systems), you must <strong>choose between Consistency (CP) and Availability (AP).</strong></h4><h4>🔍 Why is CAP Theorem Important?</h4><p>Before CAP, traditional databases were built on <strong>ACID principles</strong>, ensuring strong consistency. But as <strong>big data, cloud computing, and global-scale applications</strong> emerged, engineers realized that:</p><h4>🔹 <strong>Distributed databases cannot guarantee all three properties at once.</strong><br>🔹 <strong>Failing to choose the right trade-offs leads to poor system performance.</strong><br>🔹 <strong>New database models (NoSQL, data lakes, real-time streaming) needed flexibility.</strong></h4><h4>How CAP Theorem Changed Everything</h4><p>Traditional <strong>relational databases (RDBMS) like MySQL and PostgreSQL</strong> focus on <strong>CA (Consistency + Availability)</strong> but fail under network partitions.</p><p>Enter <strong>modern distributed databases and NoSQL systems</strong>, which optimize for:<br>📌 <strong>CP (Consistency + Partition Tolerance)</strong> → Prioritizes correctness but may reject requests.<br>📌 <strong>AP (Availability + Partition Tolerance)</strong> → Guarantees response but may return stale data.</p><h4>This led to the rise of <strong>Apache Cassandra, DynamoDB, MongoDB, and Kafka</strong>, each making different CAP trade-offs.</h4><h4>🛠 CAP Theorem in Data Engineering</h4><p>CAP isn’t just for databases — it’s deeply embedded in <strong>data pipelines, streaming, and lakehouses</strong>.</p><p>🔹 <strong>Kafka (AP)</strong> — Guarantees availability but allows temporary inconsistencies (eventual consistency).<br>🔹 <strong>Delta Lake (CP)</strong> — Ensures consistency with ACID transactions, even in distributed environments.<br>🔹 <strong>Cassandra (AP)</strong> — Optimized for availability, allowing minor inconsistencies to resolve later.<br>🔹 <strong>Google Spanner (CP+CA Hybrid)</strong> — Balances consistency with global availability using advanced techniques.</p><h4>Let’s see how this applies to Medallion Architecture.</h4><h4>🏛 CAP Theorem in Medallion Architecture</h4><p>Medallion Architecture (Bronze, Silver, Gold layers) in data lakes follows <strong>different CAP trade-offs at each stage</strong>.</p><p>LayerCAP Trade-offKey Technologies<strong>Bronze (Raw Data)</strong>AP — Availability &amp; Partition ToleranceKafka, ADLS, S3 (eventual consistency)<strong>Silver (Processed Data)</strong>CP — Consistency &amp; Partition ToleranceApache Spark, Delta Lake (ACID transactions)<strong>Gold (Business-Ready Data)</strong>CA — Consistency &amp; AvailabilitySnowflake, Redshift, BigQuery (strong consistency)</p><p>🔹 <strong>Bronze Layer (AP)</strong> → Prioritizes ingesting data quickly, allowing temporary inconsistencies.<br>🔹 <strong>Silver Layer (CP)</strong> → Cleans, transforms, and ensures correctness before moving forward.<br>🔹 <strong>Gold Layer (CA)</strong> → Guarantees strong consistency for reporting &amp; analytics.</p><h4>🚀 <strong>By balancing CAP trade-offs across layers, we ensure a scalable, reliable data pipeline.</strong></h4><h4>🌟 Beyond CAP: The Rise of PACELC Theorem</h4><p>CAP Theorem only considers <strong>network failures</strong>, but <strong>PACELC</strong> extends it by addressing <strong>trade-offs even in normal conditions</strong>.</p><p><strong>PACELC states:</strong></p><ul><li><strong>If a partition (P) occurs → Choose Availability (A) or Consistency ©.</strong></li><li><strong>Else (E), in normal operation → Choose Low Latency (L) or Strong Consistency ©.</strong></li></ul><p>📌 <strong>Example:</strong></p><ul><li><strong>Cassandra (PA/EL)</strong> → Prioritizes <strong>availability</strong> under failures, but optimizes for <strong>low latency</strong> in normal cases.</li><li><strong>Google Spanner (PC/EC)</strong> → Prioritizes <strong>consistency</strong> under failures, but still maintains <strong>strong consistency</strong> at all times.</li></ul><h4>➡️ <strong>PACELC is more relevant today</strong> because it models real-world systems where we must choose between <strong>latency and consistency</strong>, not just during failures but <strong>all the time</strong>.</h4><h4>🎯 Final Takeaways</h4><p>🔸 <strong>CAP Theorem is fundamental for designing distributed data systems</strong> — you can’t have it all!<br>🔸 <strong>NoSQL, data lakes, and modern databases all optimize for different CAP trade-offs.</strong><br>🔸 <strong>Medallion Architecture strategically balances CAP across different data layers.</strong><br>🔸 <strong>PACELC extends CAP, considering trade-offs even in normal conditions.</strong></p><p>💡 <strong>Next time you design a data system, ask yourself: Do I need strong consistency, high availability, or partition tolerance?</strong></p><p>📢 <strong>What’s your experience handling CAP trade-offs in your data pipelines? Let’s discuss in the comments!</strong> 🚀</p><p>#DataEngineering #CAPTheorem #PACELC #BigData #MedallionArchitecture #DistributedSystems #SQL #NoSQL</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d0bbef35fe6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protecting PII Data with Data Masking]]></title>
            <link>https://medium.com/@montypoddar08/protecting-pii-data-with-data-masking-0d212e35ae26?source=rss-412283251922------2</link>
            <guid isPermaLink="false">https://medium.com/p/0d212e35ae26</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Monty Poddar]]></dc:creator>
            <pubDate>Sat, 08 Mar 2025 03:28:36 GMT</pubDate>
            <atom:updated>2025-03-08T03:28:36.519Z</atom:updated>
            <content:encoded><![CDATA[<p>In today’s data-driven world, protecting <strong>Personally Identifiable Information (PII)</strong> is <strong>not just a best practice — it’s a necessity.</strong> Whether you’re working with customer data, financial transactions, or healthcare records, ensuring privacy and security is critical to <strong>compliance</strong> (GDPR, CCPA) and <strong>trust.</strong></p><p>But how do we ensure that sensitive data is protected without compromising its analytical value? The answer: <strong>Data Masking within the Medallion Architecture.</strong></p><p>In this post, I’ll walk you through <strong>how to implement data masking in a structured data pipeline</strong> using SQL, ensuring data is both <strong>usable and secure.</strong></p><h4>Understanding the Medallion Architecture in Data Masking</h4><p>Medallion Architecture organizes data into three layers:</p><p>🔹 <strong>Bronze Layer (Raw Data)</strong> → Ingests data as-is, including PII.<br>🔹 <strong>Silver Layer (Cleaned &amp; Transformed Data)</strong> → Applies masking and anonymization.<br>🔹 <strong>Gold Layer (Business-Ready Data)</strong> → Ensures PII is fully protected while still providing insights.</p><p>Now, let’s dive into a <strong>real-world SQL implementation</strong> where we handle sensitive customer information such as <strong>emails, phone numbers, credit card details, and addresses.</strong></p><h4>Step 1: Bronze Layer (Raw Data Storage)</h4><p>The <strong>Bronze layer</strong> acts as a raw storage area where data is ingested directly from source systems. This includes <strong>unmasked</strong> customer data.</p><h4>Create a Bronze Table</h4><p>CREATE TABLE bronze.customers (<br> customer_id INT,<br> full_name STRING,<br> email STRING,<br> phone STRING,<br> credit_card_number STRING,<br> address STRING,<br> created_at TIMESTAMP<br>);</p><p><strong>Example Raw Data:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HarIAFlXkQEyOtnRi_rgvQ.png" /></figure><p><strong>Problem:</strong> This dataset contains <strong>PII</strong>, which can’t be exposed directly in reports or analytics.</p><h4>Step 2: Silver Layer (Apply Data Masking)</h4><p>The <strong>Silver layer</strong> is responsible for data transformation, including <strong>masking and encryption</strong> of sensitive fields.</p><h4>Create a Silver Table with Masked Data</h4><p>We apply <strong>various masking techniques</strong> such as:</p><p>✅ <strong>Partial Masking</strong> (e.g., hiding parts of emails and phone numbers)<br>✅ <strong>Nullification</strong> (removing highly sensitive information)<br>✅ <strong>Hashing</strong> (encrypting addresses for irreversible protection)</p><p>CREATE TABLE silver.customers_masked AS<br>SELECT<br> customer_id,<br> full_name,<br> CONCAT(LEFT(email, 3), ‘***@’, SPLIT_PART(email, ‘@’, 2)) AS masked_email,<br> CONCAT(‘XXX-XXX-’, RIGHT(phone, 4)) AS masked_phone,<br> CONCAT(LEFT(credit_card_number, 4), ‘-XXXX-XXXX-XXXX’) AS masked_credit_card,<br> SHA2(address, 256) AS hashed_address, — One-way encryption<br> created_at<br>FROM bronze.customers;</p><p><strong>Masked Data Example:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ko1xao8jjlDCuzwi1BladQ.png" /></figure><p>✅ <strong>Why hashing?</strong> Unlike encryption, hashing is irreversible, making it a great option for protecting sensitive fields while ensuring uniqueness.</p><h4>Step 3: Gold Layer (PII-Free Data for Business Use)</h4><p>The <strong>Gold layer</strong> ensures that PII is fully protected while still allowing for analysis and reporting.</p><h4>Create a Gold Table</h4><p>CREATE TABLE gold.customers_final AS<br>SELECT <br> customer_id,<br> full_name,<br> masked_email,<br> masked_phone,<br> ‘****-****-****-****’ AS obfuscated_credit_card, — Fully masked<br> created_at<br>FROM silver.customers_masked;</p><p><strong>Final Output (Fully Anonymized)</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*61zhxHIgcEgCu8tSboav3g.png" /></figure><p>📌 <strong>Why this works:</strong></p><ul><li><strong>Gold Layer removes any PII</strong>, ensuring it meets compliance standards.</li><li><strong>Still valuable for analytics</strong> — we retain important details while hiding sensitive information.</li></ul><h4>Key Takeaways</h4><p>🔹 <strong>Bronze Layer:</strong> Stores raw PII.<br>🔹 <strong>Silver Layer:</strong> Applies masking and encryption.<br>🔹 <strong>Gold Layer:</strong> Ensures no sensitive data is exposed.</p><h4>Benefits of This Approach:</h4><p>✅ <strong>Compliance with regulations</strong> (GDPR, CCPA)<br>✅ <strong>Minimal performance overhead</strong><br>✅ <strong>No impact on analytics</strong><br>✅ <strong>Security-first approach</strong></p><p>🚀 <strong>Final Thoughts</strong><br>Data masking isn’t just about compliance — it’s about ensuring that businesses can extract insights <strong>without putting users at risk.</strong></p><p>By implementing <strong>Medallion Architecture</strong>, we ensure <strong>data protection at scale</strong>, making our data pipelines both <strong>efficient and secure.</strong></p><p>💡 Have you faced similar data engineering challenges? Let me know in the comments! 🚀</p><p>#DataEngineering #BigData #Spark #Privacy #DataSecurity #ETL #CloudComputing #DataPipeline #Optimization #Dataset #PII #MedallionArchitecture #SQL</p><p>If you found this post helpful, follow me on <a href="https://www.linkedin.com/in/monty-poddar-46b832142/"><strong>LinkedIn</strong></a> for more insights on Data Engineering! Let’s connect! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0d212e35ae26" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Large and Small Data Sources in Data Engineering: A Complete Guide]]></title>
            <link>https://medium.com/@montypoddar08/handling-large-and-small-data-sources-in-data-engineering-a-complete-guide-75970da5028c?source=rss-412283251922------2</link>
            <guid isPermaLink="false">https://medium.com/p/75970da5028c</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[Monty Poddar]]></dc:creator>
            <pubDate>Sun, 16 Feb 2025 20:20:24 GMT</pubDate>
            <atom:updated>2025-02-16T20:20:24.523Z</atom:updated>
            <content:encoded><![CDATA[<p>In Data Engineering, we often deal with multiple data sources — some with <strong>huge datasets</strong> and others with <strong>small data files</strong>. When processing these datasets daily, we must efficiently handle partitioning, file sizes, and special cases like <strong>weekends and market holidays</strong>.</p><p>This blog will address <strong>five critical scenarios</strong> related to handling large and small data efficiently in Spark and provide <strong>optimized solutions with code snippets</strong>.</p><p>Let’s say we have multiple data sources, some source have large data and other source have small data. It contains daily data.<br><strong>Q1. </strong>🛠️<strong>Can you tell me how many number of files it will be written in each partition?</strong></p><p>When processing data in Spark, we need to understand <strong>how many files</strong> Spark will write for a given partition size.</p><p>📌 <strong>Scenario:</strong></p><ul><li>Spark <strong>writes one file per partition</strong> by default.</li><li>If a DataFrame has <strong>10 partitions</strong>, it will create <strong>10 files</strong> in the output directory.</li><li>If we use <strong>too many partitions for small data</strong>, we will end up with <strong>many tiny files</strong>, leading to <strong>inefficiency</strong>.</li></ul><p>✅ <strong>Solution:</strong> Control the number of partitions manually to avoid excessive small files.</p><h4>📌 Code Example</h4><pre>from pyspark.sql import SparkSession</pre><pre>spark = SparkSession.builder.appName(&quot;PartitionExample&quot;).getOrCreate()</pre><pre>data = [(i, f&quot;value_{i}&quot;) for i in range(100)]  # Sample data<br>df = spark.createDataFrame(data, [&quot;id&quot;, &quot;value&quot;])</pre><pre>df.repartition(5).write.mode(&quot;overwrite&quot;).parquet(&quot;path/to/output&quot;)</pre><p>🔹 This will create <strong>5 files</strong> in the output folder instead of the default <strong>200 partitions</strong>.</p><h4>Q 2. What happens when small datasets have too many partitions?</h4><p>By default, Spark creates <strong>200 shuffle partitions</strong> (spark.sql.shuffle.partitions = 200). However, if we are processing a <strong>small dataset</strong>, having <strong>200 partitions</strong> will result in <strong>very tiny files</strong>, which is inefficient.</p><p>📌 <strong>Scenario:</strong></p><ul><li>We receive <strong>daily data</strong> that is sometimes small.</li><li>If Spark uses <strong>200 partitions for small data</strong>, it will create <strong>200 small files</strong>, increasing metadata overhead.</li></ul><p>✅ <strong>Solution:</strong> Use .coalesce() to merge partitions dynamically and reduce small files.</p><h4>📌 Code Example</h4><pre>df = df.coalesce(1)  # Merge partitions to avoid small files<br>df.write.mode(&quot;overwrite&quot;).parquet(&quot;path/to/output&quot;)</pre><p>🔹 Now, instead of <strong>200 small files</strong>, Spark will write <strong>just 1 file</strong>, optimizing storage.</p><h4>Q 3. How many files will be written if we process 365 days of data using 200 partitions? (Assume Developer forgot to repartition)</h4><p>📌 <strong>Scenario:</strong></p><ul><li>We process <strong>daily data for 365 days</strong>.</li><li>Spark uses <strong>200 partitions per day</strong> by default.</li><li>The total number of files written will be:</li></ul><p>🧮 <strong>Files Written = 200 partitions/day × 365 days = 73,000 files</strong></p><p>🚨 <strong>Problem:</strong></p><ul><li>Writing <strong>73,000 files</strong> is <strong>inefficient</strong> for cloud storage.</li><li>Querying such a large number of small files will be <strong>slow and expensive</strong>.</li></ul><p>✅ <strong>Solution:</strong> Reduce the number of <strong><em>partitions dynamically</em></strong><em> </em>by <strong>grouping data by month instead of day</strong>.</p><p>📌 <strong>OR</strong>: Avoid excessive small files using <strong>coalesce or dynamic partition pruning</strong>.</p><pre># Reduce number of files per partition when writing data<br>df.repartition(50, &quot;date&quot;).write.partitionBy(&quot;date&quot;).parquet(&quot;path/to/output&quot;)</pre><h4>OR</h4><p>Reduce files to <strong>50 per day</strong> instead of <strong>200</strong>, reducing <strong>total files to 18,250 per year</strong>.</p><pre>df = df.withColumn(&quot;month&quot;, df[&quot;date&quot;].substr(0, 7))  # Extract YYYY-MM<br>df.write.partitionBy(&quot;month&quot;).mode(&quot;overwrite&quot;).parquet(&quot;path/to/output&quot;)</pre><p>🔹 Now, instead of <strong>365 partitions</strong>, we only have <strong>12 monthly partitions</strong>, reducing the number of files significantly.</p><h4>Q4. How can we handle weekend trading data when the volume is much lower?</h4><p>🚨 <strong>Problem</strong>: If you repartition based on weekend data, you <strong>impact weekday performance</strong>.</p><p>📌 <strong>Scenario:</strong></p><ul><li>Trading happens <strong>only on weekdays (Monday-Friday)</strong>.</li><li><strong>Saturday</strong> has <strong>very few transactions</strong> (only leftover trades from Friday).</li><li>If we keep <strong>fixed partitions</strong>, Saturday data will create <strong>too many small files</strong>.</li><li>If we reduce partitions for Saturday, it might impact <strong>weekday performance</strong>.</li></ul><p>✅ <strong>Solution:</strong> Dynamically adjust partitions:</p><ul><li><strong>Weekdays → Keep default partitions</strong></li><li><strong>Saturday → Reduce partitions to avoid small files</strong><br>📌 <strong>Fix</strong>: <strong>Dynamically merge small partitions only on weekends</strong></li><li>Use <strong>Dynamic Partition Coalescing</strong></li><li><strong>Adaptive Query Execution (AQE) handles this automatically</strong></li></ul><h4>📌 Code Example</h4><pre>from pyspark.sql.functions import dayofweek</pre><pre>df = df.withColumn(&quot;day_of_week&quot;, dayofweek(&quot;date&quot;))  # Extract weekday number</pre><pre># Weekday data: Keep default partitions<br>weekday_df = df.filter(df.day_of_week.between(2, 6))  # Monday-Friday</pre><pre># Saturday data: Merge partitions to avoid small files<br>saturday_df = df.filter(df.day_of_week == 7).coalesce(1)  # Reduce partitions on Saturdays</pre><pre># Write both datasets<br>weekday_df.write.partitionBy(&quot;date&quot;).parquet(&quot;path/to/output&quot;)<br>saturday_df.write.partitionBy(&quot;date&quot;).parquet(&quot;path/to/output&quot;)</pre><p>🔹 Now, <strong>weekdays</strong> retain full partitioning, but <strong>Saturdays</strong> automatically reduce to <strong>1 file</strong>, optimizing storage.</p><h4>Q5. How can we handle market holidays dynamically without a predefined holiday table?</h4><p>📌 <strong>Scenario:</strong></p><ul><li>Market holidays are <strong>not fixed every year</strong> (e.g., <strong>Diwali, Christmas, Martin Luther King Jr. Day</strong>).</li><li>We <strong>cannot assume</strong> that a day with fewer transactions is a holiday.</li><li>Manually maintaining a holiday calendar is <strong>not scalable</strong>.</li></ul><p>✅ <strong>Best Solution:</strong> Fetch holiday data dynamically from an <strong>official market API</strong> and adjust partitions accordingly.</p><h3>📌 Optimized Code: Fetch Holiday Data from API</h3><pre>import requests<br>from pyspark.sql.functions import col</pre><pre>def get_holidays():<br>    url = &quot;https://api.tradinghours.com/v1/market-holidays&quot;<br>    params = {&quot;market&quot;: &quot;NYSE&quot;, &quot;year&quot;: &quot;2025&quot;, &quot;api_key&quot;: &quot;your_api_key&quot;}<br>    response = requests.get(url, params=params)<br>    return [h[&quot;date&quot;] for h in response.json()[&quot;holidays&quot;]]</pre><pre># Fetch holiday list dynamically<br>holiday_dates = get_holidays()</pre><pre># Convert to Spark DataFrame<br>holiday_df = spark.createDataFrame([(d,) for d in holiday_dates], [&quot;holiday_date&quot;])</pre><pre># Load daily transactions data<br>df = spark.read.parquet(&quot;path/to/daily_data&quot;)</pre><pre># Mark holidays dynamically<br>df = df.join(holiday_df, df.date == holiday_df.holiday_date, &quot;left_outer&quot;) \<br>       .withColumn(&quot;is_holiday&quot;, col(&quot;holiday_date&quot;).isNotNull())</pre><pre># Reduce partitions only on holidays<br>holiday_df = df.filter(col(&quot;is_holiday&quot;) == True).coalesce(1)<br>normal_df = df.filter(col(&quot;is_holiday&quot;) == False)</pre><pre># Write the data efficiently<br>holiday_df.write.partitionBy(&quot;date&quot;).parquet(&quot;path/to/output&quot;)<br>normal_df.write.partitionBy(&quot;date&quot;).parquet(&quot;path/to/output&quot;)</pre><p>🔹 This <strong>automatically detects market holidays</strong> and <strong>reduces partitions only for those days</strong> — fully optimized!</p><h4>🔥 Conclusion</h4><p>Efficiently handling large and small data sources requires <strong>smart partitioning</strong> and <strong>dynamic optimization</strong>. By leveraging <strong>Spark optimizations</strong>, <strong>real-time API calls</strong>, and <strong>intelligent partitioning strategies</strong>, we can:<br>✅ Reduce <strong>storage costs</strong><br>✅ Improve <strong>query performance</strong><br>✅ Handle <strong>holidays and weekends efficiently</strong></p><p>💡 Have you faced similar data engineering challenges? Let me know in the comments! 🚀</p><p>#DataEngineering #BigData #Spark #ApacheSpark #ETL #CloudComputing #DataPipeline #Optimization #Dataset</p><p>If you found this post helpful, follow me on <a href="https://www.linkedin.com/in/monty-poddar-46b832142/"><strong>LinkedIn</strong></a> for more insights on Data Engineering! Let’s connect! 😊</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=75970da5028c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hidden Complexities of Data Modeling (Beyond Star & Snowflake)]]></title>
            <link>https://medium.com/@montypoddar08/hidden-complexities-of-data-modeling-beyond-star-snowflake-e7359f8b0925?source=rss-412283251922------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7359f8b0925</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[data-modeling]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Monty Poddar]]></dc:creator>
            <pubDate>Mon, 03 Feb 2025 20:05:34 GMT</pubDate>
            <atom:updated>2025-02-03T20:05:34.427Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>🚀 <strong>Most discussions on Data Modeling stop at “Star vs. Snowflake Schema” — but the real world isn’t that simple!</strong></blockquote><p>If you’ve ever worked on large-scale Data Engineering projects, you’ve likely faced <strong>hybrid models, schema evolution, and real-time requirements</strong> that traditional approaches don’t fully address.</p><p>🚀 <strong>Data Modeling is NOT a one-size-fits-all approach!</strong></p><ul><li><strong>Kimball (Dimensional Modeling)</strong> is great for <strong>analytics &amp; reporting</strong> but struggles with <strong>historical tracking</strong>.</li><li><strong>Data Vault</strong> is perfect for <strong>historical tracking &amp; scalability</strong>, but it’s not optimized for <strong>BI queries</strong>.</li><li><strong>Hybrid modeling</strong> combines the best of both worlds!</li></ul><p>Let’s break this down with <strong>real-life examples</strong></p><h4>The Myth: Star Schema Solves Everything</h4><p>Sure, <strong>Star Schema</strong> (fact and dimension tables) is great for analytical queries, but:<br>🔹 It struggles with <strong>complex relationships</strong> and many-to-many joins<br>🔹 Changes to dimensions (e.g., slowly changing dimensions) can get messy<br>🔹 <strong>ETL complexity increases</strong> with denormalized data</p><h4>The Hidden Reality: Hybrid Data Models</h4><p>💡 <strong>Real-world scenarios require combining multiple modeling techniques</strong></p><ul><li><strong>Data Vault</strong> for <strong>historical tracking &amp; auditability</strong></li><li><strong>Dimensional Modeling (Kimball)</strong> for <strong>BI &amp; Analytics</strong></li><li><strong>Wide Tables (Denormalized)</strong> for <strong>Machine Learning feature stores</strong></li></ul><p>📊 <strong>Example: Data Vault + Kimball Hybrid Model</strong><br>Imagine you’re building a <strong>customer data platform</strong> with <strong>historical tracking &amp; fast analytics</strong>.</p><ul><li><strong>Data Vault</strong> stores raw <strong>immutable customer events</strong> (good for compliance/audit).</li><li><strong>Kimball Dimensional Model</strong> creates a <strong>Customer Dimension Table</strong> for analytics.</li></ul><h4>1️⃣ What is Data Vault<strong>(Raw History Storage)</strong>?</h4><p>🔹 A <strong>flexible, scalable data modeling approach</strong> designed for <strong>historical tracking</strong> &amp; <strong>data lineage</strong>.<br>🔹 Uses three core components:</p><ul><li><strong>Hubs</strong> (Unique business entities like Customers, Products, Orders)</li><li><strong>Satellites</strong> (Attributes that track changes over time)</li><li><strong>Links</strong> (Relationships between Hubs)</li></ul><p>✅ <strong>Best for:</strong> Large-scale data warehouses, regulatory compliance (e.g., finance, healthcare).</p><blockquote>📌 Real-Life Example: E-Commerce Customer Data</blockquote><p>Imagine an e-commerce company wants to track <strong>customer details historically</strong> while keeping <strong>relationships intact</strong>.</p><pre>CREATE TABLE customer_hub (<br>    customer_id STRING PRIMARY KEY,<br>    created_at TIMESTAMP<br>);</pre><pre>CREATE TABLE customer_satellite (<br>    customer_id STRING REFERENCES customer_hub,<br>    customer_name STRING,<br>    customer_email STRING,<br>    updated_at TIMESTAMP<br>);</pre><pre>-- Link Table: Tracks relationships (customer orders) <br>CREATE TABLE customer_order_link <br>(customer_id STRING REFERENCES customer_hub,<br>order_id STRING,<br>order_date TIMESTAMP);</pre><p>🔹 <strong>Benefits of Data Vault:</strong><br>✅ <strong>Tracks history without data loss</strong><br>✅ <strong>Highly scalable &amp; works well with big data</strong><br>✅ <strong>Ideal for schema evolution</strong></p><p>🔹 <strong>Limitations:</strong><br>❌ <strong>Not optimized for fast querying</strong> (joins needed)<br>❌ <strong>Requires transformation to be useful for BI tools</strong></p><h4><strong>2️⃣ What is Kimball Model (</strong>Dimensional Modeling For Analytics<strong>)?</strong></h4><pre>CREATE TABLE customer_dim AS<br>SELECT <br>    h.customer_id,<br>    s.customer_name,<br>    s.customer_email,<br>    s.updated_at<br>FROM customer_hub h<br>JOIN customer_satellite s ON h.customer_id = s.customer_id;</pre><p>🔹 A <strong>denormalized approach for analytics &amp; reporting</strong><br>🔹 Uses <strong>Fact Tables</strong> (numeric events like Sales, Orders) &amp; <strong>Dimension Tables</strong> (descriptive attributes like Customer, Product)</p><p>✅ <strong>Best for:</strong> Business Intelligence (BI), dashboards, ad-hoc reporting</p><h4>📌 Real-Life Example: Customer Analytics</h4><p>Let’s say the marketing team wants to analyze <strong>customer spending trends</strong> in an easy-to-query format.</p><h4>🛠 Kimball Model Example: Customer Dimension &amp; Fact Table</h4><pre>-- Dimension Table: Customer Details<br>CREATE TABLE dim_customer AS<br>SELECT <br>    h.customer_id,<br>    s.customer_name,<br>    s.customer_email,<br>    MAX(s.updated_at) AS last_updated<br>FROM customer_hub h<br>JOIN customer_satellite s ON h.customer_id = s.customer_id<br>GROUP BY h.customer_id, s.customer_name, s.customer_email;</pre><pre>-- Fact Table: Customer Purchases<br>CREATE TABLE fact_sales (<br>    order_id STRING,<br>    customer_id STRING REFERENCES dim_customer,<br>    order_amount DECIMAL(10,2),<br>    order_date TIMESTAMP<br>);</pre><p>🔹 <strong>Benefits of Kimball:</strong><br>✅ <strong>Fast analytical queries</strong> (no complex joins needed)<br>✅ <strong>Well-suited for BI tools &amp; dashboards</strong><br>✅ <strong>Simple and business-friendly schema</strong></p><p>🔹 <strong>Limitations:</strong><br>❌ <strong>Harder to track history &amp; changes</strong><br>❌ <strong>Not designed for large-scale schema evolution</strong></p><p><strong>Why is this useful?</strong><br>✅ Data Vault ensures <strong>full history</strong> of customer changes<br>✅ Kimball schema speeds up <strong>reporting &amp; analytics</strong><br>✅ You get <strong>best of both worlds</strong>: historical tracking + fast queries</p><h4>3️⃣ The Hybrid Approach: Best of Both Worlds</h4><p>🔹 Use <strong>Data Vault</strong> for <strong>storing raw, historical data</strong><br>🔹 Use <strong>Kimball</strong> for <strong>reporting &amp; analytics</strong></p><h4>📌 Real-Life Hybrid Example: Customer Insights Platform</h4><p>A <strong>large retail company</strong> wants:<br>1️⃣ A <strong>Data Vault</strong> for <strong>historical tracking &amp; compliance</strong><br>2️⃣ A <strong>Kimball model</strong> for <strong>BI reporting &amp; dashboards</strong></p><p><strong>How does it work?</strong><br>✅ <strong>Step 1:</strong> Store raw customer &amp; order data in <strong>Data Vault</strong>.<br>✅ <strong>Step 2:</strong> Periodically <strong>transform &amp; load</strong> it into a <strong>Kimball model</strong> for reporting.</p><h4>🛠 Hybrid ETL Pipeline in PySpark</h4><pre>from pyspark.sql import SparkSession<br>spark = SparkSession.builder.appName(&quot;DataVaultToKimball&quot;).getOrCreate()</pre><pre># Load Data Vault Customer Hub &amp; Satellite<br>customer_hub = spark.read.format(&quot;delta&quot;).load(&quot;/data_vault/customer_hub&quot;)<br>customer_satellite = spark.read.format(&quot;delta&quot;).load(&quot;/data_vault/customer_satellite&quot;)</pre><pre># Transform into Kimball Dimensional Model<br>dim_customer = customer_hub.join(customer_satellite, &quot;customer_id&quot;) \.select(&quot;customer_id&quot;, &quot;customer_name&quot;, &quot;customer_email&quot;) \.distinct()</pre><pre># Write to Data Warehouse (Kimball)<br>dim_customer.write.format(&quot;parquet&quot;).mode(&quot;overwrite&quot;).save(&quot;/data_warehouse/dim_customer&quot;)</pre><h4>4️⃣ The New Reality: Real-Time &amp; Streaming Models</h4><p>Traditional modeling assumes <strong>batch ETL</strong>, but in <strong>modern data pipelines</strong>, we need <strong>real-time ingestion</strong>.</p><p>✅ <strong>Streaming architectures</strong> require different approaches like <strong>Lambda or Kappa architecture</strong><br>✅ <strong>Data Lakes</strong> store raw events, while <strong>Lakehouses (Delta Lake)</strong> enable structured queries<br>✅ <strong>Schema evolution</strong> needs to be handled dynamically (tools like Iceberg, Hudi, or Delta)</p><p>📌 <strong>Example: Real-time Customer Model using Delta Lake</strong></p><pre>from pyspark.sql import SparkSession<br>from delta.tables import DeltaTable</pre><pre>spark = SparkSession.builder.appName(&quot;DataModeling&quot;).getOrCreate()</pre><pre># Load new customer events from Kafka<br>customer_events = spark.readStream.format(&quot;kafka&quot;).option(&quot;subscribe&quot;, &quot;customer_updates&quot;).load()</pre><pre># Write to Delta Table (ensures schema enforcement &amp; ACID transactions)<br>customer_events.writeStream.format(&quot;delta&quot;).option(&quot;checkpointLocation&quot;, &quot;/delta/checkpoints/&quot;).start(&quot;/delta/customer&quot;)</pre><h4>🔍 Final Thoughts: Data Modeling Is Not One-Size-Fits-All</h4><p>✅ <strong>Mixing modeling techniques</strong> (Star, Data Vault, Wide Tables) helps balance <strong>performance &amp; flexibility</strong><br>✅ <strong>Streaming-first architectures</strong> require <strong>different modeling approaches</strong><br>✅ <strong>Schema evolution is inevitable — choose formats that support it!</strong></p><p>What <strong>hybrid modeling challenges</strong> have you faced in your Data Engineering journey? Let’s discuss! 👇💬</p><p><a href="https://www.linkedin.com/in/monty-poddar-46b832142">https://www.linkedin.com/in/monty-poddar-46b832142</a></p><p>#DataEngineering #DataModeling #BigData #SQL #DeltaLake #Kafka #Analytics 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7359f8b0925" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SCD vs. CDC]]></title>
            <link>https://medium.com/@montypoddar08/scd-vs-cdc-6d24f73ed988?source=rss-412283251922------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d24f73ed988</guid>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Monty Poddar]]></dc:creator>
            <pubDate>Tue, 21 Jan 2025 14:34:49 GMT</pubDate>
            <atom:updated>2025-01-21T14:34:49.319Z</atom:updated>
            <content:encoded><![CDATA[<h3>SCD vs. CDC in Data Engineering — When to Use Them? 🚀</h3><p>As data engineers, we often encounter the challenge of handling <strong>data changes</strong> in ETL pipelines. Two widely used techniques to manage such changes are <strong>SCD (Slowly Changing Dimensions)</strong> and <strong>CDC (Change Data Capture)</strong>. But when should we use them, and how do they differ? Let’s explore!</p><h3>What is SCD (Slowly Changing Dimensions)?</h3><p>SCD focuses on managing <strong>historical data</strong> in dimensional tables. It tracks changes over time, making it ideal for slowly evolving data (e.g., customer profiles, product categories).</p><h4>Types of SCD</h4><p>1️⃣ <strong>SCD Type 1</strong>: Overwrite the old data (no history).<br>2️⃣ <strong>SCD Type 2</strong>: Maintain history by creating additional records.<br>3️⃣ <strong>SCD Type 3</strong>: Track limited history in predefined columns.</p><h4>Use Case</h4><p>📌 <strong>Scenario</strong>: Tracking changes in customer addresses.</p><p><strong>Example</strong>: A customer moves from NYC to LA. SCD ensures you retain both historical and current addresses (SCD Type 2).</p><h4>Sample Code (PySpark: SCD Type 2)</h4><pre>from pyspark.sql.functions import col, lit, current_timestamp</pre><pre># Current dimension table<br>dim_table = spark.read.format(&quot;delta&quot;).load(&quot;path/to/dim_table&quot;)</pre><pre># Incoming data<br>incoming_data = spark.read.format(&quot;delta&quot;).load(&quot;path/to/new_data&quot;)</pre><pre># Join to detect changes<br>changes = incoming_data.join(dim_table, &quot;customer_id&quot;, &quot;left_outer&quot;) \<br>    .filter((dim_table[&quot;address&quot;] != incoming_data[&quot;address&quot;]) | (dim_table[&quot;customer_id&quot;].isNull()))</pre><pre># Mark old records as inactive<br>dim_table_updates = dim_table.withColumn(&quot;is_active&quot;, lit(False)) \<br>    .withColumn(&quot;end_date&quot;, current_timestamp()) \<br>    .filter(dim_table[&quot;customer_id&quot;].isin(changes[&quot;customer_id&quot;]))</pre><pre># Add new records<br>new_records = changes.withColumn(&quot;is_active&quot;, lit(True)) \<br>    .withColumn(&quot;start_date&quot;, current_timestamp()) \<br>    .withColumn(&quot;end_date&quot;, lit(None))</pre><pre># Merge<br>updated_dim_table = dim_table_updates.union(new_records)<br>updated_dim_table.write.format(&quot;delta&quot;).mode(&quot;overwrite&quot;).save(&quot;path/to/dim_table&quot;)</pre><h3>What is CDC (Change Data Capture)?</h3><p>CDC focuses on <strong>capturing and processing incremental changes</strong> in real-time or near real-time. It’s perfect for applications that need <strong>up-to-date information</strong> (e.g., analytics dashboards, data replication).</p><h4>Techniques for CDC</h4><p>1️⃣ <strong>Log-Based CDC</strong>: Tracks changes in the database log.<br>2️⃣ <strong>Table Comparison</strong>: Compares snapshots of source tables.<br>3️⃣ <strong>Trigger-Based CDC</strong>: Uses triggers to capture changes.</p><h4>Use Case</h4><p>📌 <strong>Scenario</strong>: Real-time syncing of transactional data for analytics.</p><p><strong>Example</strong>: As orders are placed in an e-commerce system, CDC ensures the data is instantly available in the reporting dashboard.</p><h4>Sample Code (Kafka + PySpark: Log-Based CDC)</h4><pre>from pyspark.sql.functions import from_json, col<br>from pyspark.sql.types import StructType, StructField, StringType, TimestampTy</pre><pre># Kafka topic for CDC<br>cdc_topic = &quot;order_changes&quot;</pre><pre># Define schema for CDC events<br>cdc_schema = StructType([<br>    StructField(&quot;order_id&quot;, StringType(), True),<br>    StructField(&quot;status&quot;, StringType(), True),<br>    StructField(&quot;updated_at&quot;, TimestampType(), True)<br>])</pre><pre># Read from Kafka<br>cdc_stream = spark.readStream.format(&quot;kafka&quot;) \<br>    .option(&quot;kafka.bootstrap.servers&quot;, &quot;broker:9092&quot;) \<br>    .option(&quot;subscribe&quot;, cdc_topic) \<br>    .load()</pre><pre># Parse CDC events<br>parsed_stream = cdc_stream.select(from_json(col(&quot;value&quot;).cast(&quot;string&quot;), cdc_schema).alias(&quot;data&quot;)).select(&quot;data.*&quot;)</pre><pre># Write to a Delta table<br>parsed_stream.writeStream \<br>    .format(&quot;delta&quot;) \<br>    .option(&quot;checkpointLocation&quot;, &quot;path/to/checkpoints&quot;) \<br>    .outputMode(&quot;append&quot;) \<br>    .start(&quot;path/to/delta_table&quot;)</pre><h3>When to Use SCD vs. CDC?</h3><p><strong>SCD</strong> Use Case (Retail):</p><p>Historical tracking of changes,Batch updates from a CRM, ETL tools or batch pipelines (e.g., PySpark), Historical data in a dimensional table</p><p><strong>CDC</strong> Use Case (E-commerce): Real-time incremental updates, Change logs from MySQL database, Streaming tools (e.g., Kafka, Spark), Real-time data powering live dashboards</p><h3>Final Thoughts</h3><p>Choosing between SCD and CDC depends on your use case:</p><ul><li>Go for <strong>SCD</strong> when historical tracking is critical.</li><li>Choose <strong>CDC</strong> for real-time updates and incremental changes.</li></ul><p>Both techniques are essential tools in a data engineer’s arsenal, enabling efficient data management and delivery.</p><p>💡 What challenges have you faced implementing SCD or CDC in your pipelines? Let’s discuss in the comments! 🔥</p><p>On my Linkedin <a href="https://www.linkedin.com/in/monty-poddar-46b832142/">https://www.linkedin.com/in/monty-poddar-46b832142/</a></p><p><strong>#DataEngineering #BigData #ETL #CDC #SCD #RealTimeAnalytics #DataPipelines</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d24f73ed988" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Spark Executor Failures]]></title>
            <link>https://medium.com/@montypoddar08/understanding-spark-executor-failures-b6b706805092?source=rss-412283251922------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6b706805092</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[cluster]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Monty Poddar]]></dc:creator>
            <pubDate>Tue, 07 Jan 2025 19:46:09 GMT</pubDate>
            <atom:updated>2025-01-07T19:49:26.143Z</atom:updated>
            <content:encoded><![CDATA[<p>𝐖𝐡𝐚𝐭 𝐇𝐚𝐩𝐩𝐞𝐧𝐬 𝐖𝐡𝐞𝐧 𝐚 𝐒𝐩𝐚𝐫𝐤 𝐄𝐱𝐞𝐜𝐮𝐭𝐨𝐫 𝐅𝐚𝐢𝐥𝐬?</p><p>🚀 𝐃𝐚𝐭𝐚 𝐄𝐧𝐠𝐢𝐧𝐞𝐞𝐫𝐢𝐧𝐠 𝐈𝐧𝐬𝐢𝐠𝐡𝐭𝐬 🚀</p><p>Have you ever wondered what happens when a 𝑺𝒑𝒂𝒓𝒌 𝑬𝒙𝒆𝒄𝒖𝒕𝒐𝒓 𝒇𝒂𝒊𝒍𝒔 during a job execution? Failures are inevitable in distributed systems, but Spark’s design ensures that your jobs don’t crash because of them. Let’s break it down:</p><p>🔍 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐚𝐧 𝐄𝐱𝐞𝐜𝐮𝐭𝐨𝐫?</p><p>An executor is a distributed worker process responsible for executing tasks and storing intermediate data for your Spark application. It’s where the magic of parallelism happens! But what if an executor fails?</p><p>💡 𝐖𝐡𝐞𝐧 𝐚𝐧 𝐄𝐱𝐞𝐜𝐮𝐭𝐨𝐫 𝐅𝐚𝐢𝐥𝐬:</p><p>1️⃣ Spark detects the failure and reruns the failed tasks on another available executor.</p><p>2️⃣ If no executors are available, it tries to reschedule the tasks to other nodes in the cluster.</p><p>3️⃣ For 𝐜𝐚𝐜𝐡𝐞𝐝 𝐝𝐚𝐭𝐚, it reloads the lost partitions from the source or recomputes them from lineage.</p><p>🔄 𝐇𝐨𝐰 𝐌𝐚𝐧𝐲 𝐅𝐚𝐢𝐥𝐮𝐫𝐞𝐬 𝐀𝐫𝐞 𝐀𝐜𝐜𝐞𝐩𝐭𝐚𝐛𝐥𝐞?</p><p>Spark provides built-in fault tolerance! You can control task retry behavior using configurations like spark.task.maxFailures (default is 4 retries per task).For executor failures, the job will continue as long as the cluster has enough resources to rerun tasks.</p><p>📉 𝐖𝐡𝐞𝐧 𝐃𝐨 𝐓𝐡𝐢𝐧𝐠𝐬 𝐆𝐨 𝐒𝐨𝐮𝐭𝐡?</p><p>If executor failures exceed the cluster’s ability to handle retries (e.g., insufficient healthy nodes), the job fails. This can be managed by ensuring a robust cluster setup and configuring dynamic allocation (spark.dynamicAllocation.enabled) to scale resources when needed.</p><p>✨ 𝐖𝐡𝐲 𝐃𝐨𝐞𝐬 𝐓𝐡𝐢𝐬 𝐌𝐚𝐭𝐭𝐞𝐫?</p><p>Understanding Spark’s fault tolerance is key for building resilient data pipelines. Whether you’re processing petabytes of data or orchestrating real-time streams, knowing these details helps you design more reliable systems.</p><h3>How the Number of Executors is Calculated</h3><p>The number of executors is typically calculated based on:</p><ol><li><strong>Cluster Resources</strong>: Total cores and memory available in the cluster.</li><li><strong>Executor Configuration</strong>: Resources allocated per executor (executor-cores and executor-memory).</li><li><strong>Task Parallelism</strong>: The number of tasks your job requires, determined by input data splits.</li></ol><h3>Key Parameters for Executor Calculation</h3><ul><li><strong>Total Cores in Cluster</strong>: cluster_cores = nodes * cores_per_node</li><li><strong>Total Executors</strong>: total_executors = cluster_cores / executor_cores</li><li><strong>Memory per Executor</strong>: Set based on the workload, keeping space for overhead.</li></ul><h4>Example Scenario</h4><h4>Cluster Setup:</h4><ul><li><strong>Nodes</strong>: 4</li><li><strong>Cores per Node</strong>: 16</li><li><strong>Memory per Node</strong>: 64GB</li></ul><h4>Executor Configuration:</h4><ul><li><strong>Cores per Executor</strong>: 4</li><li><strong>Memory per Executor</strong>: 16GB</li></ul><h4>Input File:</h4><ul><li>Large file: 1TB, split into <strong>256 partitions</strong>.</li></ul><h4>Calculation:</h4><ul><li><strong>Cluster Total Cores</strong>: 4 nodes × 16 cores = <strong>64 cores</strong>.</li><li><strong>Executors per Node</strong>: 16 cores / 4 cores per executor = 4 executors.</li><li><strong>Total Executors</strong>: 4 executors per node × 4 nodes = 16 executors.</li><li><strong>Tasks per Executor</strong>: Executors process tasks based on partitions assigned. If we have 256 partitions and 16 executors:</li><li>256 tasks / 16 executors = 16 tasks per executor</li></ul><h3>Handling Executor Failure</h3><p>If one executor fails, Spark handles it as follows:</p><ol><li><strong>Task Rescheduling</strong>: Tasks assigned to the failed executor are <strong>rescheduled</strong> to other available executors.</li><li><strong>Recomputation from Lineage</strong>:</li></ol><ul><li>Spark leverages its <strong>DAG lineage</strong> to recompute lost data or tasks.</li><li>For cached data, Spark reloads the required partitions.</li></ul><p><strong>3. Retries</strong>:</p><ul><li>Spark retries tasks up to a configurable number of times (spark.task.maxFailures, default is 4).</li></ul><p><strong>4. Impact on Execution</strong>:</p><ul><li>If the cluster has sufficient executors, tasks are redistributed seamlessly.</li><li>If resource shortage arises (e.g., too many executor failures), the job may fail.</li></ul><h3>Example of Executor Failure</h3><h4>Scenario:</h4><ul><li>Task Distribution:</li><li><strong>File</strong>: 1TB split into 256 partitions.</li><li><strong>Executors</strong>: 16 executors, each handling 16 tasks.</li></ul><h4>Failure Event:</h4><ul><li>One executor fails (handles 16 tasks).</li><li>Tasks from the failed executor are redistributed among the remaining 15 executors.</li></ul><h4>Retry Process:</h4><ul><li><strong>Step 1</strong>: Tasks from the failed executor are reassigned.</li><li><strong>Step 2</strong>: If a task fails repeatedly (exceeding spark.task.maxFailures), the job fails.</li><li><strong>Step 3</strong>: If successful, the job completes with minor delays.</li></ul><h3>Executor Failure Recovery</h3><ol><li><strong>Dynamic Resource Allocation</strong>:</li></ol><ul><li>If enabled (spark.dynamicAllocation.enabled), Spark can request additional executors if required.</li></ul><p><strong>2. Checkpointing</strong>:</p><ul><li>If configured, checkpoints avoid recomputation from scratch.</li></ul><p><strong>3. Optimizations</strong>:</p><ul><li>Set spark.speculation to allow slow-running tasks to be re-executed on other nodes.</li></ul><h3>Visualizing the Flow</h3><ol><li><strong>Driver</strong>: Manages the Spark context, DAG, and task scheduling.</li></ol><ul><li>Sends tasks to executors.</li><li>Monitors executor health.</li></ul><p><strong>2. Executors</strong>: Execute tasks and report progress back to the driver.</p><h3>Impact of Executor Failure</h3><p><strong>Component Impact:</strong></p><p><strong>Driver: </strong>No impact unless the driver itself fails (driver failure halts the job).</p><p><strong>Executor Failure: </strong>Slows down execution but can recover if resources are available.</p><p><strong>Insufficient Nodes: </strong>If resources aren’t available, tasks cannot be rescheduled, and the job fails.</p><p>👨‍💻 𝐖𝐡𝐚𝐭 𝐀𝐫𝐞 𝐘𝐨𝐮𝐫 𝐓𝐡𝐨𝐮𝐠𝐡𝐭𝐬?</p><p>Have you experienced Spark executor failures? How did you handle them? Let’s discuss how we can design for resilience in distributed computing. Drop your insights in the comments! 💬</p><p>#DataEngineering #ApacheSpark #DistributedSystems #DataPipelines #ResilienceInTech #Spark</p><p>If you like the content and want to share your thoughts, Please reach out to me on Linkedin: <a href="https://www.linkedin.com/in/monty-poddar-46b832142"><em>https://www.linkedin.com/in/monty-poddar-46b832142</em></a></p><p><strong>Happy Learning !</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6b706805092" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clusters vs Pools]]></title>
            <link>https://medium.com/@montypoddar08/clusters-vs-pools-d531ef2209bf?source=rss-412283251922------2</link>
            <guid isPermaLink="false">https://medium.com/p/d531ef2209bf</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[clustering]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[blog]]></category>
            <dc:creator><![CDATA[Monty Poddar]]></dc:creator>
            <pubDate>Wed, 25 Dec 2024 07:46:03 GMT</pubDate>
            <atom:updated>2024-12-25T07:46:03.276Z</atom:updated>
            <content:encoded><![CDATA[<p>In data engineering, terms like <strong>clusters</strong> and <strong>pools</strong> are frequently mentioned. While these concepts may sound intimidating to beginners, they are foundational to understanding how data platforms like Databricks, Azure Synapse, and Azure Data Factory operate. In this blog, I’ll explain the differences between clusters and pools, explain their roles in these tools, and share why they matter to data engineers.</p><p><strong>Clusters</strong> and <strong>pools</strong> describe resources used for computation, but they serve different purposes.</p><ul><li><strong>Clusters</strong>: Think of clusters as <strong>workhorses</strong>. They are groups of interconnected machines (nodes) that run your computations or jobs.</li><li>Clusters are where your code or data processing logic is executed. They provide the computational power required to handle big data workloads.</li><li><strong>Pools</strong>: Pools are like <strong>waiting areas for resources</strong>. They manage pre-configured compute nodes to reduce startup times when creating a cluster.</li><li>Pools save time and costs by having ready-to-use compute resources, which can quickly be assigned to clusters when needed.</li></ul><h3>How Clusters and Pools Differ Across Platforms</h3><h4>1. Databricks</h4><ul><li><strong>Clusters</strong>: Databricks clusters are used to execute Spark jobs. They come in two flavors:</li><li><strong>Interactive Clusters</strong>: Used for ad-hoc data exploration and development.</li><li><strong>Job Clusters</strong>: Created for running a single job and terminated after completion.</li></ul><p>Databricks clusters are highly customizable, allowing you to specify the number of workers, node type, and Spark configurations.</p><ul><li><strong>Pools</strong>: Pools in Databricks reduce the startup time of clusters by maintaining a set of idle nodes.</li><li>When you create a cluster using a pool, it doesn’t need to wait for new VMs to be provisioned. Instead, it grabs an available node from the pool.</li><li>This is particularly useful in reducing costs for environments where clusters are frequently started and stopped.</li></ul><h4>2. Azure Synapse Analytics</h4><ul><li><strong>Clusters</strong>: In Synapse, clusters are tied to <strong>Synapse Spark pools</strong>. These clusters allow you to perform distributed data processing using Spark.</li></ul><p>Synapse clusters are dynamically created when you submit a job and terminated once the job completes, helping to optimize resource usage.</p><ul><li><strong>Pools</strong>: Pools in Synapse are predefined compute resources. For example:</li><li><strong>SQL Pools</strong> (Dedicated or Serverless): Handle large-scale data querying and transformations.</li><li><strong>Spark Pools</strong>: Allow you to process big data using Apache Spark.</li></ul><p>Pools in Synapse focus on simplifying resource allocation for different workloads, ensuring scalability and cost-effectiveness.</p><h4>3. Azure Data Factory (ADF)</h4><ul><li><strong>Clusters</strong>: Azure Data Factory doesn’t have clusters in the traditional sense, but it relies on compute resources (integration runtimes) to run data workflows.</li></ul><p><strong>Integration Runtimes</strong> act like clusters by providing the computational power required for data movement and transformation.</p><ul><li><strong>Pools</strong>: While ADF doesn’t explicitly use the term “pools,” you can configure <strong>pipeline concurrency</strong> and <strong>time-triggered executions</strong> to optimize resource usage.</li></ul><p>ADF often integrates with external clusters or pools, such as Databricks or Synapse, for processing large-scale data.</p><h3>Why Should We Care?</h3><ol><li><strong>Efficiency</strong>: Understanding pools can help you save time and money by reducing startup delays and optimizing resource usage.</li><li><strong>Scalability</strong>: Clusters allow you to scale up and down based on workload demands, an essential concept for working with big data.</li><li><strong>Real-World Applications</strong>:Knowing when to use a cluster versus a pool is critical when setting up workflows in tools like Databricks or Azure Synapse.</li></ol><p>Feel free to follow me on Linkedin <a href="https://www.linkedin.com/in/monty-poddar-46b832142/">https://www.linkedin.com/in/monty-poddar-46b832142/</a> and on medium <a href="https://medium.com/u/412283251922">Monty Poddar</a> as I continue exploring and simplifying data engineering concepts for beginners and Intermediate like us.</p><p>Let’s grow together in this journey!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d531ef2209bf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Engineer Interview: Part 5]]></title>
            <link>https://medium.com/@montypoddar08/data-engineer-interview-part-5-2742dee95574?source=rss-412283251922------2</link>
            <guid isPermaLink="false">https://medium.com/p/2742dee95574</guid>
            <category><![CDATA[interview]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Monty Poddar]]></dc:creator>
            <pubDate>Sun, 22 Dec 2024 17:15:04 GMT</pubDate>
            <atom:updated>2024-12-22T17:15:04.244Z</atom:updated>
            <content:encoded><![CDATA[<p>You are given a table with details about devices, the hosts they paired with, and the pairing times. The goal is to write a query that extracts the following details for each device:</p><ol><li><strong>First Paired Host and Time</strong>: The earliest pairing for each device.</li><li><strong>Latest Paired Host and Time</strong>: The most recent pairing for each device.</li></ol><h4>Input Table</h4><p><strong>Table Name: DEVICE</strong></p><p>DEVICE_ID HOST_ID PAIRING_TIME</p><p>BT1 TV1 2023–12–01 15:00:00</p><p>BT1 Mob1 2023–12–01 09:00:00</p><p>BT1 LP1 2023–12–01 18:00:00</p><p>USB1 Mob1 2023–12–01 12:00:00</p><h4>Expected Output</h4><p>DEVICE_ID FIRST_PAIRED_HOST FIRST_PAIRED_TIME LATEST_PAIRED_HOST LATEST_PAIRED_TIME</p><p>BT1 Mob1 2023–12–01 09:00:00 LP1 2023–12–01 18:00:00</p><p>USB1 Mob1 2023–12–01 12:00:00 Mob1 2023–12–01 12:00:00</p><h4>Solution</h4><p>The problem can be solved using SQL window functions such as ROW_NUMBER. These functions allow us to assign ranks to rows within each group (in this case, by DEVICE_ID) based on the pairing time.</p><p>I have solved this problem with 2 different approach as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6H5GOJwds4aZ-ac17dn52g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*et8mpvYcohkOQHGm_FzhfA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rkb9CIN_6yLYNu-qzvVsRw.png" /></figure><p>As per above image the first part is the input of the table data and rest bottom two are the solutions with two different approaches.</p><p>Please share your thoughts on my LinkedIn Post: <a href="https://www.linkedin.com/in/monty-poddar-46b832142/">https://www.linkedin.com/in/monty-poddar-46b832142/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2742dee95574" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>