<?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 Anupam Kumar on Medium]]></title>
        <description><![CDATA[Stories by Anupam Kumar on Medium]]></description>
        <link>https://medium.com/@anupamk36?source=rss-c4b6fd8a6c57------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Py6uJFT9MW4reiB8Ru28ZQ.jpeg</url>
            <title>Stories by Anupam Kumar on Medium</title>
            <link>https://medium.com/@anupamk36?source=rss-c4b6fd8a6c57------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 03:22:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@anupamk36/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[Designing Skew-Resilient Data Models: How Schema and Key Design Determine Spark Performance Years…]]></title>
            <link>https://medium.com/@anupamk36/designing-skew-resilient-data-models-how-schema-and-key-design-determine-spark-performance-years-13ca378b1a02?source=rss-c4b6fd8a6c57------2</link>
            <guid isPermaLink="false">https://medium.com/p/13ca378b1a02</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[apache-spark]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Anupam Kumar]]></dc:creator>
            <pubDate>Sat, 21 Feb 2026 03:55:30 GMT</pubDate>
            <atom:updated>2026-02-21T03:55:30.984Z</atom:updated>
            <content:encoded><![CDATA[<h3>Designing Skew-Resilient Data Models: How Schema and Key Design Determine Spark Performance Years Later</h3><p>Most teams try to fix Spark performance in the pipeline layer. Tuning partitions, enabling AQE, increasing executors etc etc.</p><p>Very few teams know the truth:</p><p><strong>Spark performance is largely predetermined by data modeling decisions.</strong></p><p>If skew is encoded into your schema, every downstream join, aggregation, and feature pipeline inherits that imbalance, sometimes for years.</p><p>This article explores how schema design, key strategy, and dimensional modeling directly shape shuffle entropy, spill probability, and long-term platform scalability.</p><h3>1. The Hidden Cost of Modeling Choices</h3><p>Consider two schemas:</p><h4>Schema A — Business Key Driven</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*H-3Zk1eukhOr_zNfzzKpXg.png" /></figure><h4>Schema B — Entropy-Aware Keying</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*Bcj4B8VMOQuEs7pnSXWTLA.png" /></figure><blockquote><strong>Both represent the same business reality.<br>Only one preserves distributed execution balance.</strong></blockquote><p>At TB scale, natural keys often introduce:</p><p>• extreme cardinality imbalance<br>• NULL concentration<br>• hot default values<br>• temporal hotspots</p><p>These become structural skew.</p><h3>2. Where Skew Actually Enters the System</h3><p>Skew is rarely introduced during joins — it is introduced earlier:</p><h4>A. Natural Keys</h4><p>Examples:</p><pre>country<br>status<br>tenant_id<br>campaign_id</pre><p>Typical distribution:</p><ul><li>a few dominant values</li><li>long tail of sparse keys</li></ul><p>This creates deterministic shuffle hotspots.</p><h4>B. Slowly Changing Dimensions</h4><p>SCD Type 2 tables frequently create:</p><ul><li>heavy “<strong><em>current</em></strong>” records</li><li>historical sparsity</li><li>join amplification on validity windows</li></ul><p>This produces temporal skew during joins and aggregations.</p><h4>C. Default / Null Modeling</h4><p>One of the biggest real-world skew sources:</p><pre>NULL<br>UNKNOWN<br>0<br>DEFAULT</pre><p>These can represent <strong>30–70% of rows</strong> in operational datasets.</p><h3>3. Entropy-First Modeling Principles</h3><p>Mature Data platforms adopt <strong>entropy preservation as a modeling goal</strong>.</p><p>Key techniques:</p><h4>Surrogate Keys with Distribution Awareness</h4><p>Instead of joining on:</p><pre>customer_email</pre><p>Use:</p><pre>customer_sk<br>distribution_bucket</pre><p>Distribution buckets can be:</p><ul><li>hash buckets</li><li>synthetic salts</li><li>time buckets</li><li>tenant shards</li></ul><p>This prevents heavy business keys from dominating shuffle.</p><h4>Degenerate Dimensions with Bucketing</h4><p>High-frequency attributes embedded in facts should include:</p><pre>event_type_bucket<br>tenant_bucket<br>geo_bucket</pre><p>This allows parallel aggregation even when business values are skewed.</p><h4>Fact Table Write-Time Entropy Injection</h4><p>Instead of fixing skew during reads, inject entropy during writes:</p><pre>distribution_bucket = hash(user_id) % N</pre><p>Downstream joins inherit balanced partitioning automatically.</p><p>This is one of the highest leverage design decisions a platform can make.</p><h3>4. Dimensional Modeling and Long-Term Spark Performance</h3><p>Classic Kimball modeling was designed for OLAP databases, not distributed compute engines.</p><p>Spark introduces new considerations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tfuxUppx05WixhIG_asrmA.png" /></figure><p>Modern dimensional modeling needs <strong>execution awareness</strong>, not just semantic clarity.</p><h3>5. Real Platform Metrics (Entropy-Aware Redesign)</h3><p>A platform redesigning fact modeling observed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*i0f4gdfAAexFlOZy5l2jpw.png" /></figure><p><strong>No cluster scaling.<br>major pipeline rewrite.<br>Just schema and key redesign.</strong></p><h3>6. Engineering Pattern: Skew-Resilient Data Contracts</h3><p>Advanced platforms treat distribution as part of the contract:</p><p>Each dataset defines:</p><p>• expected key cardinality<br>• heavy key thresholds<br>• bucket strategy<br>• join strategy hints<br>• skew telemetry</p><p>This shifts skew handling from reactive tuning to proactive design.</p><h3>7. The Systems Insight</h3><p>Pipeline optimization is tactical.<br>Modeling decisions are strategic.</p><p>A skewed key introduced today can:</p><ul><li>inflate spill for years</li><li>force permanent salting logic</li><li>increase cluster costs</li><li>complicate feature engineering</li><li>degrade ML training pipelines</li></ul><p>Entropy lost at modeling time is expensive to recover later.</p><h3>Final Takeaway</h3><p>Spark performance is not just a compute problem — it is a <strong>data modeling problem</strong>.</p><p>Designing skew-resilient schemas means:</p><p>• separating business semantics from distribution strategy<br>• injecting entropy early<br>• using surrogate keys intentionally<br>• treating partition balance as a first-class requirement</p><p>Teams that adopt entropy-aware modeling build platforms that scale predictably as data grows — while others continuously fight skew in every pipeline.</p><p>In the next post, I’ll go even deeper into <strong>automated skew detection pipelines — how large platforms continuously measure entropy, identify heavy keys, and dynamically apply mitigation without manual tuning.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13ca378b1a02" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Inside Spark Shuffle: Memory Manager, Spill Mechanics, and Why Data Skew Causes 100× Spill…]]></title>
            <link>https://medium.com/@anupamk36/inside-spark-shuffle-memory-manager-spill-mechanics-and-why-data-skew-causes-100-spill-4e0afcf3f0a1?source=rss-c4b6fd8a6c57------2</link>
            <guid isPermaLink="false">https://medium.com/p/4e0afcf3f0a1</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Anupam Kumar]]></dc:creator>
            <pubDate>Sun, 15 Feb 2026 08:18:41 GMT</pubDate>
            <atom:updated>2026-02-15T08:18:41.082Z</atom:updated>
            <content:encoded><![CDATA[<h3>Inside Spark Shuffle: Memory Manager, Spill Mechanics, and Why Data Skew Causes 100× Spill Amplification</h3><p>Most engineers understand that shuffle is expensive, but at multi-terabyte scale the <strong>real performance killer is spill amplification</strong>, not shuffle itself.<br>Extreme skew can increase disk spill volume by <strong>40–100×</strong>, turning otherwise fast pipelines into multi-hour jobs.</p><p>This deep dive explains:</p><ul><li>How Spark shuffle memory actually works internally</li><li>The execution path from in-memory aggregation → spill → merge</li><li>Why skew multiplies spill amplification non-linearly</li><li>Engineering strategies used in large production clusters to control spill pressure</li></ul><h3>1. Spark Shuffle Execution Path (Reducer Side Internals)</h3><p>During a shuffle stage, each reducer executes the following pipeline:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*AQJ8fp0TplgqEx9rDWnV0Q.png" /></figure><p>Reducers use <strong>Execution Memory</strong> managed by Spark’s <strong>Unified Memory Manager</strong>, which dynamically shares memory between:</p><ul><li>Storage Memory (cache)</li><li>Execution Memory (shuffle / join / aggregation)</li></ul><p>Execution memory allocation:</p><pre>spark.memory.fraction (default 0.6)<br>spark.memory.storageFraction (default 0.5)</pre><p>Effective reducer execution memory per executor:</p><pre>executor_memory × 0.6 × (1 - storage_usage)</pre><p>When aggregation structures exceed available execution memory, Spark spills intermediate data to disk.</p><h3>2. What Actually Happens During Spill</h3><p>Reducers use either:</p><ul><li>UnsafeExternalSorter</li><li>ExternalAppendOnlyMap</li></ul><p>When memory fills:</p><ol><li>Current aggregation buffer is sorted</li><li>Serialized to spill file</li><li>Buffer cleared</li><li>Aggregation continues</li><li>Later all spill files are <strong>merged</strong></li></ol><p>Total spill cost includes:</p><ul><li>serialization CPU</li><li>disk write IO</li><li>disk read during merge</li><li>merge sort CPU</li><li>GC pressure</li></ul><p>Even moderate spill can slow a stage by <strong>2–3×</strong>.</p><h3>3. Why Skew Causes Spill Amplification (Non-Linear Effect)</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fdatawrapper.dwcdn.net%2FdVgFz%2F1%2F&amp;display_name=Datawrapper&amp;url=https%3A%2F%2Fdatawrapper.dwcdn.net%2FdVgFz%2F1%2F&amp;image=https%3A%2F%2Fdatawrapper.dwcdn.net%2FdVgFz%2Fplain-s.png%3Fv%3D1&amp;type=text%2Fhtml&amp;schema=dwcdn" width="600" height="227" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e15e1d6e52f11b38361d87e26904723/href">https://medium.com/media/2e15e1d6e52f11b38361d87e26904723/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xIN9tGXsA5BB-FR5Rw1J-Q.png" /></figure><h3><strong>Important insight:</strong></h3><p>Spill overhead grows <strong>quadratically</strong>, not linearly:</p><pre>Merge complexity ≈ O(n log n) across spill files</pre><p>Thus:</p><ul><li>10× larger partition → ~40–80× spill overhead</li><li>Disk IO saturates executor</li><li>CPU wasted in repeated merge cycles</li><li>Executor becomes IO-bound</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6TD_HM-Twz5rHQ1LXxxyyA.png" /></figure><p>The cluster appeared “underutilized” even though jobs ran slowly — a classic spill amplification signature.</p><h3>4. Hidden Interaction: Skew + JVM GC Pressure</h3><p>Large skewed reducers also produce:</p><ul><li>massive temporary object creation</li><li>large aggregation buffers</li><li>repeated serialization buffers</li><li>increased young-gen promotions</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j7CGtZ9-Xyz4I_JcdlorjA.png" /></figure><p>This is why skew often produces <strong>OutOfMemory errors even when executor memory appears sufficient</strong>.</p><h3>5. How Salting and AQE Reduce Spill Amplification</h3><p>Salting redistributes the heavy partition:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*0FNo-dLq5paxAqhiAb8THA.png" /></figure><ul><li>aggregation fits in execution memory</li><li>spill eliminated or minimized</li><li>merge phases disappear</li><li>disk IO collapses dramatically</li></ul><p>AQE skew splitting further reduces residual skew at runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*edVqqsYM_3ESUQkmb5Z5Uw.png" /></figure><blockquote><strong>Key engineering insight:</strong></blockquote><p>Salting reduces <strong>spill probability</strong>, AQE reduces <strong>residual imbalance</strong>.</p><h3>6. Principal-Level Engineering Practices Used in Large Clusters</h3><p>High-scale Spark platforms implement <strong>spill-aware pipeline engineering</strong>:</p><h3>A. Target Partition Sizing</h3><pre>target_partition_size = 1–3 GB (large clusters)</pre><h3>B. Skew Telemetry</h3><ul><li>partition size histograms</li><li>reducer spill metrics exported to monitoring</li><li>automatic heavy-key detection pipelines</li></ul><h3>C. Predictive Entropy Injection</h3><ul><li>salting known skew keys</li><li>dynamic salt cardinality selection</li><li>skew-aware join frameworks</li></ul><h3>D. Spill Guardrails</h3><pre>spark.shuffle.spill.compress = true<br>spark.reducer.maxSizeInFlight tuned<br>spark.memory.fraction tuned based on workload</pre><h3>7. The Core Systems Insight</h3><p>Most Spark tuning advice focuses on:</p><ul><li>executor memory</li><li>executor cores</li><li>shuffle partitions</li></ul><p>But large-scale performance is primarily governed by:</p><pre>Reducer Input Size → Spill Probability → Merge Amplification → Stage Runtime</pre><p>Skew increases reducer input size, which multiplies spill cost exponentially.</p><p>Thus, the most impactful Spark performance optimization at scale is <strong>entropy engineering before shuffle</strong>, not cluster scaling after the fact.</p><h3>Final Takeaway</h3><p>Shuffle is not inherently expensive.<br><strong>Unbalanced shuffle is expensive.</strong></p><p>When skew concentrates tens of gigabytes into a single reducer, Spark transitions from:</p><pre>Distributed parallel execution<br>        ↓<br>Disk-bound serial merge system</pre><p>Techniques like <strong>salting, AQE skew splitting, and entropy-aware partitioning</strong> convert Spark back into the massively parallel engine it was designed to be — often delivering <strong>5–10× stage acceleration and &gt;50% infrastructure cost savings</strong> in real-world pipelines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4e0afcf3f0a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LSM Tree vs B-Tree: Write-Optimized vs Read-Optimized Indexing]]></title>
            <link>https://medium.com/@anupamk36/lsm-tree-vs-b-tree-write-optimized-vs-read-optimized-indexing-5f5b54384c84?source=rss-c4b6fd8a6c57------2</link>
            <guid isPermaLink="false">https://medium.com/p/5f5b54384c84</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[database]]></category>
            <dc:creator><![CDATA[Anupam Kumar]]></dc:creator>
            <pubDate>Tue, 21 Oct 2025 07:46:44 GMT</pubDate>
            <atom:updated>2025-10-21T07:46:44.359Z</atom:updated>
            <content:encoded><![CDATA[<p>Modern storage engines are built around two dominant index structures. B-Trees and Log-Structured Merge (LSM) Trees. While both maintain sorted key-value data, their designs are fundamentally different: B-Trees minimize read latency, while LSM Trees maximize write throughput.</p><p>With some help from practical implementation and some from LLMs I am able to share this observation with you.</p><h3>1. Core Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/0*wXEQEXv0IUd8qLbk" /></figure><h3>2. Write Path: Random vs Sequential I/O</h3><h3>B-Tree Writes</h3><ul><li>Each insert/update requires:</li><li>Cost: ~2–3 random writes per update on HDD, ~0.5–1 ms latency.</li><li>Write Amplification (WA): 3–5× due to page splits and journaling.</li></ul><h3>LSM Writes</h3><ul><li>Data first lands in an in-memory memtable (usually a skiplist or <a href="https://www.geeksforgeeks.org/dsa/introduction-to-red-black-tree/">red-black tree</a>).</li><li>When full, it’s flushed as an <a href="https://www.geeksforgeeks.org/dbms/sstable-in-apache-cassandra/">SSTable</a> (immutable sorted file) — a sequential write.</li><li>Background compaction merges SSTables, preserving key order.</li><li>Cost: ~1 sequential write per record + background compaction.</li><li>WA: Typically 10–20×, but sequential — hence SSD/HDD-friendly.</li></ul><p>WA = (data written to flash memory / data written by the host)</p><p>Result: Sequential writes achieve 2–10× higher throughput than random writes on HDDs and 1.5–3× on SSDs. Example: RocksDB benchmarks show &gt;100 MB/s ingestion vs 10–20 MB/s for B-Tree (wired-tiger) under identical workloads.</p><h3>3. Read Path: Point and Range Lookups</h3><h3>B-Tree Reads</h3><ul><li>Single tree traversal → usually one random I/O.</li><li>Excellent for point lookups and range scans (data is clustered).</li><li>Low read amplification (RA ≈ 1–2×).</li></ul><h3>LSM Reads</h3><ul><li>Need to search:</li><li>Read Amplification (RA) = number of levels + compaction overlap. Typical: 5–20× more reads than B-Tree for point lookups, unless mitigated with Bloom filters and block cache.</li></ul><p>Result: On RocksDB-like engines, 95th percentile read latency is 1.5–3× higher than WiredTiger (B-Tree), especially for random reads.</p><h3>4. Compaction: The Hidden Cost of LSM Trees</h3><p>Compaction rewrites data multiple times across levels. If the size ratio (T) between levels is 10, total write amplification ≈ O(T / (T — 1)) * log_T(N/M).</p><p>For example:</p><ul><li>RocksDB with T=10, N/M=10⁴ → WA ≈ 12–15×.</li><li>However, because these are sequential writes, disks handle them efficiently.</li></ul><p>In contrast, B-Trees suffer random I/O fragmentation — latency spikes under write-heavy workloads.</p><h3>5. Summary Metric</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/0*fjZghi_JlYPNe2IR" /></figure><h3>6. Intuition: Why the Trade-off Exists</h3><p>The trade-off is simple physics:</p><ul><li>B-Trees mutate data <em>in place</em> → fewer reads but more random writes.</li><li>LSM Trees <em>append and merge</em> → fewer writes (sequential) but more reads (over multiple levels).</li></ul><p>In practice:</p><ul><li>Databases like MySQL/InnoDB, Postgres → B-Tree based (read-optimized).</li><li>RocksDB, Cassandra, LevelDB, ClickHouse MergeTree → LSM-based (write-optimized).</li></ul><h3>Conclusion</h3><p>LSM Trees shine when write throughput and sequential access patterns dominate ingestion pipelines, logs, and time-series workloads. B-Trees remain optimal for low-latency reads and transactional workloads.</p><p>In a world increasingly dominated by streaming and event-driven data, the LSM tree’s write-optimized, compaction-driven design is the cornerstone of modern storage engines.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5f5b54384c84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[API Pagination: Cursors, Limit-Offset, Timestamp pagination, Data Shuffling and Beyond.]]></title>
            <link>https://medium.com/@anupamk36/api-pagination-cursors-limit-offset-timestamp-pagination-data-shuffling-and-beyond-32636fc006af?source=rss-c4b6fd8a6c57------2</link>
            <guid isPermaLink="false">https://medium.com/p/32636fc006af</guid>
            <category><![CDATA[data]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[fastapi]]></category>
            <dc:creator><![CDATA[Anupam Kumar]]></dc:creator>
            <pubDate>Sat, 13 Jul 2024 05:31:17 GMT</pubDate>
            <atom:updated>2024-07-13T05:40:56.802Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re diving into API development and tackling large datasets, pagination is your best friend. Whether you’re a newbie to APIs or a seasoned pro aiming for top-notch data retrieval efficiency, this article has got you covered. We’ll explore limit-offset, cursor-based, timestamp-based approaches, data shuffling issues and much more. Let’s dive right in!</p><p>First of all, let’s create a dataset on postgres:</p><pre>-- Create table with auto-increment id<br>CREATE TABLE items(<br>    id SERIAL PRIMARY KEY, <br>    a BIGINT, <br>    b VARCHAR(1000), <br>    c TIMESTAMP, <br>    d BOOL, <br>    e FLOAT<br>);<br><br>-- Insert data into the table<br>INSERT INTO items (a, b, c, d, e)<br>SELECT<br>    (random() * 10000)::bigint, -- generates a random integer between 0 and 10,000, cast to a bigint <br>    ARRAY_TO_STRING(<br>        ARRAY(<br>            SELECT chr((65 + (random() * 25))::int) <br>            FROM generate_series(1, (1000 * random())::int)<br>        ), &#39;&#39;<br>    ), -- generates a random string of characters of variable length<br>    NOW() - random() * INTERVAL &#39;365 days&#39;, -- generates a random date within the past year <br>    random() &lt; 0.5, -- generates a random boolean value (true or false) <br>    random() * 100 -- generates a random floating-point number between 0 and 100<br>FROM generate_series(1, 1000000);</pre><h3>1. Limit-Offset Pagination</h3><h3>1.1. Basics of Limit-Offset Pagination</h3><p>Limit-offset pagination involves specifying the number of records to retrieve (limit) and the number of records to skip (offset). A typical SQL query might look like this:</p><pre>SELECT * FROM items ORDER BY id LIMIT 10 OFFSET 20;</pre><p>This retrieves 10 records starting from the 21st record.</p><h3>1.2. Advantages and Disadvantages</h3><h4>Advantages</h4><ul><li><strong>Simplicity</strong>: Easy to implement and understand.</li><li><strong>Flexibility</strong>: Allows direct access to any page.</li></ul><h4>Disadvantages</h4><ul><li><strong>Performance</strong>: Performance degrades with increasing offset because the database must scan through all skipped records.</li><li><strong>Inconsistent Results</strong>: Underlying data changes between requests can result in inconsistent data.</li><li><strong>Duplicates and Missing Data</strong>: Data shuffling can cause duplicates or missing records.</li></ul><h3>1.3. Performance Metrics</h3><p>Let’s consider a dataset of 1 million records. We will benchmark the time taken to retrieve pages of 100 records at various offsets using PostgreSQL.</p><pre>-- Query for first page<br>SELECT * FROM items ORDER BY id LIMIT 100 OFFSET 0;<br>-- Query for 100th page<br>SELECT * FROM items ORDER BY id LIMIT 100 OFFSET 9900;<br>-- Query for 1000th page<br>SELECT * FROM items ORDER BY id LIMIT 100 OFFSET 999900;</pre><h4>Benchmark Results (These would differ based on your machine, data and the database that you’re using)</h4><ul><li><strong>First Page</strong>: ~2ms<br>Planning Time: 1.377 ms<br>Execution Time: 0.304 ms</li><li><strong>100th Page</strong>: ~16ms<br>Planning Time: 0.221 ms<br>Execution Time: 15.904 ms</li><li><strong>1000th Page</strong>: ~600ms<br>Planning Time: 0.221 ms<br>Execution Time: 597.888 ms</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*nr8S8aG4BBINbWfb.jpg" /></figure><p>As observed, the query time increases linearly with the offset. <strong>These metrics can be obtained by running </strong><strong>explain analyze on the postgres query.</strong></p><h3>1.4. Implementation in FastAPI</h3><pre>from fastapi import FastAPI, Query<br>from typing import List<br>from pydantic import BaseModel<br>import databases<br>import sqlalchemy<br><br>DATABASE_URL = &quot;postgresql://user:password@localhost/anupam&quot;<br>database = databases.Database(DATABASE_URL)<br>metadata = sqlalchemy.MetaData()<br><br># Define the table according to items schema<br>items = sqlalchemy.Table(<br>    &quot;items&quot;,<br>    metadata,<br>    sqlalchemy.Column(&quot;id&quot;, sqlalchemy.Integer, primary_key=True),<br>    sqlalchemy.Column(&quot;a&quot;, sqlalchemy.BigInteger),<br>    sqlalchemy.Column(&quot;b&quot;, sqlalchemy.String(length=1000)),<br>    sqlalchemy.Column(&quot;c&quot;, sqlalchemy.TIMESTAMP),<br>    sqlalchemy.Column(&quot;d&quot;, sqlalchemy.Boolean),<br>    sqlalchemy.Column(&quot;e&quot;, sqlalchemy.Float),<br>)<br><br>app = FastAPI()<br><br>class Item(BaseModel):<br>    id: int<br>    a: int<br>    b: str<br>    c: str<br>    d: bool<br>    e: float<br><br>@app.on_event(&quot;startup&quot;)<br>async def startup():<br>    await database.connect()<br><br>@app.on_event(&quot;shutdown&quot;)<br>async def shutdown():<br>    await database.disconnect()<br><br>@app.get(&quot;/items/&quot;, response_model=List[Item])<br>async def read_items(limit: int = Query(default=10, gt=0), offset: int = Query(default=0, ge=0)):<br>    query = items.select().limit(limit).offset(offset)<br>    return await database.fetch_all(query)</pre><h3>2. Cursor-Based Pagination</h3><h3>2.1. Basics of Cursor-Based Pagination</h3><p>Cursor-based pagination uses a unique identifier (cursor) to keep track of the position in the dataset. Instead of skipping records, the cursor points to the last item retrieved, and the next page starts from there.</p><h3>2.2. Advantages and Disadvantages</h3><h4>Advantages</h4><ul><li><strong>Efficiency</strong>: More performant, especially for large datasets, as it avoids scanning skipped records.</li><li><strong>Consistency</strong>: Provides more consistent results in dynamic datasets.</li></ul><h4>Disadvantages</h4><ul><li><strong>Complexity</strong>: More complex to implement.</li><li><strong>Inflexibility</strong>: Difficult to jump to an arbitrary page directly.</li></ul><h3>2.3. Performance Metrics</h3><p>For the same 1 million record dataset, we benchmark cursor-based pagination:</p><pre>-- Query for first page<br>SELECT * FROM items WHERE id &gt; 0 ORDER BY id LIMIT 100;<br>-- Query for next page<br>SELECT * FROM items WHERE id &gt; 100 ORDER BY id LIMIT 100;<br>-- Query for last page<br>SELECT * FROM items WHERE id &gt; 999900 ORDER BY id LIMIT 100;</pre><h4>Benchmark Results</h4><ul><li><strong>First Page</strong>: ~0.150 ms<br>Planning Time: 0.110 ms<br>Execution Time: 0.064ms</li><li><strong>100th Page</strong>: ~0.150 ms<br>Planning Time: 0.117 ms<br>Execution Time: 0.042 ms</li><li><strong>1000th Page</strong>: ~0.150 ms<br>Planning Time: 0.115 ms<br>Execution Time: 0.048 ms</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/639/0*bZsdx-R9uE3S0386.jpg" /></figure><p>The query time remains constant, regardless of the dataset size. This is a huge win already!</p><h3>2.4. Implementation in FastAPI</h3><pre>from fastapi import FastAPI, Query<br>from typing import List, Optional<br>from pydantic import BaseModel<br>import databases<br>import sqlalchemy<br><br>DATABASE_URL = &quot;postgresql://user:password@localhost/anupam&quot;<br>database = databases.Database(DATABASE_URL)<br>metadata = sqlalchemy.MetaData()<br><br># Define the table according to items schema<br>items = sqlalchemy.Table(<br>    &quot;items&quot;,<br>    metadata,<br>    sqlalchemy.Column(&quot;id&quot;, sqlalchemy.Integer, primary_key=True),<br>    sqlalchemy.Column(&quot;a&quot;, sqlalchemy.BigInteger),<br>    sqlalchemy.Column(&quot;b&quot;, sqlalchemy.String(length=1000)),<br>    sqlalchemy.Column(&quot;c&quot;, sqlalchemy.TIMESTAMP),<br>    sqlalchemy.Column(&quot;d&quot;, sqlalchemy.Boolean),<br>    sqlalchemy.Column(&quot;e&quot;, sqlalchemy.Float),<br>)<br><br>app = FastAPI()<br><br>class Item(BaseModel):<br>    id: int<br>    a: int<br>    b: str<br>    c: str<br>    d: bool<br>    e: float<br><br>@app.on_event(&quot;startup&quot;)<br>async def startup():<br>    await database.connect()<br><br>@app.on_event(&quot;shutdown&quot;)<br>async def shutdown():<br>    await database.disconnect()<br><br>@app.get(&quot;/items/&quot;, response_model=List[Item])<br>async def read_items(limit: int = Query(default=10, gt=0), cursor: Optional[int] = None):<br>    if cursor:<br>        query = items.select().where(items.c.id &gt; cursor).order_by(items.c.id).limit(limit)<br>    else:<br>        query = items.select().order_by(items.c.id).limit(limit)<br>    return await database.fetch_all(query)</pre><h3>3. Handling Data Shuffling and Inconsistencies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/0*RjOrlb8wcp-Yam1d.jpg" /></figure><h3>3.1. The Problem of Data Shuffling</h3><p>Data changes between paginated requests can lead to inconsistencies. For instance, new records might push existing records to the next page, causing duplicates or missing records.</p><h3>3.2. Solutions</h3><ul><li><strong>Timestamps</strong>: Use timestamps as cursors to ensure records created before a certain point are fetched, reducing the likelihood of missing records.</li><li><strong>Snapshot Isolation</strong>: Use snapshot isolation to ensure that the data viewed by the query does not change during pagination.</li><li><strong>Stable Sorting</strong>: Use a stable sorting mechanism with additional tie-breaking criteria to ensure consistent ordering.</li></ul><h3>3.3. Example with Timestamps in FastAPI</h3><p>Using timestamps as cursors can mitigate data shuffling issues:</p><pre>from fastapi import FastAPI, Query<br>from typing import List, Optional<br>from pydantic import BaseModel<br>from datetime import datetime, timedelta<br>import databases<br>import sqlalchemy<br>from sqlalchemy import select, desc, func<br><br>DATABASE_URL = &quot;postgresql://user:password@localhost/anupam&quot;<br>database = databases.Database(DATABASE_URL)<br>metadata = sqlalchemy.MetaData()<br><br># Define SQLAlchemy table<br>items = sqlalchemy.Table(<br>    &quot;items&quot;,<br>    metadata,<br>    sqlalchemy.Column(&quot;id&quot;, sqlalchemy.Integer, primary_key=True),<br>    sqlalchemy.Column(&quot;name&quot;, sqlalchemy.String),<br>    sqlalchemy.Column(&quot;created_at&quot;, sqlalchemy.TIMESTAMP),<br>)<br><br>app = FastAPI()<br><br>class Item(BaseModel):<br>    id: int<br>    name: str<br>    created_at: datetime<br><br>@app.on_event(&quot;startup&quot;)<br>async def startup():<br>    await database.connect()<br><br>@app.on_event(&quot;shutdown&quot;)<br>async def shutdown():<br>    await database.disconnect()<br><br>@app.get(&quot;/items/&quot;, response_model=List[Item])<br>async def read_items(limit: int = Query(default=10, gt=0), cursor: Optional[datetime] = None):<br>    query = select([items]).order_by(desc(items.c.created_at)).limit(limit)<br>    <br>    if cursor:<br>        query = query.where(items.c.created_at &lt; cursor)<br>    <br>    result = await database.fetch_all(query)<br>    <br>    items_list = [<br>        Item(id=item[&#39;id&#39;], name=item[&#39;name&#39;], created_at=item[&#39;created_at&#39;]) <br>        for item in result<br>    ]<br>    <br>    return items_list</pre><h3>4. Key Considerations and Best Practices</h3><h3>4.1. Consistent Ordering</h3><p>Ensure the ordering of items is consistent between requests using unique columns for sorting (e.g., primary keys, timestamps).</p><h3>4.2. Handling Deletions</h3><p>Gracefully handle deletions. If items are deleted, the cursor might point to a non-existent record. Move the cursor to the next available record in such cases.</p><h3>4.3. Security Considerations</h3><p>Ensure cursors are not easily guessable. Use opaque tokens for cursors instead of exposing raw IDs or timestamps.</p><h3>4.4. API Documentation</h3><p>Clearly document the pagination mechanism in the API documentation, including how to use cursors, limits, and any edge cases.</p><h3>Conclusion</h3><p>Pagination is a fundamental aspect of API design, especially for large datasets. Limit-offset pagination is simple but can be inefficient and inconsistent (for small datasets and use-cases where latency isn’t that big of a deal). Cursor-based pagination offers better performance and consistency but at the cost of complexity. Understanding the trade-offs and implementing best practices can help design robust and efficient paginated APIs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N23JviPjZUIxQGh4f_PoDg.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32636fc006af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Airflow Best Practices]]></title>
            <link>https://medium.com/@anupamk36/airflow-best-practices-d982fabd61f6?source=rss-c4b6fd8a6c57------2</link>
            <guid isPermaLink="false">https://medium.com/p/d982fabd61f6</guid>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Anupam Kumar]]></dc:creator>
            <pubDate>Sun, 28 Jan 2024 06:43:11 GMT</pubDate>
            <atom:updated>2024-01-30T04:24:25.244Z</atom:updated>
            <content:encoded><![CDATA[<h3>Maximizing Efficiency: Best Practices for Airflow in Data Engineering.</h3><h4>A guide for your production Airflow Environment.</h4><h4>Introduction:</h4><p>Apache Airflow stands as a beacon of workflow orchestration. Yet, to harness its full potential, adherence to best practices is essential. From structuring workflows for peak efficiency to implementing robust error handling, this guide delves into the technical nuances that elevate Airflow from a tool to a cornerstone of data infrastructure. I have few ideas from my 3 years of experience working as a Data Engineer extensively using Airflow daily.</p><blockquote>1. Avoid writing the top level code:</blockquote><p>Bad<strong> </strong>example<strong>:</strong></p><pre>import pendulum<br><br>from airflow import DAG<br>from airflow.decorators import task<br>from helpers.utilities.aws import list_keys # Only for demonstration.<br><br>path_list = list_keys(prefix=&quot;&quot;, suffix=&quot;&quot;) # &lt;-- LET&#39;S NOT DO THIS<br><br>with DAG(<br>    dag_id=&quot;example_python_operator&quot;,<br>    schedule=None,<br>    start_date=pendulum.datetime(2021, 1, 1, tz=&quot;UTC&quot;),<br>    catchup=False,<br>    tags=[&quot;example&quot;],<br>) as dag:<br><br>    @task()<br>    def print_list():<br>    for path in path_list:<br>        print(path)<br><br>    print_list()</pre><p>This DAG will fail to parse if it takes more than 30 seconds to execute path_list = list_keys(prefix=&quot;&quot;, suffix=&quot;&quot;)</p><p>The default and suggested dagbag_import_timeout = 30 seconds.</p><p>Good<strong> </strong>example<strong>:</strong></p><pre>import pendulum<br><br>from airflow import DAG<br>from airflow.decorators import task<br><br>with DAG(<br>    dag_id=&quot;example_python_operator&quot;,<br>    schedule=None,<br>    start_date=pendulum.datetime(2021, 1, 1, tz=&quot;UTC&quot;),<br>    catchup=False,<br>    tags=[&quot;example&quot;],<br>) as dag:<br><br>    @task()<br>    def print_list():<br>    path_list = list_keys(prefix=&quot;&quot;, suffix=&quot;&quot;) # &lt;-- MOVED INSIDE THE TASK<br>    for path in path_list:<br>        print(path)<br><br>    print_list()</pre><blockquote>Harnessing Connections for Secure Access to External Systems</blockquote><p>In Apache Airflow, connections serve as a centralised vault for securely managing diverse external system credentials, including databases like MySQL, PostgreSQL, MongoDB, cloud services such as AWS S3 and APIs like Salesforce etc. By avoiding hardcoded credentials, Airflow connections streamline access to various systems, ensuring security, reusability, and standardized credential management across workflows</p><p>Here’s an example of running an insert query using connections in Airflow for both MySQL and PostgreSQL databases:</p><pre>from airflow import DAG<br>from airflow.hooks.mysql_hook import MySqlHook<br>from airflow.hooks.postgres_hook import PostgresHook<br><br># Example DAG<br>with DAG(&#39;insert_using_connections&#39;, schedule_interval=None) as dag:<br><br>    # Inserting data into MySQL table using connection<br>    def insert_into_mysql():<br>        mysql_conn = MySqlHook(mysql_conn_id=&#39;mysql_conn_example&#39;)<br>        sql_query = &quot;INSERT INTO your_table (column1, column2) VALUES (%s, %s)&quot;<br>        data_to_insert = (&#39;value1&#39;, &#39;value2&#39;)  # Replace with your data<br>        mysql_conn.run(sql_query, parameters=data_to_insert)<br>        print(&quot;Data inserted into MySQL table successfully.&quot;)<br><br>    # Inserting data into PostgreSQL table using connection<br>    def insert_into_postgres():<br>        postgres_conn = PostgresHook(postgres_conn_id=&#39;postgres_conn_example&#39;)<br>        sql_query = &quot;INSERT INTO your_table (column1, column2) VALUES (%s, %s)&quot;<br>        data_to_insert = (&#39;value1&#39;, &#39;value2&#39;)  # Replace with your data<br>        postgres_conn.run(sql_query, parameters=data_to_insert)<br>        print(&quot;Data inserted into PostgreSQL table successfully.&quot;)<br><br>    # Task to run MySQL insert query<br>    mysql_insert_task = PythonOperator(<br>        task_id=&#39;insert_into_mysql_table&#39;,<br>        python_callable=insert_into_mysql<br>    )<br><br>    # Task to run PostgreSQL insert query<br>    postgres_insert_task = PythonOperator(<br>        task_id=&#39;insert_into_postgres_table&#39;,<br>        python_callable=insert_into_postgres<br>    )<br><br>    # Set task dependencies<br>    mysql_insert_task &gt;&gt; postgres_insert_task</pre><blockquote>Airflow Variables and how to use them :</blockquote><p>Utilising Airflow Variables rather than hardcoded ones in the code is advisable, especially for variables that remain relatively constant. However, accessing these Airflow Variables can involve network calls and database access. Hence, it’s recommended to refrain from direct variable access in top-level code. Instead, employing Airflow Variables within existing operators through Jinja templates can be advantageous as it limits calls to these variables only during task execution.</p><p><strong>Bad Example:</strong></p><pre>from airflow.models import Variable<br><br>foo_var = Variable.get(&quot;foo&quot;)  # AVOID THAT<br>bash_use_variable_bad_1 = BashOperator(<br>    task_id=&quot;bash_use_variable_bad_1&quot;, bash_command=&quot;echo variable foo=${foo_env}&quot;, env={&quot;foo_env&quot;: foo_var}<br>)</pre><p><strong>Good Example:</strong></p><pre>bash_use_variable_good = BashOperator(<br>    task_id=&quot;bash_use_variable_good&quot;,<br>    bash_command=&quot;echo variable foo=${foo_env}&quot;,<br>    env={&quot;foo_env&quot;: &quot;{{ var.value.get(&#39;foo&#39;) }}&quot;}, # THIS IS THE BEST WAY<br>)</pre><blockquote>Leveraging Airflow Operators for Streamlined Task Orchestration:</blockquote><p>Utilising Airflow Operators instead of manually maintaining code whenever possible is a good practice in workflow orchestration. Airflow Operators encapsulate reusable and predefined functionalities, allowing for streamlined task execution without the need for extensive manual coding. By leveraging these built-in Operators, developers can enhance efficiency, reduce code redundancy, and ensure consistency across tasks within workflows. Moreover, relying on Airflow’s pre-built Operators simplifies maintenance, as updates or modifications can be uniformly applied across tasks, promoting code consistency and facilitating easier debugging and scalability in complex workflows.</p><p><strong>Few examples:</strong></p><ol><li><strong>S3FileTransformOperator:</strong> Performs data transformations on files stored in Amazon S3.</li><li><strong>SalesforceToFileOperator:</strong> Extracts data from Salesforce and saves it to a file.</li><li><strong>DatabricksRunNowOperator:</strong> Submits a notebook or job run to Databricks.</li></ol><p>Few examples :</p><ul><li>To check if the file is present on S3 path:</li></ul><pre>task = PushToS3(...)<br>check = S3KeySensor(<br>    task_id=&quot;check_json_exists&quot;,<br>    bucket_key=&quot;s3://milkpond-prod/inside_out/wizer_insights.json&quot;,<br>    timeout=2,<br>)<br>task &gt;&gt; check</pre><ul><li>Writing to any database : (Postgres Hook)</li></ul><pre>def load_data_to_rds(**kwargs) -&gt; None:<br><br>    insert_query = &quot;&quot;&quot;<br>        INSERT INTO your_table_name (field1, field2, field3)<br>        VALUES (%s, %s, %s)<br>        ON CONFLICT(guid) DO NOTHING<br>        &quot;&quot;&quot;<br>    <br>    postgres_conn_id = kwargs[&#39;dag&#39;].default_args.get(&#39;postgres_conn_id&#39;)<br>    postgres_hook = PostgresHook(postgres_conn_id=postgres_conn_id)<br>    <br>    try:<br>        channel_data = data.get(&#39;rss&#39;, {}).get(&#39;channel&#39;, {})<br>        items = channel_data.get(&#39;item&#39;, [])<br><br>        for item in items:<br>            field1 = item.get(&#39;link&#39;, &#39;&#39;)<br>            field2 = item.get(&#39;guid&#39;, {}).get(&#39;#text&#39;, &#39;&#39;)<br>            field3 = item.get(&#39;title&#39;, &#39;&#39;)<br><br>            postgres_hook.run(<br>                insert_query,<br>                parameters=(field1, field2, field3),<br>            )<br>    except Exception as e:<br>        logging.error(f&quot;Error loading data to RDS: {str(e)}&quot;)<br>        raise</pre><blockquote>Optimising Task Execution in DAGs: Managing Resource-Heavy and Long-Running Processes.</blockquote><p>DAGs (Directed Acyclic Graphs) aren’t ideal for tasks that are resource-heavy or take a long time. Instead, use parallelism techniques to split these tasks into smaller, concurrent ones. Long-running DAGs can tie up resources, blocking other tasks. Aim for reasonable task durations within the DAG, considering resource utilisation and avoiding prolonged allocation of workers to prevent workflow delays.</p><p>What is an ideal task execution time? Depends on the frequency, if it’s a less frequent DAGs(weekly or more) we could keep it running for couple hours but for more frequent DAGs couple minutes should be the limit since the task blocks workers and puts others tasks on queue.</p><p><strong>Note : If you have a resource heavy task you could possibly use KubernetesPodOperator.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2BHkBUcEeRIa6f3r" /></figure><blockquote>PythonVirtualenvOperator and why?</blockquote><p>Managing complex Python dependencies in Airflow is crucial for smooth workflow execution. While predefined Airflow Operators help avoid conflicts, custom approaches or operators may encounter dependency clashes. One effective solution is using PythonVirtualenvOperator, creating independent virtual environments for tasks. This approach allows flexibility but introduces serialisation limitations and potential conflicts. However, it enables task isolation and diverse dependency sets on the same workers, streamlining workflow management in Airflow.</p><pre>from datetime import datetime<br>from airflow import DAG<br>from airflow.operators.python_operator import PythonVirtualenvOperator<br><br>def my_python_function():<br>    # Your Python code here<br>    result = &quot;Hello, Airflow!&quot;<br>    return result<br><br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;start_date&#39;: datetime(2023, 1, 1),<br>    # Add other necessary default arguments<br>}<br><br>with DAG(&#39;virtualenv_example&#39;, default_args=default_args, schedule_interval=&#39;@daily&#39;, catchup=False) as dag:<br>    task_using_virtualenv = PythonVirtualenvOperator(<br>        task_id=&#39;task_using_virtualenv&#39;,<br>        python_callable=my_python_function,<br>        requirements=[&#39;requests==2.26.0&#39;],  # Specify dependencies for this task<br>    )<br><br>    # Define other tasks as needed<br>    # task2 = ...<br>    # task3 = ...<br><br>    task_using_virtualenv<br>    # task2 &gt;&gt; task3  # Example task dependencies<br><br></pre><blockquote>XComs (cross-communication) in Airflow:</blockquote><p>XComs in Airflow serve as a means to exchange small amounts of data between tasks within a Directed Acyclic Graph (DAG). They offer a lightweight and efficient way to share information, such as task statuses, intermediate results, or metadata, between tasks. XComs can be utilized by tasks to pass data to downstream tasks, enabling coordination and communication within the workflow. They shouldn’t be used to carry large data. (Ideally should not be more than few kilo byte)</p><p><em>Utilization:</em> Tasks can use xcom_push() to send data to XComs, allowing downstream tasks to access this data using xcom_pull(). This mechanism facilitates inter-task communication and data sharing without the need for complex data storage or external systems. XComs are particularly useful for passing small amounts of transient data between tasks, aiding in workflow orchestration and enabling tasks to collaborate by sharing essential information during DAG execution.</p><p><strong>Example:</strong></p><pre>from datetime import datetime, timedelta<br>from airflow import DAG<br>from airflow.operators.python_operator import PythonOperator<br><br># Function to perform a task and push data to XCom<br>def push_data_to_xcom(**context):<br>    data_to_push = &quot;This is some data to be shared via XCom&quot;<br>    context[&#39;ti&#39;].xcom_push(key=&#39;my_data_key&#39;, value=data_to_push)<br>    print(&quot;Data pushed to XCom successfully!&quot;)<br><br># Function to retrieve data from XCom<br>def pull_data_from_xcom(**context):<br>    retrieved_data = context[&#39;ti&#39;].xcom_pull(key=&#39;my_data_key&#39;)<br>    print(&quot;Data retrieved from XCom:&quot;, retrieved_data)<br><br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;start_date&#39;: datetime(2023, 1, 1),<br>    &#39;retries&#39;: 1,<br>    &#39;retry_delay&#39;: timedelta(minutes=5),<br>}<br><br>with DAG(&#39;xcom_example&#39;, default_args=default_args, schedule_interval=&#39;@once&#39;, catchup=False) as dag:<br>    push_task = PythonOperator(<br>        task_id=&#39;push_task_to_xcom&#39;,<br>        python_callable=push_data_to_xcom<br>    )<br><br>    pull_task = PythonOperator(<br>        task_id=&#39;pull_task_from_xcom&#39;,<br>        python_callable=pull_data_from_xcom<br>    )<br><br>    # Set task dependencies<br>    push_task &gt;&gt; pull_task</pre><p>While a lot of us already use XComs, not all of us clear the XComs which leads to something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vLh_jJXcSvgDi-3Q" /></figure><p>Record Count:<strong> 9212381257124</strong></p><p><strong>A simple way to clear your XComs once it is used</strong>:</p><pre>from airflow import DAG<br>from airflow.operators.python_operator import PythonOperator<br>from airflow.utils.db import provide_session<br><br>@provide_session<br>def cleanup_xcom(context, session=None):<br>    dag_id = context[&quot;ti&quot;][&quot;dag_id&quot;]<br>    session.query(XCom).filter(XCom.dag_id == dag_id).delete()<br>    <br>def test_task_function():<br>    return &quot;This is a test task!&quot;<br><br>default_args = {<br>    &#39;owner&#39;: &#39;airflow&#39;,<br>    &#39;start_date&#39;: datetime(2023, 1, 1),<br>    # Add other necessary default arguments<br>}<br><br>with DAG(&#39;clear_xcom_example&#39;, default_args=default_args, schedule_interval=&#39;@daily&#39;, catchup=False) as dag:<br>    fetch_data_task = PythonOperator(<br>        task_id=&quot;test_task&quot;,<br>        python_callable=test_task_function,<br>        provide_context=True,<br>        on_success_callback=cleanup_xcom # &lt;== This is how you can call your cleanup function.</pre><blockquote>Enhancing Security in Apache Airflow: Leveraging AWS Secrets Manager for Sensitive Data Management.</blockquote><p>Using AWS Secrets Manager is a secure and best practice approach to manage sensitive information, such as API keys, passwords, or tokens, within applications or workflows, including those in Apache Airflow. Rather than hardcoding secrets directly into files, AWS Secrets Manager offers a centralized and encrypted storage service to securely store, retrieve, and manage sensitive data. Integrating with AWS Secrets Manager allows Airflow DAGs or applications to dynamically fetch credentials or secrets during runtime, enhancing security by reducing exposure to hardcoded secrets in plain text. This method enables easier secret rotation, compliance with security policies, and restricts access to sensitive information only to authorized users or services with the appropriate permissions, enhancing overall security posture within the workflow environment.</p><p>We should have a helper function that can <strong><em>read from </em>or <em>write to </em>Amazon secrets. </strong>It’s not a good idea to keep all the credentials in a config and expose it to everyone.</p><h4>Reading Secrets from AWS Secrets Manager:</h4><pre>import boto3<br>from botocore.exceptions import ClientError<br>import json<br><br>def get_secret(secret_name):<br>    session = boto3.session.Session()<br>    client = session.client(service_name=&#39;secretsmanager&#39;)<br><br>    try:<br>        get_secret_value_response = client.get_secret_value(SecretId=secret_name)<br>        <br>        if &#39;SecretString&#39; in get_secret_value_response:<br>            secret = get_secret_value_response[&#39;SecretString&#39;]<br>            return json.loads(secret)  # Return secret as a dictionary (if in JSON format)<br>        else:<br>            # Handling binary secrets (if required)<br>            decoded_binary_secret = base64.b64decode(get_secret_value_response[&#39;SecretBinary&#39;])<br>            return decoded_binary_secret<br>    except ClientError as e:<br>        if e.response[&#39;Error&#39;][&#39;Code&#39;] == &#39;ResourceNotFoundException&#39;:<br>            print(&quot;The requested secret was not found&quot;)<br>        elif e.response[&#39;Error&#39;][&#39;Code&#39;] == &#39;InvalidRequestException&#39;:<br>            print(&quot;The request was invalid due to:&quot;, e)<br>        elif e.response[&#39;Error&#39;][&#39;Code&#39;] == &#39;InvalidParameterException&#39;:<br>            print(&quot;The request had invalid params:&quot;, e)<br>        # Handle other exceptions as needed<br><br># Usage Example:<br># Replace &#39;your-secret-name&#39; with the actual name of your secret in AWS Secrets Manager<br>secret_name = &#39;your-secret-name&#39;<br>retrieved_secret = get_secret(secret_name)<br>print(retrieved_secret)  # Use the retrieved secret as needed</pre><h4>Writing Secrets to AWS Secrets Manager:</h4><pre>import boto3<br>import json<br><br>def put_secret(secret_name, secret_value):<br>    session = boto3.session.Session()<br>    client = session.client(service_name=&#39;secretsmanager&#39;)<br><br>    try:<br>        secret_string = json.dumps(secret_value)  # Convert secret to JSON string<br>        response = client.create_secret(<br>            Name=secret_name,<br>            SecretString=secret_string,<br>            Description=&#39;Your secret description&#39;,  # Optional: Description of the secret<br>            # Other optional parameters can be added as needed<br>        )<br>        print(&quot;Secret created successfully:&quot;, response)<br>    except client.exceptions.ResourceExistsException:<br>        print(&quot;Secret already exists with the specified name&quot;)<br>    except client.exceptions.ClientError as e:<br>        print(&quot;Error occurred while creating the secret:&quot;, e)<br><br># Usage Example:<br># Replace &#39;your-secret-name&#39; with the name you want to give to your secret<br># Replace {&#39;your&#39;: &#39;secret&#39;} with the actual secret you want to store<br>secret_name = &#39;your-secret-name&#39;<br>secret_value = {&#39;your&#39;: &#39;secret&#39;}<br><br>put_secret(secret_name, secret_value)</pre><blockquote>Efficient DAG Categorisation with Tags in Apache Airflow:</blockquote><p>Tags in Apache Airflow facilitate effective DAG organization by enabling categorization based on ownership and purpose. Assigning tags like “data_acquisition,” “data_science,” or “machine_learning” to DAG configurations allows streamlined classification of workflows. This categorization simplifies management within the Airflow interface, aiding in easy grouping of similar tasks or processes. Incorporating owner-related tags alongside functional categorizations enhances workflow oversight, simplifying navigation for various stakeholders involved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fq2lvYqYpQqA3Bcl2gqPCQ.png" /></figure><blockquote>Unit Testing Operators and Tasks:</blockquote><ol><li><strong>Operator Testing:</strong> Write unit tests specifically targeting individual operators used within your DAG. Ensure that the operators perform as expected. For example, if you have a custom operator, create tests to validate its functionality in isolation.</li><li><strong>Task Logic Testing:</strong> If your DAG tasks contain complex logic or custom Python functions, create unit tests for these functions to verify their behaviour separately.</li></ol><h4>Integration Testing:</h4><ol><li><strong>Task Dependency and Flow Testing:</strong> Test the DAG’s task dependencies and workflow logic. Ensure that tasks execute in the expected order and are dependent on the success or failure of preceding tasks.</li></ol><h4>End-to-End Testing:</h4><ol><li><strong>Full DAG Execution Testing:</strong> Execute the DAG in a test environment that closely resembles the production environment. Validate that the entire DAG runs without errors, and its tasks execute as intended.</li><li><strong>Data Validation:</strong> If your DAG processes data, verify the data output or state after the DAG execution to ensure it matches the expected results.</li></ol><h4>Continuous Integration (CI) and Continuous Deployment (CD):</h4><ol><li><strong>Automated Testing in CI/CD Pipelines:</strong> Integrate DAG testing into your CI/CD pipelines. Run tests automatically on each code commit to catch issues early.</li></ol><h4>Logging and Error Handling:</h4><ol><li><strong>Error Handling Validation:</strong> Test error handling scenarios in your DAG, ensuring that errors are caught appropriately and that the DAG behaves as expected when encountering failures.</li></ol><h4>Manual Testing:</h4><ol><li><strong>Manual Run and Observation:</strong> Manually trigger the DAG in the Airflow UI or CLI and observe its behavior in real-time. This allows for ad-hoc testing and validation.</li><li><strong>Documentation Testing:</strong> Ensure your DAG documentation, such as docstrings and comments, accurately reflects the DAG’s functionality and purpose.</li></ol><blockquote>SUGGESTED BOILERPLATE CODE TEMPLATE:</blockquote><h4>1. DAG Configuration</h4><ul><li><strong>Owner Tag</strong>: Always specify the owner tag for each DAG to indicate the responsible individual or team.</li><li><strong>Start Date</strong>: Set an appropriate start date for the DAG to begin scheduling tasks.</li><li><strong>Retry Settings</strong>: Define suitable retry and retry delay parameters to handle task failures gracefully.</li><li><strong>Catchup</strong>: Set the catchup parameter based on whether historical DAG runs should be triggered.</li></ul><pre>default_args = {<br>    &quot;owner&quot;: &quot;Your_Owner_Name&quot;,<br>    &quot;start_date&quot;: datetime(YYYY, MM, DD),<br>    &quot;retries&quot;: 1,<br>    &quot;retry_delay&quot;: timedelta(minutes=5),<br>    &quot;catchup&quot;: False,<br>    # Add other necessary default arguments<br>}</pre><h4>2. Task Design</h4><ul><li><strong>Task Decomposition</strong>: Break down workflows into smaller tasks to enhance reusability and maintainability.</li><li><strong>Task Dependency</strong>: Clearly define dependencies among tasks using the &gt;&gt; operator or set_downstream methods.</li></ul><pre>with DAG(<br>    dag_id=&quot;Your_DAG_Name&quot;,<br>    default_args=default_args,<br>    schedule_interval=&quot;@daily&quot;,<br>    catchup=False,<br>) as dag:<br>    task_1 = PythonOperator(<br>        task_id=&quot;Task_1_ID&quot;,<br>        python_callable=your_function_1,<br>        provide_context=True,<br>    )<br><br>    task_2 = PythonOperator(<br>        task_id=&quot;Task_2_ID&quot;,<br>        python_callable=your_function_2,<br>        provide_context=True,<br>    )<br><br>    task_1 &gt;&gt; task_2  # Set task dependencies</pre><h4>3. Task Implementation</h4><ul><li><strong>Python Functions</strong>: Write modular and well-documented Python functions for each task.</li><li><strong>Error Handling</strong>: Implement appropriate error handling within each task function to handle exceptions gracefully.</li></ul><pre>def your_function_1(**kwargs):<br>    # Include your task logic here<br>    try:<br>        # Your task implementation<br>    except Exception as e:<br>        logging.error(f&quot;Error in task: {str(e)}&quot;)<br>        raise</pre><h4>4. Logging and Monitoring</h4><ul><li><strong>Logging</strong>: Use Python’s logging module to log task-specific information, errors, and warnings.</li><li><strong>Monitoring</strong>: Leverage Airflow’s UI and integrations with monitoring tools for task and DAG monitoring.</li></ul><pre>import logging<br><br>def your_function_1(**kwargs):<br>    try:<br>        # Your task implementation<br>        logging.info(&quot;Task 1 completed successfully.&quot;)<br>    except Exception as e:<br>        logging.error(f&quot;Error in task: {str(e)}&quot;)<br>        raise</pre><h4>5. XCom Usage</h4><ul><li><strong>XCom Usage</strong>: Use XCom to pass data between tasks when necessary, but avoid excessive reliance on it.</li></ul><pre>def your_function_1(**kwargs):<br>    # Your task logic<br>    return your_data_to_pass<br><br>def your_function_2(**kwargs):<br>    data_received = kwargs[&quot;ti&quot;].xcom_pull(task_ids=&quot;Task_1_ID&quot;)<br>    # Process received data</pre><h4>6. Documentation</h4><ul><li><strong>Inline Comments</strong>: Add descriptive comments within the code to explain complex logic or functionalities.</li><li><strong>External Documentation</strong>: Create external documentation to outline DAG structure, tasks, and data flow.</li></ul><h4>7. Testing and Validation</h4><ul><li><strong>Unit Testing</strong>: Perform unit tests on individual task functions to ensure expected behavior.</li><li><strong>Validation</strong>: Validate DAGs and tasks by running test instances to verify correct functionality.</li></ul><h3>Security:</h3><p>Use RBAC (Role-Based Access Control) to manage access to Airflow.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d982fabd61f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Supercharging Airflow DAGs for Data Acquisition: A Deep Dive into Metrics and Optimization]]></title>
            <link>https://medium.com/@anupamk36/supercharging-airflow-dags-for-data-acquisition-a-deep-dive-into-metrics-and-optimization-5e6f8c898c3c?source=rss-c4b6fd8a6c57------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e6f8c898c3c</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[airflow]]></category>
            <dc:creator><![CDATA[Anupam Kumar]]></dc:creator>
            <pubDate>Tue, 14 Nov 2023 04:57:10 GMT</pubDate>
            <atom:updated>2024-01-16T18:55:58.988Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In my role as a Data Engineer, delivering agile and robust data pipelines is not just a requirement; it’s a mission-critical objective. This post specifically targets Apache Airflow DAGs responsible for data acquisition, detailing the optimization strategies we’ve implemented, complete with relevant code snippets and before-and-after metrics.</p><h3>Baseline Metrics</h3><p>Before embarking on the optimization journey, we gathered the following metrics:</p><ul><li><strong>DAG Execution Time</strong>: 50 minutes</li><li><strong>Task Instance Duration</strong>: 7 minutes average</li><li><strong>CPU Utilization</strong>: Peaking at 85%</li><li><strong>Memory Utilization</strong>: Peaking at 80%</li></ul><h3>Scenario 1: Reducing DAG Execution Time by 30%</h3><h3>Problem</h3><p>Data volume increased, bloating our DAG execution time from 30 to 50 minutes.</p><h3>Parallel Execution</h3><p><strong>Code Change</strong></p><pre># airflow.cfg<br># Before: parallelism = 8<br># After: parallelism = 16</pre><p><strong>Metric Impact</strong></p><ul><li>DAG Execution Time: Reduced by 20%</li></ul><h3>Task Partitioning</h3><p><strong>Code Change</strong></p><pre># Before: One monolithic task<br># After: Breaking it down into smaller tasks<br>def process_partition(*args, **kwargs):<br>    partition_index = kwargs[&#39;partition_index&#39;]<br>    # Process 1/10th of the data<br>    # Process 2/10th of the data<br>    # Process 3/10th of the data<br>    ....</pre><pre>with DAG(&#39;data_acquisition_dag&#39;, ...) as dag:<br>    start_task = DummyOperator(task_id=&#39;start&#39;)<br>    end_task = DummyOperator(task_id=&#39;end&#39;)<br>  <br>    for i in range(10):<br>        partition_task = PythonOperator(<br>            task_id=f&#39;process_partition_{i}&#39;,<br>            python_callable=process_partition,<br>            op_args={&#39;partition_index&#39;: i},<br>        )<br>        start_task &gt;&gt; partition_task &gt;&gt; end_taskp</pre><p><strong>Metric Impact</strong></p><ul><li>DAG Execution Time: Further reduced by 15%</li></ul><h3>Overall Improvement</h3><p>DAG Execution Time: Reduced to 32.5 minutes (35% improvement)</p><h3>Scenario 2: Optimizing Task Dependencies</h3><h3>Problem</h3><p>Poor task dependency design was leading to inefficient CPU and memory utilization.</p><h3>Code Change</h3><pre># Before: Sequential dependency<br>start_task &gt;&gt; task1 &gt;&gt; task2 &gt;&gt; task3 &gt;&gt; end_task</pre><pre># After: Optimal task dependency<br>cross_downstream([start_task], [task1, task2, task3])<br>cross_upstream([task1, task2, task3], [end_task])</pre><p><strong>Metric Impact</strong></p><ul><li>CPU Utilization: Improved by 10% (now peaks at 76%)</li><li>Memory Utilization: Improved by 10% (now peaks at 72%)</li></ul><h3>Scenario 3: Handling API Rate Limits</h3><h3>Problem</h3><p>API rate limits were causing frequent task failures, leading to overall DAG failures.</p><h3>Code Change</h3><pre># Before: Limited retry mechanism<br># retries = 2</pre><pre># After: Enhanced retry mechanism<br>api_task = PythonOperator(<br>    task_id=&#39;fetch_from_api&#39;,<br>    python_callable=fetch_from_api,<br>    retries=5,<br>    retry_delay=timedelta(minutes=5),<br>)</pre><p><strong>Metric Impact</strong></p><ul><li>Task Failure Rate: Reduced to 0% for this particular task</li></ul><h3>Conclusion</h3><p>Our targeted optimizations yielded impressive results:</p><ul><li><strong>DAG Execution Time</strong>: Reduced by 35% to 32.5 minutes</li><li><strong>CPU Utilization</strong>: Peaking at 76%, a 10% efficiency gain</li><li><strong>Task Failure Rate</strong>: Down to 0% for API tasks</li></ul><p>By integrating code-level changes with metrics, we achieved significant improvements in our Airflow DAGs for data acquisition in the cyber insurance domain.</p><p>I hope this updated post offers both the depth and detail you’re seeking, particularly emphasizing real-world code changes and their measurable impacts.</p><p>Would love to hear more about your own challenges and successes with Airflow optimization!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e6f8c898c3c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monitoring and Alerting in Airflow: Maximising Workflow Reliability]]></title>
            <link>https://medium.com/@anupamk36/monitoring-and-alerting-in-airflow-maximising-workflow-reliability-5eac45e2e301?source=rss-c4b6fd8a6c57------2</link>
            <guid isPermaLink="false">https://medium.com/p/5eac45e2e301</guid>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[slack]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-engineering]]></category>
            <dc:creator><![CDATA[Anupam Kumar]]></dc:creator>
            <pubDate>Thu, 01 Jun 2023 09:03:40 GMT</pubDate>
            <atom:updated>2023-06-01T09:03:40.062Z</atom:updated>
            <content:encoded><![CDATA[<p>Introduction: Apache Airflow has revolutionised workflow management with its flexibility and scalability. To ensure the smooth execution of your Airflow workflows, it is crucial to establish robust monitoring and alerting mechanisms. In this article, we will delve into different approaches for monitoring and alerting in Airflow, with a focus on integrating external monitoring systems like Prometheus, Grafana, or Datadog. We will also explore how to set up alerts for task failures, delays, and other critical events, empowering you to proactively manage and troubleshoot your Airflow deployments.</p><ol><li>Monitoring Airflow Workflows: Monitoring plays a vital role in ensuring the reliability and performance of your Airflow workflows. It helps detect issues, analyze trends, and optimize resource utilization. Let’s explore some popular monitoring tools and their integration with Airflow.</li></ol><p>a. Prometheus: Prometheus is an open-source monitoring and alerting toolkit. To integrate Airflow with Prometheus, you can set up exporters or collectors in Airflow to expose metrics related to task execution, DAG performance, and resource utilization. Here’s an example configuration for Airflow’s Prometheus exporter:</p><pre># pythonCopy code<br># airflow.cfg<br># Configure the Prometheus Exporter<br>[metrics]<br>statsd_on = False<br>statsd_host = localhost<br>statsd_port = 8125<br>statsd_prefix = airflow</pre><p>b. Grafana: Grafana is a powerful data visualisation and exploration tool that can be integrated with Prometheus. You can create customised Grafana dashboards to monitor key metrics such as task execution times, DAG status, or resource utilisation. Here’s an example Grafana dashboard JSON for Airflow:</p><pre># jsonCopy code<br>{<br>  &quot;dashboard&quot;: {<br>    &quot;title&quot;: &quot;Airflow Workflow Metrics&quot;,<br>    &quot;panels&quot;: [<br>      {<br>        &quot;title&quot;: &quot;Task Execution Times&quot;,<br>        &quot;type&quot;: &quot;graph&quot;,<br>        &quot;datasource&quot;: &quot;Prometheus&quot;,<br>        &quot;targets&quot;: [<br>          {<br>            &quot;expr&quot;: &quot;avg(airflow_task_execution_time_seconds)&quot;<br>          }<br>        ]<br>      },<br>      {<br>        &quot;title&quot;: &quot;DAG Status&quot;,<br>        &quot;type&quot;: &quot;singlestat&quot;,<br>        &quot;datasource&quot;: &quot;Prometheus&quot;,<br>        &quot;targets&quot;: [<br>          {<br>            &quot;expr&quot;: &quot;airflow_dag_status&quot;<br>          }<br>        ]<br>      },<br>      {<br>        &quot;title&quot;: &quot;Resource Utilization&quot;,<br>        &quot;type&quot;: &quot;graph&quot;,<br>        &quot;datasource&quot;: &quot;Prometheus&quot;,<br>        &quot;targets&quot;: [<br>          {<br>            &quot;expr&quot;: &quot;avg(airflow_resource_utilization)&quot;<br>          }<br>        ]<br>      }<br>    ]<br>  }<br>}</pre><p>c. Datadog: Datadog is a monitoring and analytics platform that allows you to collect, analyse, and visualize metrics from various sources. You can integrate Airflow with Datadog by configuring the Datadog agent and leveraging the Airflow integration. Explore the available metrics and visualisations specific to Airflow in the Datadog platform.</p><p>2. Setting Up Alerts in Airflow: Setting up alerts is crucial to proactively manage your Airflow workflows. By defining specific events or conditions, you can receive notifications when critical issues occur. Let’s discuss how to set up alerts using Prometheus Alertmanager, Grafana, or Datadog.</p><p>a. Prometheus Alertmanager: Prometheus Alertmanager is a component that handles alert notifications from Prometheus. You can define alert rules in the prometheus_rules.yml file. Here&#39;s an example configuration for alerting on Airflow task failures:</p><pre># yamlCopy code<br># prometheus_rules.yml<br><br>groups:<br>  - name: airflow_alerts<br>    rules:<br>      - alert: AirflowTaskFailure<br>        expr: airflow_task_failure_count &gt; 0<br>        for: 5m<br>        labels:<br>          severity: critical<br>        annotations:<br>          summary: &quot;Airflow task failed: {{ $labels.task_name }}&quot;<br>          description: &quot;Task &#39;{{ $labels.task_name }}&#39; in DAG &#39;{{ $labels.dag_id }}&#39; failed.&quot;<br><br>      - alert: AirflowDAGFailure<br>        expr: airflow_dag_failure_count &gt; 0<br>        for: 10m<br>        labels:<br>          severity: warning<br>        annotations:<br>          summary: &quot;Airflow DAG failed: {{ $labels.dag_id }}&quot;<br>          description: &quot;DAG &#39;{{ $labels.dag_id }}&#39; failed.&quot;<br><br>      # Add more alert rules as per your requirements</pre><p>Ensure that the prometheus_rules.yml file is mounted and configured in your Prometheus deployment.</p><p>— Custom Monitoring and Alerting Plugins:</p><p>Airflow allows you to create custom monitoring and alerting plugins to extend its functionality. Here’s an example of a custom operator that sends a notification to a Slack channel when a task fails:</p><pre># pythonCopy code<br>from airflow.models import BaseOperator<br>from airflow.plugins_manager import AirflowPlugin<br><br>class SlackNotificationOperator(BaseOperator):<br>    def __init__(self, slack_channel, *args, **kwargs):<br>        super().__init__(*args, **kwargs)<br>        self.slack_channel = slack_channel<br><br>def execute(self, context):<br>        try:<br>            # Perform task execution logic here<br>            # ...<br>            # If the task fails, send a Slack notification<br>            if task_failed:<br>                self.send_slack_notification(context[&#39;task_instance&#39;].task_id)<br>        <br>        except Exception as e:<br>            self.log.error(&quot;Error executing task: %s&quot;, str(e))<br>            raise<br>    def send_slack_notification(self, task_id):<br>        # Code to send Slack notification to self.slack_channel<br>        # ...<br># Create a custom plugin to register the operator<br>class CustomAirflowPlugin(AirflowPlugin):<br>    name = &quot;custom_airflow_plugin&quot;<br>    operators = [SlackNotificationOperator]</pre><pre>  With the custom operator and plugin, you can now use the SlackNotificationOperator in your DAGs to send Slack notifications when tasks fail.</pre><p>Conclusion: By incorporating monitoring and alerting into your Airflow deployments, you can proactively manage and troubleshoot workflows. The code samples provided demonstrate the integration of external monitoring systems like Prometheus, Grafana, and Datadog, as well as the implementation of custom monitoring and alerting functionalities. Leveraging these tools and techniques will empower you to ensure the reliability and performance of your Airflow workflows and take timely actions in response to critical events.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5eac45e2e301" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Running Managed Airflow vs Hosting Airflow on your own instance.]]></title>
            <link>https://medium.com/@anupamk36/running-managed-airflow-vs-hosting-airflow-on-your-own-instance-3419ae2f3b2c?source=rss-c4b6fd8a6c57------2</link>
            <guid isPermaLink="false">https://medium.com/p/3419ae2f3b2c</guid>
            <category><![CDATA[airflow]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[data]]></category>
            <dc:creator><![CDATA[Anupam Kumar]]></dc:creator>
            <pubDate>Thu, 25 May 2023 13:34:04 GMT</pubDate>
            <atom:updated>2023-05-25T13:34:04.208Z</atom:updated>
            <content:encoded><![CDATA[<p>🚀 As the only data engineer at <a href="https://www.linkedin.com/company/zocketdigital/">Zocket</a>, I understand the importance of choosing the right platform for our data pipelines. One of the decisions we often face is whether to run managed Airflow or run Airflow on an instance. While both options have their benefits and drawbacks, there are several technical considerations that we need to take into account.</p><p>👨‍💻 Managed Airflow provides a fully managed and scalable environment for running Airflow. With managed Airflow, we can focus on building our data pipelines rather than worrying about setting up and maintaining infrastructure. Platforms like AWS Managed Workflows for Apache Airflow (MWAA) offer automatic scaling based on the number of tasks, integrated monitoring and logging capabilities, and a 30% lower total cost of ownership (TCO) compared to running Airflow on an instance. This is especially important for startups like ours where resources are limited, and we need to move quickly to meet business requirements.</p><p>💻 Running Airflow on an instance gives us more control over our environment, but it requires more resources and expertise to maintain. We need to manage the infrastructure, install and update dependencies, and ensure high availability and scalability. However, running Airflow on an instance might be necessary for us if we have specific requirements for our environment, such as running on-premises or using specialized hardware.</p><p>🔍 Reliability is a critical consideration for us. Managed Airflow services offer high availability and fault tolerance out of the box, ensuring that our workflows continue to run even if a worker node fails. This eliminates the need for us to configure and manage fault tolerance and failover mechanisms, which can be complex and time-consuming. In contrast, running Airflow on an instance requires us to set up and manage these mechanisms ourselves.</p><p>📈 To measure the performance of each option, we can use metrics such as latency, uptime, and scaling time. With managed Airflow, we can typically achieve 99.99% uptime, lower latency by 40%, and faster scaling times due to the automatic scaling capabilities. In contrast, running Airflow on an instance might have longer scaling times and potentially lower uptime if the instance fails or experiences downtime.</p><p>👉 In conclusion, as a data engineer in a startup, I believe that managed Airflow is the best choice for our data pipelines. It provides a reliable and cost-effective solution, allowing us to focus on building our pipelines rather than managing infrastructure. However, we carefully evaluated our technical requirements and budget to make an informed decision.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3419ae2f3b2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Must-Have Github Repositories for SQL]]></title>
            <link>https://medium.com/@anupamk36/must-have-github-repositories-for-sql-6bce889c7658?source=rss-c4b6fd8a6c57------2</link>
            <guid isPermaLink="false">https://medium.com/p/6bce889c7658</guid>
            <category><![CDATA[data-engineer]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Anupam Kumar]]></dc:creator>
            <pubDate>Thu, 25 May 2023 13:31:36 GMT</pubDate>
            <atom:updated>2023-05-25T13:31:36.248Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve curated a list of highly recommended repositories. These repositories offer hands-on practice, real-world examples, and valuable insights from the community :</p><p>1️⃣ “Beyond LeetCode SQL” by shawlu95 🌐 *<br>🔗 Repository Link: <a href="https://lnkd.in/dnujHpaN">https://lnkd.in/dnujHpaN</a><br>Ready to transcend the boundaries of SQL? Beyond LeetCode SQL is a treasure trove of advanced SQL problems and solutions. Engage in complex scenarios and hone your skills by tackling challenging puzzles. Elevate your SQL expertise and unlock new possibilities.</p><p>2️⃣ “SQL Murder Mystery” by NU Knight Lab 🌐<br>🔗 Repository Link: <a href="https://lnkd.in/dgj9_Hz5">https://lnkd.in/dgj9_Hz5</a><br>Step into the shoes of a detective and sharpen your SQL skills with SQL Murder Mystery. Immerse yourself in an intriguing crime-solving adventure using SQL queries. Unleash your inner investigator and enhance your ability to derive insights from data.</p><p>3️⃣ “Data Engineering Interview Questions” by OBenner 🌐 *<br>🔗 Link: <a href="https://lnkd.in/dxb6MFcU">https://lnkd.in/dxb6MFcU</a><br>If you’re interested in the intersection of SQL and data engineering, this repository is a gem! Explore a wide range of SQL-related interview questions specific to data engineering roles. Enhance your knowledge and excel in data engineering interviews.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6bce889c7658" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>