<?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 Mohanaselvan Kathamuthu on Medium]]></title>
        <description><![CDATA[Stories by Mohanaselvan Kathamuthu on Medium]]></description>
        <link>https://medium.com/@mohanaslvn?source=rss-38b11276ad1e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*0L3VyVNrB4CH8hGl</url>
            <title>Stories by Mohanaselvan Kathamuthu on Medium</title>
            <link>https://medium.com/@mohanaslvn?source=rss-38b11276ad1e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 19:19:35 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohanaslvn/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[Why Everyone’s Talking About the MCP Protocol]]></title>
            <link>https://medium.com/@mohanaslvn/why-everyones-talking-about-the-mcp-protocol-78fb858e9da7?source=rss-38b11276ad1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/78fb858e9da7</guid>
            <category><![CDATA[mcp-protocol]]></category>
            <category><![CDATA[mcp-server]]></category>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[mcp-client]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Mohanaselvan Kathamuthu]]></dc:creator>
            <pubDate>Tue, 03 Feb 2026 03:10:18 GMT</pubDate>
            <atom:updated>2026-02-03T03:10:18.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-TxubjsI1-if1kgKzcgAg.png" /></figure><h3>Why MCP Is Needed</h3><p>Today, AI models don’t naturally know how to use tools or access data. Every integration is built using custom prompts, schemas, and glue code. This makes AI systems fragile, hard to scale, and difficult to secure.</p><p>MCP is needed to standardise how AI interacts with tools and data. It removes tight coupling, improves reusability, and creates clear security boundaries — so AI applications can move from demos to production-ready systems.</p><h3>From Origin to Adoption</h3><p>The <strong>Model Context Protocol (MCP)</strong> was introduced in 2024 by <strong>Anthropic</strong> as an open protocol to standardise how AI models interact with external tools and data.</p><p>Over time, MCP moved from concept to real usage. Today, MCP is actively adopted and supported by multiple platforms:</p><ul><li><strong>Anthropic</strong> uses MCP across its Claude ecosystem, encouraging tool builders to expose MCP servers.</li><li><strong>OpenAI</strong> has added MCP support across its tooling and agent workflows, signalling broader industry alignment.</li><li><strong>Microsoft</strong> supports MCP within AI and developer tooling, especially in agent-based and enterprise scenarios.</li><li><strong>LangChain</strong> provides MCP adapters, allowing agent frameworks to consume MCP-based tools easily.</li></ul><p>Today, MCP is still evolving — but it has clearly moved beyond an idea. It is becoming shared infrastructure for building scalable, production-grade AI systems.</p><h3>Architecture of MCP</h3><p>MCP follows a <strong>client–server architecture</strong> that cleanly separates AI models from the systems they interact with.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGmsoQ9nKaxKXxGXvyM-XQ.png" /></figure><h3>Core Components</h3><h3>1. MCP Client</h3><ul><li>Resides inside the AI application or agent</li><li>Discovers available capabilities exposed by MCP servers</li><li>Sends structured requests to access resources or invoke tools</li><li>Receives responses and passes them back to the model</li><li>Remains independent of tool implementation details</li></ul><h3>2. MCP Server</h3><ul><li>Acts as the interface between AI and external systems</li><li>Defines which resources, tools, and prompts are available</li><li>Handles request validation and execution</li><li>Enforces access control and security policies</li><li>Prevents direct model access to underlying systems</li></ul><h3>3. Transport Layer</h3><ul><li>Defines how MCP clients and servers communicate</li><li>Commonly uses JSON-RPC over HTTP or stdio</li><li>Keeps the protocol lightweight and language-agnostic</li><li>Allows MCP to work across local and remote environments</li></ul><h3>3. Resources</h3><ul><li>Represent read-only data exposed to the AI</li><li>Can include files, documents, database records, logs, or metadata</li><li>Used to provide accurate and up-to-date context</li><li>Cannot modify underlying systems</li></ul><h3>4. Tools</h3><ul><li>Represent actions the AI is allowed to perform</li><li>Examples include searching data, writing files, triggering workflows, or running jobs</li><li>Each tool has a well-defined input and output schema</li><li>Execution is fully controlled by the MCP server</li></ul><h3>5. Prompts</h3><ul><li>Predefined prompt templates exposed by the server</li><li>Ensure consistent instructions across different AI interactions</li><li>Reduce prompt duplication inside applications</li><li>Help guide models toward correct tool usage</li></ul><h3>End-to-End Working of MCP</h3><p>Consider an AI assistant that needs to fetch a user’s details and send them via email.</p><p>When the user asks, <strong>“Send my profile details to my email,”</strong> the AI model understands the intent but does not directly access any database or email service.</p><p>An <strong>MCP Server</strong> already exposes two capabilities:</p><ul><li>A <strong>resource</strong> to fetch user profile details</li><li>A <strong>tool</strong> to send emails</li></ul><p>The <strong>MCP Client</strong> requests the user profile resource from the MCP server. The server retrieves the data from the backend system and returns it in a structured format.</p><p>Next, the MCP client invokes the email-sending tool, passing the fetched user details as input. The MCP server handles the actual email delivery while enforcing permissions and validation.</p><p>Once the email is sent successfully, the server returns a confirmation. The AI assistant then responds to the user, confirming that the email has been sent.</p><p>In this entire flow, the AI model never interacts directly with databases or email systems. It only requests capabilities, while the MCP server controls execution — making the integration secure, reusable, and production-ready</p><h3>Why This Architecture Matters</h3><p>MCP’s architecture separates AI models from the systems they use, making integrations modular, reusable, and secure. By keeping tool logic and permissions outside the model, MCP reduces tight coupling and enables AI systems to scale and evolve into production-ready applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78fb858e9da7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Fast Is Polars Really? A Basic Performance Test]]></title>
            <link>https://medium.com/@mohanaslvn/how-fast-is-polars-really-a-basic-performance-test-20f07f723ff4?source=rss-38b11276ad1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/20f07f723ff4</guid>
            <category><![CDATA[performance-testing]]></category>
            <category><![CDATA[polars-dataframe]]></category>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[pandas-vs-polars]]></category>
            <dc:creator><![CDATA[Mohanaselvan Kathamuthu]]></dc:creator>
            <pubDate>Sat, 10 Jan 2026 19:20:35 GMT</pubDate>
            <atom:updated>2026-01-10T19:20:35.893Z</atom:updated>
            <content:encoded><![CDATA[<p>Measuring how both tools perform on common data tasks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZHxKBmgkxm7en7kv4Lnkrw.png" /></figure><p>The tests below are conducted using synthetically generated data, with one dataset containing 1 million rows and another containing 20 million rows. Each dataset is saved in both CSV and Parquet formats. I’ll be testing their performance while loading the data, running filters, doing groupby operations, sorting, performing joins, and executing an end-to-end pipeline to understand how each library behaves in real-world scenarios.</p><blockquote>The tests below were performed on a Windows system running a 12th Gen Intel Core i5–1235U (10 cores, 12 threads) with 16GB RAM.</blockquote><h3><strong>Load Speed Test (CSV &amp; Parquet)</strong></h3><p>To start the comparison, I tested how Pandas and Polars load the same 1M and 20M synthetic datasets in both CSV and Parquet formats. The syntax for loading files is nearly identical in both libraries.</p><pre>#loading csv file in pandas<br>import pandas as pd<br>df = pd.read_csv(&quot;benchmark_data.csv&quot;)<br><br>#loading csv file in polars<br>import polars as pl<br>df = pl.read_csv(&quot;benchmark_data.csv&quot;)<br><br>#loading parquet file in pandas<br>import pandas as pd<br>df = pd.read_parquet(&quot;benchmark_data.parquet&quot;)<br><br>#loading parquet file in polars<br>import polars as pl<br>df = pl.read_parquet(&quot;benchmark_data.parquet&quot;)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*KuFgiLODZMFXSgTDUgrDjQ.png" /><figcaption>Pandas loading time</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/706/1*elLGxG6NKxSvyT3Hcz7pCA.png" /><figcaption>Polars loading time</figcaption></figure><p>The load-time results show a big difference. Polars loaded the 20M CSV in just over a second, while Pandas took close to fifty seconds. Even with Parquet, Polars finished almost instantly compared to Pandas. The smaller 1M files show the same pattern. These results clearly highlight how much faster Polars handles file loading.</p><blockquote><em>Loading speed alone doesn’t decide which library is better, so next I’ll test how both perform on real transformations</em></blockquote><h3>Transformation Performance Test</h3><p>The next set of tests focuses on common transformations used in real data pipelines. These include filtering rows, creating new calculated columns, joining with lookup tables, and running groupby aggregations. By applying the same operations in both Pandas and Polars, we can see how each library handles the core steps that appear in everyday data engineering workflows.</p><p>The examples below also highlight the small but important syntax differences between Pandas and Polars while performing the same transformations.</p><pre>import pandas as pd<br><br>PARQUET_FILE = &quot;benchmark_data.parquet&quot;<br><br># Lookup table for join<br>lookup_pd = pd.DataFrame({<br>    &quot;department&quot;: [&quot;Sales&quot;, &quot;Engineering&quot;, &quot;HR&quot;, &quot;Finance&quot;, &quot;Support&quot;, &quot;Marketing&quot;],<br>    &quot;bonus&quot;: [5000, 8000, 3000, 4000, 3500, 4500]<br>})<br><br># Load Parquet<br>df_pd = pd.read_parquet(PARQUET_FILE)<br><br># 1. Filtering<br>filtered_pd = df_pd[df_pd[&quot;age&quot;] &gt; 40]<br><br># 2. Transform Column<br>df_pd[&quot;salary_with_bonus&quot;] = df_pd[&quot;salary&quot;] * 1.10<br><br># 3. Join Operation<br>joined_pd = df_pd.merge(lookup_pd, on=&quot;department&quot;, how=&quot;left&quot;)<br><br># 4. GroupBy + Aggregation<br>grouped_pd = df_pd.groupby(&quot;city&quot;)[&quot;salary&quot;].agg([&quot;mean&quot;, &quot;max&quot;, &quot;min&quot;])</pre><pre>import polars as pl<br><br>PARQUET_FILE = &quot;benchmark_data.parquet&quot;<br><br># Lookup table for join<br>lookup_pl = pl.DataFrame({<br>    &quot;department&quot;: [&quot;Sales&quot;, &quot;Engineering&quot;, &quot;HR&quot;, &quot;Finance&quot;, &quot;Support&quot;, &quot;Marketing&quot;],<br>    &quot;bonus&quot;: [5000, 8000, 3000, 4000, 3500, 4500]<br>})<br><br># Load Parquet<br>df_pl = pl.read_parquet(PARQUET_FILE)<br><br># 1. Filtering<br>filtered_pl = df_pl.filter(pl.col(&quot;age&quot;) &gt; 40)<br><br># 2. Transform Column<br>df_pl2 = df_pl.with_columns([<br>    (pl.col(&quot;salary&quot;) * 1.10).alias(&quot;salary_with_bonus&quot;)<br>])<br><br># 3. Join Operation<br>joined_pl = df_pl.join(lookup_pl, on=&quot;department&quot;, how=&quot;left&quot;)<br><br># 4. GroupBy + Aggregation<br>grouped_pl = df_pl.group_by(&quot;city&quot;).agg([<br>    pl.col(&quot;salary&quot;).mean().alias(&quot;mean_salary&quot;),<br>    pl.col(&quot;salary&quot;).max().alias(&quot;max_salary&quot;),<br>    pl.col(&quot;salary&quot;).min().alias(&quot;min_salary&quot;)<br>])</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*V6cfukqf5DRl8JN6X2oN4A.png" /><figcaption>20M CSV file transformation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*vHfHQmYaD_qH_7cpYHPoiw.png" /><figcaption>20M parquet file transformation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*kt3qPcybkt3okR9IVD2QMA.png" /><figcaption>1M CSV file transformation</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*qIaE1UBx2bf5g20pHSSgNw.png" /><figcaption>1M Parquet file transformation</figcaption></figure><p>The transformation tests clearly show that Polars completes every step — filtering, column calculations, joins, and groupby aggregations — much faster than Pandas across both CSV and Parquet datasets. Even as the data size changes, Polars consistently keeps its execution times low, while Pandas takes noticeably longer for the same operations.</p><p>Even though Polars comes out faster in both loading and transformation tests, speed alone isn’t the only factor in deciding whether a switch is truly worth it. Things like ecosystem support, memory usage, and integration with existing tools all play a role. I’ll break down these considerations in detail in my next blog so you can decide when a move to Polars makes sense.</p><p>Next Blog link : <a href="https://medium.com/@mohanaslvn/the-final-verdict-is-polars-the-better-choice-b7ce0f2e7764">https://medium.com/@mohanaslvn/the-final-verdict-is-polars-the-better-choice-b7ce0f2e7764</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20f07f723ff4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Final Verdict: Is Polars the Better Choice?]]></title>
            <link>https://medium.com/@mohanaslvn/the-final-verdict-is-polars-the-better-choice-b7ce0f2e7764?source=rss-38b11276ad1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7ce0f2e7764</guid>
            <category><![CDATA[pandas]]></category>
            <category><![CDATA[pandas-vs-polars]]></category>
            <category><![CDATA[polars-dataframe]]></category>
            <category><![CDATA[performance-testing]]></category>
            <dc:creator><![CDATA[Mohanaselvan Kathamuthu]]></dc:creator>
            <pubDate>Sat, 10 Jan 2026 19:17:50 GMT</pubDate>
            <atom:updated>2026-01-10T19:17:50.377Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jcIFv12A9uL5zdKyCSB21w.jpeg" /></figure><p>After testing load speed, transformations, joins, groupbys, and overall workflow behaviour, it’s clear that Polars delivers exceptional performance. But performance alone cannot decide whether a team should replace Pandas. In real data engineering environments, the choice depends on ecosystem support, integration with big-data frameworks, visualization needs, learning curve, and long-term maintainability. Bringing these factors together so you can decide when switching to Polars makes sense — and when Pandas is still the better choice.</p><h3>1. Performance: Where Polars Dominates</h3><p>Polars is built with a Rust engine and designed for multi-threading. This gives it clear advantages:</p><ul><li>much faster filtering, grouping, sorting, joining</li><li>highly efficient use of all CPU cores</li><li>dramatically lower memory footprint</li><li>lazy execution that optimizes entire pipelines</li><li>excellent support for columnar formats like Parquet</li></ul><p>In every transformation and loading test, Polars completed operations significantly faster than Pandas.</p><p>But performance isn’t the whole story.<br> Speed can attract attention, yet the day-to-day usefulness of a library often depends on everything around it.</p><h3>2. Ecosystem Support: Pandas Still Leads</h3><p>Pandas has been the default data analysis library in Python for more than a decade. Because of that, the ecosystem around it is enormous:</p><ul><li>every major ML library accepts Pandas DataFrames</li><li>Integration With Big Data Frameworks(Spark, Databricks, Snowflake) is easy with Pandas</li><li>most plotting tools (Matplotlib, Seaborn, Plotly) expect Pandas input</li><li>BI dashboards, Excel tools, and notebook extensions work directly with Pandas</li><li>millions of StackOverflow answers, tutorials, and examples exist for Pandas</li><li>enterprise teams already have Pandas-based code in production</li></ul><p>Switching a team’s entire workflow to Polars means revisiting many tools that tightly integrate with Pandas today.</p><p>Polars is growing fast, but its ecosystem is still young.</p><h3>3. Dataset Size &amp; Workflow Type</h3><p>Your choice depends heavily on the size and type of your data.</p><p><strong>Pandas is ideal for</strong></p><ul><li>datasets comfortably under a few GB</li><li>exploration in notebooks</li><li>plotting and ML model prep</li><li>analytics and reporting</li><li>ad-hoc data cleaning</li></ul><p><strong>Polars is ideal for</strong></p><ul><li>large datasets that push memory limits</li><li>CPU-intensive transformations</li><li>parallel processing workflows</li><li>pipelines where lazy execution saves time</li><li>Python-only data engineering pipelines</li></ul><p>In real-world projects, many teams end up using <strong>both</strong>.</p><h3>4. Cost, Infrastructure &amp; Cloud Efficiency</h3><p>Performance isn’t only about speed — it affects cost too.</p><p><strong>Polars :</strong></p><ul><li>reduce CPU time</li><li>lower cloud compute costs</li><li>run faster on local machines</li><li>minimize memory spikes</li></ul><p><strong>Pandas:</strong></p><ul><li>runs everywhere without extra dependencies</li><li>has simpler installation in restrictive environments</li><li>is supported by practically every cloud notebook runtime</li></ul><h3>Final Verdict: Should You Switch to Polars?</h3><p>These conclusions reflect my practical experience: Polars wins on performance; Pandas wins on compatibility, tooling, and everyday usability. The most realistic long-term strategy isn’t choosing one over the other, but combining both, using each where it performs best.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7ce0f2e7764" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unlocking Spark SQL Performance: AQE, Dynamic Partition Pruning & Join Strategy Controls in…]]></title>
            <link>https://medium.com/@mohanaslvn/unlocking-spark-sql-performance-aqe-dynamic-partition-pruning-join-strategy-controls-in-eb87aab35191?source=rss-38b11276ad1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb87aab35191</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[spark-optimization]]></category>
            <dc:creator><![CDATA[Mohanaselvan Kathamuthu]]></dc:creator>
            <pubDate>Sun, 24 Aug 2025 11:13:47 GMT</pubDate>
            <atom:updated>2025-08-24T11:13:47.315Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unlocking Spark SQL Performance: AQE, Dynamic Partition Pruning &amp; Join Strategy Controls in Databricks</h3><p>When running large-scale data workloads on Spark (especially in Databricks), performance tuning goes far beyond just throwing bigger clusters at the problem. At the <strong>Spark session level</strong>, you can enable powerful optimizations that let the engine adapt to data at runtime, prune unnecessary work, and pick the most efficient join strategies. Three of the most impactful features are:</p><ol><li><strong>Adaptive Query Execution (AQE)</strong></li><li><strong>Dynamic Partition Pruning (DPP)</strong></li><li><strong>Join Strategy Controls</strong></li></ol><p>In this post, we’ll go beyond the basics to cover how they work internally, what joins are available in Databricks, and how Local Shuffle Reader helps influence performance</p><h3>🔹1. Adaptive Query Execution (AQE)</h3><h3>What is AQE?</h3><p>Normally Spark generates a <strong>static execution plan</strong> at query compile time. But runtime realities (data skew, incorrect stats, unexpected filter selectivity) can make those plans inefficient.</p><p><strong>Adaptive Query Execution (AQE)</strong> allows Spark to <strong>re-optimize execution plans dynamically</strong> as stages complete and new statistics are available.</p><h3>Key Features of AQE</h3><h4>1. Dynamic Shuffle Partition Coalescing</h4><ul><li>Spark defaults to a fixed number of shuffle partitions (spark.sql.shuffle.partitions, often 200).</li><li>This can cause too many small tasks for small jobs, or too few huge tasks for big data.</li><li>With AQE, Spark measures shuffle data size and <strong>coalesces partitions</strong> into an optimal number.</li></ul><p><strong>Tuning Knob:</strong></p><pre>spark.conf.set(&quot;spark.sql.adaptive.shuffle.targetPostShuffleInputSize&quot;, &quot;134217728&quot;)  # 128MB</pre><p><strong>Meaning:</strong> Each reducer task should process ~128 MB of data after shuffle.</p><p>Larger value = fewer, heavier tasks (less scheduling overhead).</p><p>Smaller value = more, lighter tasks (better load balancing).</p><h4>2. Skew Join Handling</h4><p>Data skew causes some partitions to be much larger than others → “long tail” tasks.AQE detects skewed partitions and splits them into smaller chunks, so they can be processed in parallel.</p><pre>spark.conf.set(&quot;spark.sql.adaptive.skewJoin.enabled&quot;, &quot;true&quot;)</pre><h4>3. Dynamic Join Selection</h4><p>Spark may <strong>switch join strategy at runtime</strong>:</p><p>Example: Initially plans a Sort-Merge Join, but finds one side is actually very small → switches to Broadcast Hash Join.</p><h4>4. Local Shuffle Reader</h4><p>In Spark 3.1+ and Databricks runtimes, AQE can assign shuffle read tasks to <strong>prefer local executors</strong> (those that already have the data).</p><ul><li>This reduces <strong>cross-executor/network traffic</strong>, improving performance.</li><li>Especially useful in large joins where shuffle data is cached locally on SSD.</li></ul><pre>spark.conf.set(&quot;spark.sql.adaptive.localShuffleReader.enabled&quot;, &quot;true&quot;)</pre><h3>How Databricks Decides</h3><p>Databricks’ Catalyst optimizer + AQE work together:</p><ol><li>Generate an initial plan with static heuristics (stats, thresholds).</li><li>Execute initial stages and collect real metrics (partition sizes, row counts).</li><li>Rewrite subsequent stages based on actual observed data.</li></ol><p>This makes query execution far more robust to data skew, stale stats, and misestimates.</p><h3>🔹2. Dynamic Partition Pruning (DPP)</h3><h3>What is DPP?</h3><p>Partition pruning reduces the number of partitions scanned from a partitioned table. <strong>Dynamic Partition Pruning </strong>takes this further: Spark decides at runtime which partitions to read, based on values from the query.</p><h3>Why It Matters</h3><p>Without DPP, Spark may scan an entire fact table even if the filter comes from another dataset. DPP ensures only relevant partitions are scanned → huge performance gain in star-schema joins.</p><h3>How to Enable</h3><pre>spark.conf.set(&quot;spark.sql.optimizer.dynamicPartitionPruning.enabled&quot;, &quot;true&quot;)</pre><h3>Example</h3><pre>-- fact table partitioned by date<br>SELECT f.user_id, SUM(f.amount)<br>FROM fact_events f<br>JOIN dim_calendar d<br>  ON f.event_date = d.date<br>WHERE d.year = 2025 AND d.month = 8;</pre><ul><li>Without DPP → Spark may scan <strong>all partitions of fact_events</strong>.</li><li>With DPP → Spark reads only <strong>August 2025 partitions</strong>, massively reducing I/O.</li></ul><p>In Databricks, DPP integrates tightly with Delta Lake, making queries on partitioned Delta tables much faster.</p><h3>🔹3. Join Strategy Controls</h3><h3>Joins Available in Databricks (Spark SQL)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/983/1*2aCtUEGRDn8eT0zG0RRa5w.png" /></figure><h3>How Spark Chooses Join Strategy</h3><p><strong>Broadcast if possible</strong></p><ol><li>If one side &lt; spark.sql.autoBroadcastJoinThreshold (default 10 MB in OSS, 10–100 MB in Databricks), Spark uses BHJ.</li><li>AQE can promote to Broadcast at runtime if data shrinks after filters.</li></ol><p><strong>Sort-Merge Join fallback</strong></p><ol><li>Default for large equi-joins.</li><li>Robust, but heavy shuffling &amp; sorting.</li></ol><p><strong>Shuffle Hash Join</strong></p><ol><li>Used if enabled and both sides fit into memory hash structures.</li><li>Less shuffle overhead than SMJ.</li></ol><p><strong>Nested Loop Joins</strong></p><ol><li>Last resort for cross/non-equi joins.</li><li>Expensive; avoid unless necessary.</li></ol><h3>Key Configs</h3><pre># Increase broadcast threshold if you have large executors<br>spark.conf.set(&quot;spark.sql.autoBroadcastJoinThreshold&quot;, 104857600)  # 100MB<br><br># Timeout for broadcast<br>spark.conf.set(&quot;spark.sql.broadcastTimeout&quot;, &quot;600&quot;)<br><br># Prefer Sort-Merge Join if unsure (safe but expensive)<br>spark.conf.set(&quot;spark.sql.join.preferSortMergeJoin&quot;, &quot;true&quot;)</pre><h3>✅ Best Practices</h3><ol><li><strong>Always enable AQE</strong> in production: it fixes skew, partition sizing, and join strategy dynamically.</li><li><strong>Enable Dynamic Partition Pruning</strong> for partitioned Delta tables.</li><li><strong>Increase broadcast threshold</strong> (50–200 MB) if your cluster memory allows; take advantage of BHJ.</li><li><strong>Use “</strong><strong>EXPLAIN FORMATTED”</strong>to confirm Spark picked the right join and pruning strategy.</li><li><strong>Watch Spark UI</strong> for skew, shuffle size, and task imbalance.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb87aab35191" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Running Unity Catalog Workloads with a Service Principal (Tech ID)]]></title>
            <link>https://medium.com/@mohanaslvn/running-unity-catalog-workloads-with-a-service-principal-tech-id-43bfa2f658fe?source=rss-38b11276ad1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/43bfa2f658fe</guid>
            <category><![CDATA[databricks]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[unity-catalog]]></category>
            <category><![CDATA[service-principal]]></category>
            <dc:creator><![CDATA[Mohanaselvan Kathamuthu]]></dc:creator>
            <pubDate>Tue, 01 Jul 2025 16:06:37 GMT</pubDate>
            <atom:updated>2025-07-01T16:14:12.279Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A step-by-step guide to configuring clusters, permissions, and access controls for Unity Catalog using a service principal in Databricks.</em></p><h4>✅ Use Case:</h4><p>You may want to run jobs, pipelines, or automated tasks in Databricks <strong>using a service principal</strong> instead of a human user — especially for CI/CD, ETL pipelines, or production automation</p><h3>🧩 Steps to Use a Service Principal with Unity Catalog</h3><h3>1. Create a Service Principal (SP) in Azure</h3><p>If you’re using Azure:</p><ul><li>Go to <strong>Azure Active Directory &gt; App Registrations</strong></li><li>Create a new app registration (this is your <strong>service principal</strong>)</li><li>Generate a <strong>client secret</strong></li><li>Assign necessary <strong>Azure RBAC roles</strong> for storage access (e.g., Storage Blob Data Reader)</li></ul><h4>2. Sync the Service Principal to Databricks via SCIM</h4><p>To make the SP visible in Databricks:</p><ul><li>Go to <strong>Databricks Admin Console &gt; Users</strong></li><li>Use SCIM or <strong>manually add</strong> the SP as a user or group</li><li>This allows Unity Catalog to apply permissions to the SP</li></ul><p><em>You can also use </em><strong><em>Groups</em></strong><em> if you want to organize multiple SPs with shared access policies</em></p><h4>3. Grant Permissions in Unity Catalog</h4><p>Using SQL:</p><p>Prefix spn: is required for service principals</p><pre>-- Grant access to the service principal<br>GRANT USAGE ON CATALOG finance_catalog TO `spn:my-service-principal-name`;<br>GRANT SELECT ON TABLE finance_catalog.revenue.q1_data TO `spn:my-service-principal-name`;<br></pre><h3>4. Create a Cluster with the Right Configuration</h3><p>To run Unity Catalog workloads, your cluster must meet the following:</p><ul><li>✅ <strong>Access Mode</strong>: Must be <strong>Shared</strong></li><li>✅ <strong>Unity Catalog</strong>: Automatically enabled with Shared mode</li><li>✅ <strong>Run As</strong>: Set to the <strong>Service Principal</strong></li><li>✅ <strong>Databricks Runtime</strong>: Version <strong>11.1 or later</strong> (recommended)</li><li>🔐 <strong>Storage Access</strong>: Ensure the SP has access to the <strong>storage credential</strong> if the data is in <strong>external locations or volumes</strong></li></ul><h3>5. Run the Job or Notebook as the Service Principal</h3><p>Use either:</p><ul><li><strong>Jobs API / CLI</strong> to trigger jobs using the SP’s token</li><li>Or set up <strong>Service Principal Authentication</strong> via the Databricks REST API</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43bfa2f658fe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Everything You Need to Know About Unity Catalog in Databricks”]]></title>
            <link>https://medium.com/@mohanaslvn/everything-you-need-to-know-about-unity-catalog-in-databricks-6743afd26b2d?source=rss-38b11276ad1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6743afd26b2d</guid>
            <category><![CDATA[centralized-governance]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[unity-catalog]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[databricks]]></category>
            <dc:creator><![CDATA[Mohanaselvan Kathamuthu]]></dc:creator>
            <pubDate>Mon, 30 Jun 2025 17:12:40 GMT</pubDate>
            <atom:updated>2025-07-01T15:45:15.460Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why Unity Catalog? The Industrial Problem It Solves</h4><p>As enterprises grow, so does their data — across teams, tools, clouds, and regions. In such distributed environments, ensuring secure, consistent, and auditable access to data becomes one of the biggest challenges in data engineering and governance.</p><h4>⚠️ The Problem Before Unity Catalog</h4><p>Before Unity Catalog, Databricks workspaces used separate Hive metastores, leading to:</p><p>❌ <strong>Isolated metadata silos</strong> — making data discovery difficult</p><p>❌ <strong>Inconsistent access control</strong> — policies managed per workspace</p><p>❌ <strong>No end-to-end lineage</strong> — hard to trace data flow for audits or debugging</p><p>❌ <strong>Redundant data copies</strong> — for sharing across teams or regions</p><p>❌ <strong>Limited collaboration</strong> — between departments or clouds</p><p>❌ <strong>Compliance risks</strong> — due to lack of visibility and centralized governance</p><p>These issues were especially painful for <strong>regulated industries</strong> like finance, healthcare, and telecom, where <strong>compliance, lineage, and access control</strong> are non-negotiable.</p><h4>✅ The Unity Catalog Solution</h4><p>Databricks introduced Unity Catalog to solve these enterprise-scale governance challenges. It offers:</p><p>✅ A <strong>single, unified metastore</strong> across all workspaces and regions</p><p>✅ <strong>Fine-grained, RBAC-based access control</strong> down to column-level</p><p>✅ <strong>Centralized data lineage</strong> and <strong>usage monitoring</strong></p><p>✅ <strong>Audit logging</strong> for compliance and traceability</p><p>✅ <strong>Cross-workspace and multi-cloud collaboration</strong> without copying data</p><p>✅ <strong>Secure external location support</strong> to manage data directly in cloud storage</p><p>With Unity Catalog, organizations gain <strong>complete control and visibility</strong> over their data — <strong>without compromising scalability, flexibility, or performance</strong></p><h4>What Changed with Unity Catalog in Databricks</h4><p>Earlier, each workspace had a separate Hive metastore, so data and permissions had to be managed individually. Sharing data between teams required copying, and tracking usage was difficult. Now, Unity Catalog connects all workspaces to one place, making access control and tracking centralized</p><h4>🧱 Unity Catalog Architecture and Components</h4><h4>1. Metastore</h4><p>The metastore is the heart of Unity Catalog. It acts as a central control plane that stores all metadata — including catalogs, schemas, tables, access rules, and lineage — and is shared across multiple Databricks workspaces in a region.</p><p><em>🟢 </em>Why it exists:<em> To centralize metadata and governance</em></p><h4>2. Catalog</h4><p>A <strong>catalog</strong> is the top-level container within the metastore. It is used to logically group schemas, usually by team, department, or function (e.g., finance_catalog, sales_catalog).</p><p><em>🟢 </em>Why it exists:<em> To organize datasets by domain or business unit</em></p><h4><strong>3. Schema (Database)</strong></h4><p>A <strong>schema</strong> sits inside a catalog and contains related tables and views. It acts like a namespace within a catalog.</p><p><em>🟢 </em>Why it exists:<em> To organize related datasets</em></p><h4>4. Table / View</h4><p>These are the core data assets users interact with — physical data in <strong>tables</strong> and saved queries in <strong>views</strong>.</p><p><em>🟢 </em>Why it exists:<em> To represent and query actual data</em></p><h4>5. Volumes</h4><p>Volumes are secure, cataloged folders for storing files like CSVs, models, and reports — governed by Unity Catalog with RBAC and audit logging.</p><p><em>🟢 </em>Why it exists:<em> Secure, organized file access with RBAC and audit logging, backed by cloud storage</em></p><h4>6. External Location</h4><p>An <strong>external location</strong> securely links Unity Catalog to cloud storage paths (like ADLS or S3) while enforcing governance.</p><p><em>🟢 </em>Why it exists:<em> To manage secure, governed access to cloud storage</em></p><h4><strong>7. Storage Credential</strong></h4><p>This defines the cloud permission (e.g., an IAM role or Azure service principal) used to access the external location.</p><p><em>🟢 </em>Why it exists:<em> To securely authorize access to cloud storage</em></p><h4>8. Users &amp; Groups</h4><p>Unity Catalog integrates with your cloud Identity Provider (like Azure AD) to manage users and groups centrally.</p><p><em>🟢 </em>Why it exists:<em> To enable identity-based access control</em></p><h4>9. RBAC (Role-Based Access Control)</h4><p>RBAC allows assigning permissions at the catalog, schema, table, or even column level.</p><p><em>🟢 </em>Why it exists:<em> To ensure the right people have the right access</em></p><h4>10. Lineage Tracker</h4><p>Unity Catalog automatically tracks how data flows through queries, tables, and views.</p><p><em>🟢 </em>Why it exists:<em> To understand data dependencies and transformations</em></p><h4>11. Audit Logging</h4><p>Every access, change, or query is logged for review.</p><p><em>🟢 </em>Why it exists:<em> To meet compliance and security requirements</em></p><h4>🔁 Example: How Unity Catalog Components Work Together During a Query</h4><h4>🎯 Scenario:</h4><p>A data analyst in Workspace A runs the following query:</p><pre>SELECT region, SUM(amount) <br>FROM sales_catalog.revenue.transactions <br>WHERE year = 2024 <br>GROUP BY region;</pre><h4>🔍 Step-by-Step Component Involvement:</h4><p>🧑‍💼 <strong>User &amp; Groups: </strong>The analyst’s identity is verified. Unity Catalog checks their <strong>user/group membership</strong> (synced via SCIM from your Identity Provider).</p><p>🔐 <strong>RBAC (Role-Based Access Control)</strong></p><p>Unity Catalog checks if the user has SELECT permission on:</p><ol><li>The <strong>catalog</strong>: sales_catalog</li><li>The <strong>schema</strong>: revenue</li><li>The <strong>table</strong>: transactions</li><li>The <strong>columns</strong>: region, amount, year</li></ol><p>If the user lacks access to any part, the query is blocked.</p><p>🗂️ <strong>Metastore</strong></p><p>The metastore is queried to fetch <strong>metadata</strong> about:</p><ul><li>The table’s structure</li><li>Column types</li><li>Location in storage</li><li>Registered storage credentials</li></ul><h4>📚 Catalog → Schema → Table</h4><p>Unity Catalog locates the table sales_catalog.revenue.transactions and its storage location.</p><p>In <strong>Volume-based workflows</strong>, this could be:</p><pre>df = spark.read.csv(&quot;/Volumes/sales_catalog/revenue/input_files/transactions.csv&quot;)</pre><p>In this case, Unity Catalog would resolve:</p><ul><li>Volume metadata</li><li>File location</li><li>Access control on the volume</li></ul><p>🔐 <strong>Storage Credential &amp; External Location</strong></p><ul><li>Unity Catalog uses the configured <strong>Storage Credential</strong> to authenticate access to the <strong>External Location</strong> (e.g., s3://company-data/sales/)</li><li>This allows Spark to read data from cloud storage securely, without exposing raw credentials</li></ul><p>⚙️ <strong>Spark Processing</strong></p><ul><li>Spark uses this metadata to <strong>read the data</strong>, execute the SUM aggregation and GROUP BY</li><li>The compute happens inside the Databricks cluster in Workspace A</li></ul><p>📈 <strong>Lineage Tracker</strong></p><p>Unity Catalog automatically <strong>records lineage</strong>, noting:</p><ul><li>The input table used</li><li>Columns accessed</li><li>Query logic</li><li>Output (if saved)</li></ul><p>This can be viewed later for auditing or impact analysis.</p><p>📋 <strong>Audit Logging</strong></p><ul><li>The query and access event are <strong>logged automatically</strong></li><li>Logs include who accessed what, when, and from where</li></ul><h4>⚠️ Key Limitations of Unity Catalog</h4><ul><li><strong>Unity-enabled clusters only</strong> — Doesn’t work with legacy or single-user clusters</li><li><strong>Cloud-only</strong> — No support for on-prem or offline setups</li><li><strong>Limited asset types</strong> — ML models and dashboards not yet supported</li><li><strong>No row-level security</strong> — Only column-level RBAC is available</li><li><strong>Setup complexity</strong> — Requires cloud IAM, SCIM, external locations</li><li><strong>One metastore per region</strong> — Workspaces in different regions need separate metastores</li><li><strong>No cross-metastore access</strong> — A workspace can connect to only one metastore</li><li><strong>UI limitations</strong> — Fine-grained RBAC mostly managed via SQL or APIs</li><li><strong>Some features in preview</strong> — Lineage and discovery features are still evolving</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6743afd26b2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding SparkContext: The Backbone of Apache Spark Execution]]></title>
            <link>https://medium.com/@mohanaslvn/understanding-sparkcontext-the-backbone-of-apache-spark-execution-2092c7fbbd39?source=rss-38b11276ad1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/2092c7fbbd39</guid>
            <category><![CDATA[sparksession]]></category>
            <category><![CDATA[spark-context]]></category>
            <category><![CDATA[performance-optimization]]></category>
            <category><![CDATA[spark-tuning]]></category>
            <dc:creator><![CDATA[Mohanaselvan Kathamuthu]]></dc:creator>
            <pubDate>Wed, 25 Jun 2025 17:03:07 GMT</pubDate>
            <atom:updated>2025-06-25T17:03:07.788Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A deep dive into how SparkContext works, how to configure it for performance, and how it’s managed in platforms like Databricks</em></p><h4>Introduction</h4><p>In Apache Spark, SparkContext is the foundational entry point that connects your application to the Spark execution environment. It is responsible for initializing the core services and setting up internal components such as the scheduler, memory manager, and cluster resource manager. Think of SparkContext as the &quot;driver&quot; of your Spark application—it coordinates the execution of tasks, manages configurations, and acts as a bridge between your code and the cluster resources. Without SparkContext, no RDDs can be created, and no transformations or actions can be executed. Understanding and effectively configuring SparkContext is crucial for tuning your Spark jobs and optimizing performance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WNZRja2bLnRivLZH" /></figure><h4>Initializing and limitations of SparkContext</h4><p>The below example shows how SparkContext is initialized using SparkConf, specifying the application name and execution mode</p><pre>from pyspark import SparkConf, SparkContext<br><br># Step 1: Create SparkConf with app name and master<br>conf = SparkConf().setAppName(&quot;SimpleApp&quot;).setMaster(&quot;local[*]&quot;)<br><br># Step 2: Initialize SparkContext<br>sc = SparkContext(conf=conf)<br><br># Step 3: Use SparkContext to create an RDD<br>rdd = sc.parallelize([1, 2, 3, 4, 5])<br>print(rdd.map(lambda x: x * 2).collect())<br><br># Step 4: Stop the context when done<br>sc.stop()</pre><ul><li>Supports only low-level <strong>RDD API</strong>, not DataFrames or SQL.</li><li>Lacks <strong>query optimization</strong> (no Catalyst or Tungsten).</li><li>Cannot read from <strong>Hive</strong> or run <strong>SQL queries</strong> directly.</li><li>More <strong>verbose and error-prone</strong> compared to high-level APIs.</li><li>Mostly <strong>deprecated</strong> in favor of SparkSession in modern Spark versions.</li></ul><h4>What is the Alternative to SparkContext Today?</h4><p>The modern and recommended alternative to SparkContext is: SparkSession</p><h4>Why SparkSession?</h4><p>Introduced in Spark 2.0+ as a unified entry point for:</p><ul><li>RDD</li><li>DataFrame</li><li>SQL</li><li>Streaming</li><li>Catalog APIs</li></ul><p>It internally creates and manages the SparkContext, so you still have access to low-level features when needed</p><pre>from pyspark.sql import SparkSession<br><br>spark = SparkSession.builder \<br>    .appName(&quot;ModernSparkApp&quot;) \<br>    .getOrCreate()</pre><h3>Top 10 SparkSession Performance Configurations</h3><ol><li><strong>spark.sql.shuffle.partitions</strong><br> 🔹 <em>Default:</em> 200<br> 🔹 <em>Purpose:</em> Controls the number of partitions used during shuffle. Lower for small datasets to avoid overhead.</li><li><strong>spark.executor.memory</strong><br> 🔹 <em>Default:</em> 1g<br> 🔹 <em>Purpose:</em> Allocates memory to each executor. Higher memory helps with larger data transformations.</li><li><strong>spark.executor.cores</strong><br> 🔹 <em>Default:</em> 1<br> 🔹 <em>Purpose:</em> Sets how many cores are allocated per executor. More cores = more parallel tasks.</li><li><strong>spark.sql.autoBroadcastJoinThreshold</strong><br> 🔹 <em>Default:</em> 10 MB<br> 🔹 <em>Purpose:</em> Threshold size below which tables are broadcast for joins, reducing shuffle.</li><li><strong>spark.sql.adaptive.enabled</strong><br> 🔹 <em>Default:</em> false<br> 🔹 <em>Purpose:</em> Enables Adaptive Query Execution to optimize joins and partitions at runtime.</li><li><strong>spark.memory.fraction</strong><br> 🔹 <em>Default:</em> 0.6<br> 🔹 <em>Purpose:</em> Fraction of executor memory reserved for computation and caching.</li><li><strong>spark.serializer</strong><br> 🔹 <em>Default:</em> JavaSerializer<br> 🔹 <em>Purpose:</em> KryoSerializer is faster and more compact for large datasets.</li><li><strong>spark.sql.inMemoryColumnarStorage.compressed</strong><br> 🔹 <em>Default:</em> true<br> 🔹 <em>Purpose:</em> Compresses cached in-memory tables, saving memory.</li><li><strong>spark.dynamicAllocation.enabled</strong><br> 🔹 <em>Default:</em> false<br> 🔹 <em>Purpose:</em> Dynamically adjusts number of executors based on workload.</li><li><strong>spark.sql.files.maxPartitionBytes</strong><br> 🔹 <em>Default:</em> 128 MB<br> 🔹 <em>Purpose:</em> Controls max size of input splits; affects file read parallelism.</li></ol><h4>Example code</h4><pre>from pyspark.sql import SparkSession<br><br>spark = SparkSession.builder \<br>    .appName(&quot;PerformanceTunedApp&quot;) \<br>    .config(&quot;spark.sql.shuffle.partitions&quot;, &quot;100&quot;) \<br>    .config(&quot;spark.executor.memory&quot;, &quot;4g&quot;) \<br>    .config(&quot;spark.executor.cores&quot;, &quot;4&quot;) \<br>    .config(&quot;spark.sql.autoBroadcastJoinThreshold&quot;, &quot;52428800&quot;) \  # 50 MB<br>    .config(&quot;spark.sql.adaptive.enabled&quot;, &quot;true&quot;) \<br>    .config(&quot;spark.memory.fraction&quot;, &quot;0.8&quot;) \<br>    .config(&quot;spark.serializer&quot;, &quot;org.apache.spark.serializer.KryoSerializer&quot;) \<br>    .config(&quot;spark.sql.inMemoryColumnarStorage.compressed&quot;, &quot;true&quot;) \<br>    .config(&quot;spark.dynamicAllocation.enabled&quot;, &quot;true&quot;) \<br>    .config(&quot;spark.sql.files.maxPartitionBytes&quot;, &quot;67108864&quot;) \  # 64 MB<br>    .getOrCreate()</pre><h4>How SparkSession work in Databricks</h4><p>In Databricks, SparkSession is automatically created when a cluster starts and is available as the pre-defined variable spark. It serves as the main entry point for working with DataFrames, SQL, and even RDDs (via spark.sparkContext). You don’t need to manually create it, but you can customize its behavior using spark.conf.set() for session-scoped settings. For deeper configuration changes like executor memory or core settings, use the cluster’s Spark Config UI—these changes apply at startup and require a cluster restart. While SparkSession is flexible for most workloads, some low-level tuning still depends on pre-launch configuration.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2092c7fbbd39" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spark Architecture Explained: DAG, Executors, Stages & Tasks simplified]]></title>
            <link>https://medium.com/@mohanaslvn/spark-architecture-explained-dag-executors-stages-tasks-simplified-80e46b9989fa?source=rss-38b11276ad1e------2</link>
            <guid isPermaLink="false">https://medium.com/p/80e46b9989fa</guid>
            <category><![CDATA[basics]]></category>
            <category><![CDATA[dağ]]></category>
            <category><![CDATA[executor]]></category>
            <category><![CDATA[spark-architecture]]></category>
            <category><![CDATA[with-examples]]></category>
            <dc:creator><![CDATA[Mohanaselvan Kathamuthu]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 17:11:10 GMT</pubDate>
            <atom:updated>2025-06-24T17:11:10.926Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A beginner-friendly guide to understanding how Apache Spark breaks down your code into DAGs, stages, and tasks behind the scenes</em></p><h3><strong>History</strong></h3><p>In the late 1990s and early 2000s, most organizations relied on RDBMS(Relational Database Management System) like Oracle, MySQL or SQL Server to store and process data. These systems worked well for structured data such as sales record, customer information and transactional logs usually in the range of gigabytes to a few terabytes and ran on single servers.</p><p>However, by the 2010s, with the rise of smartphones, social media and IoT devices, data begun pouring in from logs, Sensors and user interactions, growing into petabyte-scale and beyond. This marked the beginning of the Big Data era, where traditional systems couldn’t scale or process such high-volume, high-velocity data efficiently.</p><p>To solve this, Hadoop introduced a distributed approach using HDFS for storage and Map Reduce for batch processing, enabling large-scale data handling across clusters. But it was slow for iterative or real time tasks due to its disk-heavy processing model. That gap led to the rise of Apache Spark in the early 2010s, which offered much faster performance using in-memory computation, making it ideal for modern analytics and data pipelines.</p><h4><strong>Spark Core Architecture Overview</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*MVk_K2mw1H3WlCYy.jpg" /></figure><p>Apache Spark is designed to process large-scale data in a distributed and fault-tolerant manner. Its architecture breaks down complex data processing tasks into smaller, parallelizable units that can be executed efficiently across a cluster. At the core of Spark lies a set of tightly integrated components that work together to manage resources, schedule tasks, and handle distributed execution.</p><h3>🔑 Key Components of Spark Architecture</h3><ol><li><strong>Driver: </strong>The central coordinator of a Spark application. It converts user code into jobs and manages execution planning and task scheduling.</li><li><strong>SparkContext: </strong>The main entry point for interacting with Spark. It connects the driver to the cluster manager and initializes necessary services.</li><li><strong>Cluster Manager: </strong>Allocates resources (CPU, memory) to Spark applications. Supported options include YARN, Kubernetes, Mesos, and Standalone.</li><li><strong>Executors: </strong>Distributed worker processes launched on cluster nodes. They run the actual tasks and handle data storage (memory/disk).</li><li><strong>Tasks: </strong>The smallest unit of work assigned to executors. Each task processes data from a specific partition.</li><li><strong>Stages: </strong>Logical divisions within a Spark job, formed by breaking the DAG at shuffle boundaries. They help optimize and parallelize execution.</li><li><strong>DAG (Directed Acyclic Graph): </strong>A graph representation of all operations (transformations and actions). Spark uses it to plan and optimize job execution.</li><li><strong>RDD (Resilient Distributed Dataset): </strong>The low-level, fault-tolerant collection of data partitioned across the cluster. It forms the backbone of Spark’s data processing model.</li></ol><h4><strong>What is Databricks and How It Fits into Spark Architecture</strong></h4><p>Databricks provides a managed Spark environment that handles infrastructure, resource allocation, and scaling automatically. While the core Spark architecture — Driver, Executors, DAGs, and Tasks — remains unchanged. In essence, Databricks makes it easier and faster to develop, deploy, and scale Spark applications without worrying about low-level cluster management.</p><h3>Scenario: Processing Customer Data with Date Conversion and Grouping</h3><p>You’re working with a large CSV file containing customer information stored in S3 or DBFS. The data includes a created_date in &quot;MM/dd/yyyy&quot; format and a country column. Your goal is to:</p><ol><li>Read the data,</li><li>Convert the date to &quot;yyyy-MM-dd&quot; format,</li><li>Group the data by country and created_date to count new users per country per day,</li><li>Write the result back as CSV.</li></ol><blockquote>from pyspark.sql.functions import to_date, date_format</blockquote><blockquote>df = spark.read.csv(“s3://data/customer.csv”, header=True)</blockquote><blockquote>df2 = df.withColumn(<br> “created_date”,<br> date_format(to_date(“created_date”, “MM/dd/yyyy”), “yyyy-MM-dd”)<br>)</blockquote><blockquote>result = df2.groupBy(“country”, “created_date”).count()</blockquote><blockquote>result.write.mode(“overwrite”).csv(“s3://data/processed/user_count/”)</blockquote><h3>How Each Spark Component Helps Process This Job</h3><h3>1️⃣Driver &amp; SparkContext — Application Entry</h3><ul><li>When your job starts, <strong>SparkContext</strong> is initialized on the <strong>Driver</strong>.</li><li>The <strong>Driver</strong> parses your code and builds a logical plan of actions (read, transform, write</li></ul><h3>2️⃣ DAG Creation — Building the Execution Plan</h3><ul><li>Spark lazily constructs a <strong>Directed Acyclic Graph (DAG)</strong> from your operations:</li><li>Read → Transform → GroupBy → Write</li><li>It captures dependencies between operations and identifies where data needs to be shuffled.</li><li>No execution happens yet — it’s all lazy!</li></ul><h3>3️⃣ Cluster Manager — Allocating Resources</h3><ul><li>The <strong>Driver</strong> requests CPU and memory resources from the <strong>Cluster Manager</strong> (e.g., YARN or Kubernetes).</li><li>In response, multiple <strong>Executors</strong> are launched across the cluster.</li></ul><h3>4️⃣ Executors — Workers Ready to Execute</h3><ul><li><strong>Executors </strong>are launched on available cluster nodes.</li><li>Each executor is assigned <strong>tasks</strong> — these are specific units of work like reading a partition of the file or transforming a chunk of data.</li></ul><h3>5️⃣ Stage 1 — Reading &amp; Date Transformation (No Shuffle)</h3><ul><li>The first <strong>stage</strong> includes reading the CSV and applying withColumn to reformat the created_date.</li><li>This is a <strong>narrow transformation</strong> — each output partition depends on one input partition.</li><li>Spark assigns <strong>tasks</strong> to Executors, one per data partition (one task reads 64 MB of the CSV file)</li></ul><h3>6️⃣ Stage 2 — groupBy Causes a Shuffle</h3><ul><li>The groupBy(&quot;country&quot;, &quot;created_date&quot;) triggers a <strong>wide transformation</strong>.</li><li>Spark must <strong>repartition</strong> the data so that all rows for the same key land on the same executor.</li><li>This leads to <strong>shuffle</strong>, where:Data is written to disk by source partitions, sent over the network, Read and grouped by destination partitions on different executors.</li></ul><h3>7️⃣ Tasks Within Stages — Parallel Execution</h3><ul><li>Each <strong>stage</strong> is broken into <strong>tasks</strong>, and tasks are distributed to executors.</li><li>Stage 1 tasks read and reformat dates.</li><li>Stage 2 tasks shuffle, group, and count.</li><li>Stage 3 tasks write output to S3/DBFS.</li></ul><h3>8️⃣ RDDs — Fault Tolerance Backbone</h3><ul><li>Internally, Spark uses <strong>RDDs</strong> to manage partitions and transformation lineage.</li><li>If a task fails during the shuffle, Spark recomputes it using RDD lineage.</li></ul><h3>9️⃣ Stage 3 — Writing the Output</h3><ul><li>After aggregation, the final results are saved to s3://data/processed/user_count/.</li><li>Each executor writes out one or more output files (e.g., part-0001.csv).</li></ul><h3>🔚 Job Completion</h3><ul><li>The Driver monitors task progress and retries if needed.</li><li>Once all stages succeed, Spark gracefully shuts down executors and finalizes the job.</li></ul><h3>Conclusion</h3><p>Apache Spark’s architecture may look complex, but every component — from the Driver to DAGs and Executors — plays a clear role in efficient, distributed data processing. Understanding these building blocks helps you write better Spark jobs, debug faster, and scale with confidence — especially when using platforms like Databricks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80e46b9989fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>