<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="4.4.1">Jekyll</generator><link href="https://www.pulkitkapoor.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://www.pulkitkapoor.com/" rel="alternate" type="text/html" /><updated>2025-10-30T04:53:28+00:00</updated><id>https://www.pulkitkapoor.com/feed.xml</id><title type="html">Pulkit Kapoor | Data Engineering &amp;amp; Cloud</title><subtitle>Pulkit Kapoor&apos;s blog on data engineering, AWS, and cloud technology.</subtitle><author><name>Pulkit Kapoor</name><email>pulkit42041@gmail.com</email></author><entry><title type="html">Redshift Data Sharing</title><link href="https://www.pulkitkapoor.com/aws/dataengineering/Redshift-Data-sharing/" rel="alternate" type="text/html" title="Redshift Data Sharing" /><published>2024-11-10T00:00:00+00:00</published><updated>2024-07-14T00:00:00+00:00</updated><id>https://www.pulkitkapoor.com/aws/dataengineering/Redshift-Data-sharing</id><content type="html" xml:base="https://www.pulkitkapoor.com/aws/dataengineering/Redshift-Data-sharing/"><![CDATA[<p><a href="https://blog.pulkitkapoor.com/understanding-amazon-redshift-data-sharing-features" class="btn btn--success">Read on hashnode!</a></p>

<p>AWS Redshift is the data-warehousing solution provided by Amazon Web Services. As part of the Datawarehouse offering, Amazon Redshift provides a very useful feature known as data sharing. In this short article, we will get an understanding of when to use this feature and how to configure it in your own organization.</p>

<blockquote>
  <p>A <strong>data warehouse</strong> is a centralized repository designed to store, manage, and analyze large volumes of structured and semi-structured data from various sources. It is specifically optimized for <strong>querying, reporting, and data analysis.</strong></p>
</blockquote>

<h2 id="what-is-data-sharing">What is Data Sharing?</h2>

<h3 id="scenario-1---different-clusters">Scenario 1 - Different clusters</h3>

<p>In a large conglomerate with separate <strong>Amazon Redshift clusters</strong> dedicated to each division—such as finance, automotive, and manufacturing—you have a <strong>distributed data warehousing architecture</strong> where each division operates independently but still belongs to the overarching company infrastructure.</p>

<p>Joining datasets that reside on separate Amazon Redshift clusters—like joining data from the finance and manufacturing divisions—is achievable with <strong>Redshift Data Sharing</strong>. This feature allows seamless data access across clusters, avoiding the need to move or duplicate data.</p>

<h3 id="scenario-2---outsourcing-compute"><strong>Scenario 2 - Outsourcing compute</strong></h3>

<p>Another use case is sharing data with a third-party vendor without impacting the performance of your mission-critical Redshift cluster. In this scenario, you can set up a <strong>Redshift Serverless</strong> instance and configure <strong>data sharing</strong> for the specific datasets you want to share.</p>

<p>This allows the third-party vendor to access and analyze the shared data in the serverless environment without consuming compute resources from your primary ETL cluster. The serverless instance dynamically scales based on usage, ensuring that your main cluster’s resources remain fully dedicated to critical workloads.</p>

<h2 id="how-to-configure-data-sharing">How to configure data sharing?</h2>

<p>To configure data sharing, we need to configure the source and the receiving cluster, or serverless instance. The terminology we will use is <strong>producer, and consumer.</strong></p>

<h3 id="configure-the-producer">Configure the producer</h3>

<p>First, we will configure data sharing on the producer cluster so we can make the required data available to consume for the consumer (one or many)</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">-- As Admin User</span>
<span class="c1">-- Create datashare</span>
<span class="k">CREATE</span> <span class="n">DATASHARE</span> <span class="n">shareData</span><span class="p">;</span>
<span class="k">ALTER</span> <span class="n">DATASHARE</span> <span class="n">shareData</span> <span class="k">ADD</span> <span class="k">SCHEMA</span> <span class="n">a_schema</span><span class="p">;</span>                        <span class="c1">-- Add target schema</span>
<span class="k">ALTER</span> <span class="n">DATASHARE</span> <span class="n">shareData</span> <span class="k">ADD</span> <span class="k">TABLE</span> <span class="n">a_schema</span><span class="p">.</span><span class="n">a_table</span><span class="p">;</span>                 <span class="c1">-- Add required tables to share</span>

<span class="c1">-- Grant permissions to required consumers</span>
<span class="k">GRANT</span> <span class="k">USAGE</span> <span class="k">ON</span> <span class="n">DATASHARE</span> <span class="n">datashareDeviceLogs</span> <span class="k">TO</span> <span class="n">NAMESPACE</span> <span class="s1">'CONSUMER_NAMESPACE_ID'</span><span class="p">;</span>     <span class="c1">-- Share with consumer namespace</span>
<span class="k">DESC</span> <span class="n">DATASHARE</span> <span class="n">shareData</span><span class="p">;</span>

<span class="c1">-- Needed if target cluster is set as publicly accessible</span>
<span class="k">ALTER</span> <span class="n">DATASHARE</span> <span class="n">shareData</span> <span class="k">SET</span> <span class="n">PUBLICACCESSIBLE</span> <span class="o">=</span> <span class="k">TRUE</span><span class="p">;</span>                

<span class="k">GRANT</span> <span class="k">ALTER</span><span class="p">,</span> <span class="k">SHARE</span> <span class="k">ON</span> <span class="n">DATASHARE</span> <span class="n">shareData</span> <span class="k">TO</span> <span class="k">GROUP</span> <span class="n">the_group1</span><span class="p">;</span>        <span class="c1">-- To allow group to manage this datashare</span>
<span class="k">select</span> <span class="o">*</span> <span class="k">from</span> <span class="n">svv_datashare_privileges</span><span class="p">;</span>                               <span class="c1">-- see who is allowed to alter datashares other than admin</span>
</code></pre></div></div>

<h3 id="configure-the-consumer">Configure the consumer</h3>

<p>Once datashare has been configured on the producer, we can login into the consumer as an admin user and run the below commands to consume and read from the shared data.</p>

<div class="language-sql highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">-- As Admin User</span>
<span class="c1">-- check for incoming datashares</span>
<span class="k">SHOW</span> <span class="n">DATASHARES</span><span class="p">;</span>
<span class="k">DESC</span> <span class="n">DATASHARE</span> <span class="n">shareData</span> <span class="k">OF</span> <span class="n">NAMESPACE</span> <span class="s1">'PRODUCER_NAMESPACE_ID'</span><span class="p">;</span>

<span class="c1">-- Create a database to interact with the shared objects</span>
<span class="k">CREATE</span> <span class="k">DATABASE</span> <span class="n">sharedData</span> <span class="k">WITH</span> <span class="n">PERMISSIONS</span> <span class="k">FROM</span> <span class="n">DATASHARE</span> <span class="n">shareData</span> <span class="k">OF</span> <span class="n">NAMESPACE</span> <span class="s1">'PRODUCER_NAMESPACE_ID'</span><span class="p">;</span>

<span class="c1">---------------------------- Access using a external schema ----------------------------</span>
<span class="c1">--- using this configuration, the user cannot directly query the datashare database but through external schema ---</span>

<span class="c1">-- Create external schema poining to the datashare's database</span>
<span class="k">CREATE</span> <span class="k">EXTERNAL</span> <span class="k">SCHEMA</span> <span class="n">shared</span> <span class="k">FROM</span> <span class="n">REDSHIFT</span> <span class="k">DATABASE</span> <span class="n">sharedData</span> <span class="k">SCHEMA</span> <span class="s1">'a_schema'</span><span class="p">;</span>
<span class="c1">-- Grant permissions</span>
<span class="c1">-- Usage access for datashare source schema (Note, we are not giving access to datashare itsself)                                </span>
<span class="k">GRANT</span> <span class="k">USAGE</span> <span class="k">ON</span> <span class="k">SCHEMA</span> <span class="n">sharedData</span><span class="p">.</span><span class="n">a_schema</span> <span class="k">TO</span> <span class="k">GROUP</span> <span class="n">a_group</span><span class="p">;</span>       
<span class="c1">-- Access for external schema</span>
<span class="k">GRANT</span> <span class="k">USAGE</span> <span class="k">ON</span> <span class="k">SCHEMA</span> <span class="n">shared</span><span class="p">.</span><span class="n">a_table</span> <span class="k">TO</span> <span class="k">GROUP</span> <span class="n">a_group</span><span class="p">;</span>  
<span class="k">GRANT</span> <span class="k">SELECT</span> <span class="k">ON</span> <span class="k">ALL</span> <span class="n">TABLES</span> <span class="k">IN</span> <span class="k">SCHEMA</span> <span class="n">sharedData</span><span class="p">.</span><span class="n">a_schema</span> <span class="k">TO</span> <span class="k">TO</span> <span class="k">GROUP</span> <span class="n">a_group</span><span class="p">;</span>            <span class="c1">-- [PRIVELEGE] to target datashare table</span>
</code></pre></div></div>

<p>With proper permissions set at the <strong>producer</strong> and <strong>consumer</strong>, the users and groups with proper permisisons will be able to query the shared data.</p>

<h3 id="limitations-for-data-sharing">Limitations for data sharing</h3>

<p>The following are limitations when working with datashares in Amazon Redshift:</p>

<ol>
  <li>Data sharing is supported for all provisioned <strong>ra3</strong> cluster types (ra3.16xlarge, ra3.4xlarge, and ra3.xlplus) and Amazon Redshift Serverless. It isn’t supported for other cluster types.</li>
  <li>Amazon Redshift doesn’t support adding external schemas, tables, or late-binding views on external tables to datashares.</li>
  <li>Consumers can’t add datashare objects to another datashare. Additionally, consumers can’t add views referencing datashare objects to another datashare.</li>
  <li>Amazon Redshift doesn’t support sharing stored procedures through datashares.</li>
</ol>]]></content><author><name>Pulkit Kapoor</name><email>pulkit42041@gmail.com</email></author><category term="aws" /><category term="dataengineering" /><category term="aws" /><category term="redshift" /><category term="datawarehouse" /><category term="dataengineering" /><summary type="html"><![CDATA[How and why to use Redshift data sharing.]]></summary></entry><entry><title type="html">Exploding Spark Event Logs</title><link href="https://www.pulkitkapoor.com/aws/dataengineering/Exploding-SparkLogs-EMR/" rel="alternate" type="text/html" title="Exploding Spark Event Logs" /><published>2024-07-13T00:00:00+00:00</published><updated>2024-07-14T00:00:00+00:00</updated><id>https://www.pulkitkapoor.com/aws/dataengineering/Exploding-SparkLogs-EMR</id><content type="html" xml:base="https://www.pulkitkapoor.com/aws/dataengineering/Exploding-SparkLogs-EMR/"><![CDATA[<h2 id="understanding-the-problem">Understanding the problem</h2>
<p>If you’re running Apache Spark on AWS EMR, you might have run into a nasty surprise: compacted event logs that keep ballooning in size, even when they’re supposed to be shrinking.  We recently tackled this issue, and the culprit turned out to be a sneaky pair of custom Spark listeners. In this post, we’ll break down why this happens and how we solved it with a custom filter.</p>

<p class="notice--info">For streaming spark applications, you can turn on eventlogs that help to recreate spark UI when the application fails or completes</p>

<h2 id="the-problem-compacted-event-logs-gone-wild">The Problem: Compacted Event Logs Gone Wild</h2>

<p>While monitoring our production Spark jobs, we noticed that the compacted event logs for several streaming jobs were growing at an alarming rate. Compaction is meant to reduce log size, but even after compaction, the overall size and number of logs kept creeping up.</p>

<p>Diving into the event logs, we found that events related to two specific classes were piling up:</p>

<ul>
  <li><code class="language-plaintext highlighter-rouge">org.apache.spark.sql.execution.ui.SparkListenerEffectiveSQLConf</code></li>
  <li><code class="language-plaintext highlighter-rouge">org.apache.spark.sql.execution.ui.SparkListenerQueryExecutionMetrics</code></li>
</ul>

<h2 id="the-root-cause-missing-compaction-filters">The Root Cause: Missing Compaction Filters</h2>

<p>These two listeners aren’t native to the Spark version we were using (3.2.1). They’re part of Amazon EMR’s modified Spark SQL implementation.  The problem? AWS hadn’t implemented the necessary logic to clean up these events during compaction. They were just accumulating like digital dust bunnies.</p>

<h2 id="our-solution">Our solution</h2>

<p>To fix this, we needed to create a custom filter to exclude these events during compaction. Here’s the high-level approach we took:</p>

<ul>
  <li><strong>Identify the Target Events</strong>: We pinpointed the specific event types we wanted to exclude.</li>
  <li><strong>Write the Filter</strong>: We crafted a filter to remove those events from the compaction process.</li>
  <li><strong>Testing in Dev</strong>: We thoroughly tested the filter in our development environment to ensure it worked as expected and didn’t break the Spark History UI.</li>
  <li><strong>Deploy to Production</strong>: Once confident, we rolled out the filter to our production environment.</li>
</ul>

<h2 id="under-the-hood">Under the Hood</h2>

<p>To make this fix a reality, we created a new implementation for Spark’s EventFilterBuilder interface. This interface is how Spark dynamically loads custom filters using its service loader mechanism.</p>

<p>Here’s a breakdown of our solution:</p>

<div class="language-scala highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">package</span> <span class="nn">org.apache.spark.deploy.history</span>
<span class="c1">// ... (other imports)</span>

<span class="c1">// Custom Event Filter Builder</span>
<span class="k">private</span><span class="o">[</span><span class="kt">spark</span><span class="o">]</span> <span class="k">class</span> <span class="nc">CustomEventFilterBuilder</span> <span class="k">extends</span> <span class="nc">EventFilterBuilder</span> <span class="k">with</span> <span class="nc">Logging</span> <span class="o">{</span>
  <span class="k">override</span> <span class="k">def</span> <span class="nf">createFilter</span><span class="o">()</span><span class="k">:</span> <span class="kt">EventFilter</span> <span class="o">=</span> <span class="k">new</span> <span class="nc">CustomEventFilter</span>
<span class="o">}</span>

<span class="c1">// Custom Event Filter</span>
<span class="k">private</span><span class="o">[</span><span class="kt">spark</span><span class="o">]</span> <span class="k">class</span> <span class="nc">CustomEventFilter</span> <span class="k">extends</span> <span class="nc">EventFilter</span> <span class="k">with</span> <span class="nc">Logging</span> <span class="o">{</span>
  <span class="c1">// Exclude filter</span>
  <span class="k">def</span> <span class="nf">acceptFn</span><span class="k">:</span> <span class="kt">PartialFunction</span><span class="o">[</span><span class="kt">SparkListenerEvent</span>, <span class="kt">Boolean</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
    <span class="k">case</span> <span class="n">e</span><span class="k">:</span> <span class="kt">SparkListenerEvent</span> <span class="kt">if</span> <span class="kt">List</span><span class="o">(</span><span class="err">"</span><span class="kt">SparkListenerQueryExecutionMetrics</span><span class="err">"</span><span class="o">,</span> <span class="err">"</span><span class="kt">SparkListenerEffectiveSQLConf</span><span class="err">"</span><span class="o">).</span><span class="py">contains</span><span class="o">(</span><span class="nv">Utils</span><span class="o">.</span><span class="py">getSimpleName</span><span class="o">(</span><span class="nv">e</span><span class="o">.</span><span class="py">getClass</span><span class="o">))</span> <span class="k">=&gt;</span> <span class="kc">false</span>
  <span class="o">}</span>
  <span class="k">override</span> <span class="k">def</span> <span class="nf">statistics</span><span class="o">()</span><span class="k">:</span> <span class="kt">Option</span><span class="o">[</span><span class="kt">FilterStatistics</span><span class="o">]</span> <span class="k">=</span> <span class="nc">None</span>
<span class="o">}</span>
</code></pre></div></div>

<h2 id="how-it-works">How it Works</h2>

<h5 id="service-loader-magic">Service Loader Magic:</h5>
<p>The key to this working is a special file we added to our project called <strong>META-INF/services/org.apache.spark.deploy.history.EventFilterBuilder</strong>. This file contains the fully qualified class name of our <em>CustomEventFilterBuilder</em>. When Spark starts up, it automatically discovers this file and loads our filter builder.</p>

<h5 id="builder-does-its-thing">Builder Does Its Thing:</h5>
<p>When it’s time to filter events, Spark calls the <code class="language-plaintext highlighter-rouge">createFilter()</code> method on our <em>CustomEventFilterBuilder</em>. This simply returns a new instance of our <em>CustomEventFilter</em>.</p>

<h5 id="filter-in-action">Filter in Action:</h5>
<p>The <em>CustomEventFilter</em> takes over. Its <code class="language-plaintext highlighter-rouge">acceptFn</code> function checks each event’s class name. If the class name matches one of the events in our excludedEvents list (in our case, <em>SparkListenerQueryExecutionMetrics</em> and <em>SparkListenerEffectiveSQLConf</em>), the event is rejected during compaction.</p>

<h2 id="why-this-approach-is-awesome">Why This Approach is Awesome</h2>

<ul>
  <li><strong>Simple and Elegant</strong>: The code itself is straightforward, making it easy to understand and maintain.</li>
  <li><strong>Minimal Disruption</strong>: We’re not modifying Spark’s core code. Our custom filter neatly integrates into the existing framework.</li>
  <li><strong>Targeted Filtering</strong>: We have precise control over which events to exclude, ensuring we don’t accidentally impact other Spark functionalities.</li>
  <li><strong>Extensible</strong>: You can easily modify the excludedEvents list to target different events based on your specific requirements.
This custom filter solved our event log woes, dramatically reducing their size and improving the stability of our Spark cluster. If you’re facing a similar issue, this approach might just be your saving grace!</li>
</ul>

<hr />

<h4 id="optional---why-service-loaders-are-so-cool">Optional - Why Service Loaders Are So Cool</h4>

<p>Imagine you’re building a complex software application, and you want to make it flexible and extensible. You want to allow other developers (or even yourself in the future) to add new features or customize behavior without modifying the core codebase.  This is where service loaders come in handy.</p>

<p>In essence, a service loader is a mechanism that allows a Java application to discover and load implementations of specific interfaces at runtime.  Think of it as a way for the main application to say, “Hey, I need something that can do X. Is there anyone out there who can help?”</p>

<h5 id="how-service-loaders-work">How Service Loaders Work</h5>

<ul>
  <li><strong>Interface</strong>: The core application defines an interface that outlines the contract for a particular functionality. This interface acts like a blueprint for what the extension should do.</li>
  <li><strong>Implementations</strong>: Developers create separate components that provide concrete implementations of the interface.</li>
  <li><strong>Service File</strong>: Each implementation includes a special configuration file (<em>usually in the <code class="language-plaintext highlighter-rouge">META-INF/services</code> directory</em>) that lists the fully qualified class names of the implementation classes.</li>
  <li><strong>Discovery</strong>: The core application uses the <em>service loader</em> mechanism to scan its classpath at runtime. It looks for these configuration files and automatically loads the listed implementation classes.</li>
  <li><strong>Usage</strong>: The core application can then use the loaded implementations, seamlessly extending its capabilities without any hardcoded dependencies.</li>
</ul>

<div class="language-java highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// In the core application, defining the interface</span>
<span class="kn">package</span> <span class="nn">translator</span><span class="o">;</span>
<span class="kd">public</span> <span class="kd">interface</span> <span class="nc">MessageTranslator</span> <span class="o">{</span>
    <span class="nc">String</span> <span class="nf">translate</span><span class="o">(</span><span class="nc">String</span> <span class="n">message</span><span class="o">);</span>
<span class="o">}</span>

<span class="c1">// In a separate module create implementation of the interface</span>
<span class="kd">public</span> <span class="kd">class</span> <span class="nc">EnglishToFrenchTranslator</span> <span class="kd">implements</span> <span class="nc">MessageTranslator</span> <span class="o">{</span>
    <span class="nd">@Override</span>
    <span class="kd">public</span> <span class="nc">String</span> <span class="nf">translate</span><span class="o">(</span><span class="nc">String</span> <span class="n">message</span><span class="o">)</span> <span class="o">{</span>
        <span class="c1">// ... translation logic ...</span>
        <span class="k">return</span> <span class="s">"Translated "</span> <span class="o">+</span> <span class="n">message</span><span class="o">;</span>
    <span class="o">}</span>
<span class="o">}</span>

<span class="c1">// Service File: META-INF/services/translator.MessageTranslator</span>
<span class="n">translator</span><span class="o">.</span><span class="na">EnglishToFrenchTranslator</span>

<span class="c1">// Usage in application</span>
<span class="c1">// In the core application</span>
<span class="nc">ServiceLoader</span><span class="o">&lt;</span><span class="nc">MessageTranslator</span><span class="o">&gt;</span> <span class="n">loader</span> <span class="o">=</span> <span class="nc">ServiceLoader</span><span class="o">.</span><span class="na">load</span><span class="o">(</span><span class="nc">MessageTranslator</span><span class="o">.</span><span class="na">class</span><span class="o">);</span>
<span class="k">for</span> <span class="o">(</span><span class="nc">MessageTranslator</span> <span class="n">translator</span> <span class="o">:</span> <span class="n">loader</span><span class="o">)</span> <span class="o">{</span>
    <span class="nc">System</span><span class="o">.</span><span class="na">out</span><span class="o">.</span><span class="na">println</span><span class="o">(</span><span class="n">translator</span><span class="o">.</span><span class="na">translate</span><span class="o">(</span><span class="s">"Hello"</span><span class="o">));</span> 
<span class="o">}</span>

</code></pre></div></div>

<p>In our Spark example, the service loader helped us seamlessly integrate our custom filter, demonstrating the power of this elegant design pattern.</p>]]></content><author><name>Pulkit Kapoor</name><email>pulkit42041@gmail.com</email></author><category term="aws" /><category term="dataengineering" /><category term="aws" /><category term="emr" /><category term="spark" /><category term="streaming" /><category term="dataengineering" /><summary type="html"><![CDATA[How to reduce size of spark event logs on EMR for streaming applications.]]></summary></entry><entry><title type="html">AWS EMR - Private Subnets</title><link href="https://www.pulkitkapoor.com/aws/EMR-Private-Cluster-Infra/" rel="alternate" type="text/html" title="AWS EMR - Private Subnets" /><published>2024-04-10T00:00:00+00:00</published><updated>2024-04-10T00:00:00+00:00</updated><id>https://www.pulkitkapoor.com/aws/EMR-Private-Cluster-Infra</id><content type="html" xml:base="https://www.pulkitkapoor.com/aws/EMR-Private-Cluster-Infra/"><![CDATA[<p><a href="https://github.com/k-pulkit/learning-central-engineering/tree/main/topic-EMR/lab1" class="btn btn--info">Checkout the complete code!</a></p>

<p class="notice--warning">The github repo contains all the code for the deployment of EMR in private cluster.</p>

<h2 id="introduction">Introduction</h2>

<figure style="max-width: 680px" class="align-center">
  <div class="image-wrapper">
    <img src="/assets/images/collections/posts/2024-04-10-EMR-Private-Cluster-Infra/arch.png" alt="EMR private cluster architecture" />

  </div>
  <figcaption>Architecture</figcaption>
</figure>

<p>In this comprehensive guide, we’ll walk through the process of creating an Amazon EMR (Elastic MapReduce) cluster in a private subnet using Terraform. By deploying the EMR cluster in a private subnet, we ensure that the cluster’s resources are not directly accessible from the internet, enhancing its security posture.</p>

<h2 id="prerequisites">Prerequisites</h2>

<p>Before we begin, ensure you have the following:</p>

<ul>
  <li>An AWS account with appropriate permissions to create resources.</li>
  <li>Terraform installed on your local machine.</li>
</ul>

<h2 id="step-1-setting-up-the-terraform-configuration">Step 1: Setting Up the Terraform Configuration</h2>

<p>We start by creating a new Terraform configuration file (e.g., <code class="language-plaintext highlighter-rouge">emr_cluster.tf</code>) and define the AWS provider and required providers:</p>

<div class="language-hcl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">provider</span> <span class="s2">"aws"</span> <span class="p">{</span>
  <span class="nx">profile</span> <span class="o">=</span> <span class="s2">"terraform"</span>
  <span class="nx">region</span>  <span class="o">=</span> <span class="nx">var</span><span class="p">.</span><span class="nx">region</span>
<span class="p">}</span>

<span class="nx">terraform</span> <span class="p">{</span>
  <span class="nx">required_providers</span> <span class="p">{</span>
    <span class="nx">aws</span> <span class="o">=</span> <span class="p">{</span>
      <span class="nx">source</span>  <span class="o">=</span> <span class="s2">"hashicorp/aws"</span>
      <span class="nx">version</span> <span class="o">=</span> <span class="s2">"~&gt; 5.42.0"</span>
    <span class="p">}</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Here, we configure the AWS provider to use the AWS profile “terraform” and specify the region from the <code class="language-plaintext highlighter-rouge">var.region</code> variable.</p>

<h2 id="step-2-declaring-data-sources">Step 2: Declaring Data Sources</h2>

<p>We declare data sources to fetch information needed for our configuration. For example, to get the list of available availability zones:</p>

<div class="language-hcl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">data</span> <span class="s2">"aws_availability_zones"</span> <span class="s2">"available"</span> <span class="p">{}</span>
</code></pre></div></div>

<h2 id="step-3-defining-local-variables">Step 3: Defining Local Variables</h2>

<p>Next, let’s define some local variables for reuse in our configuration:</p>

<div class="language-hcl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">locals</span> <span class="p">{</span>
  <span class="nx">name</span>        <span class="o">=</span> <span class="nx">replace</span><span class="p">(</span><span class="nx">basename</span><span class="p">(</span><span class="nx">path</span><span class="p">.</span><span class="nx">cwd</span><span class="p">),</span> <span class="s2">"-cluster"</span><span class="p">,</span> <span class="s2">""</span><span class="p">)</span>
  <span class="nx">vpc_name</span>    <span class="o">=</span> <span class="s2">"MyVPC1"</span>
  <span class="nx">vpc_cidr</span>    <span class="o">=</span> <span class="s2">"10.0.0.0/16"</span>
  <span class="nx">bucket_name</span> <span class="o">=</span> <span class="s2">"slvr-emr-bucket-443"</span>
  <span class="nx">azs</span>         <span class="o">=</span> <span class="nx">slice</span><span class="p">(</span><span class="nx">data</span><span class="p">.</span><span class="nx">aws_availability_zones</span><span class="p">.</span><span class="nx">available</span><span class="p">.</span><span class="nx">names</span><span class="p">,</span> <span class="mi">0</span><span class="p">,</span> <span class="mi">3</span><span class="p">)</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Here, we set the name of the EMR cluster, the VPC name, VPC CIDR block, S3 bucket name, and the availability zones to use. The last local variable <code class="language-plaintext highlighter-rouge">azs</code> takes the first 3 zones of the available zone for configured aws-region.</p>

<h2 id="step-4-configuring-the-emr-module">Step 4: Configuring the EMR Module</h2>

<p>Now, let’s configure the EMR module to create our EMR cluster. We specify the release label, applications, auto-termination policy, bootstrap action, configurations, instance groups, and other settings:</p>

<div class="language-hcl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">module</span> <span class="s2">"emr_instance_group"</span> <span class="p">{</span>
  <span class="nx">source</span>  <span class="o">=</span> <span class="s2">"terraform-aws-modules/emr/aws"</span>
  <span class="nx">version</span> <span class="o">=</span> <span class="s2">"~&gt;1.2.1"</span>

  <span class="nx">name</span> <span class="o">=</span> <span class="s2">"${local.name}-instance-group"</span>

  <span class="c1">#: Version of the EMR Big-data release</span>
  <span class="nx">release_label_filters</span> <span class="o">=</span> <span class="p">{</span>
    <span class="nx">emr6</span> <span class="o">=</span> <span class="p">{</span>
      <span class="nx">prefix</span> <span class="o">=</span> <span class="s2">"emr-6"</span>
    <span class="p">}</span>
  <span class="p">}</span>

  <span class="c1">#: List of applications to deploy on the EMR cluster</span>
  <span class="nx">applications</span> <span class="o">=</span> <span class="p">[</span><span class="s2">"spark"</span><span class="p">,</span> <span class="s2">"hadoop"</span><span class="p">]</span>
  <span class="nx">auto_termination_policy</span> <span class="o">=</span> <span class="p">{</span>
    <span class="nx">idle_timeout</span> <span class="o">=</span> <span class="mi">3600</span>
  <span class="p">}</span>

  <span class="c1">#: Any script to run while bootstrapping the cluster</span>
  <span class="nx">bootstrap_action</span> <span class="o">=</span> <span class="p">{</span>
    <span class="nx">example</span> <span class="o">=</span> <span class="p">{</span>
      <span class="nx">path</span> <span class="o">=</span> <span class="s2">"file:/bin/echo"</span><span class="p">,</span>
      <span class="nx">name</span> <span class="o">=</span> <span class="s2">"Just an example"</span><span class="p">,</span>
      <span class="nx">args</span> <span class="o">=</span> <span class="p">[</span><span class="s2">"Hello World!"</span><span class="p">]</span>
    <span class="p">}</span>
  <span class="p">}</span>

  <span class="c1">#: Alter any existing configuration, like spark-env, core-site, hdfs-site etc.</span>
  <span class="nx">configurations_json</span> <span class="o">=</span> <span class="nx">jsonencode</span><span class="p">([</span>
    <span class="p">{</span>
      <span class="s2">"Classification"</span> <span class="o">:</span> <span class="s2">"spark-env"</span><span class="p">,</span>
      <span class="s2">"Configurations"</span> <span class="o">:</span> <span class="p">[</span>
        <span class="p">{</span>
          <span class="s2">"Classification"</span> <span class="o">:</span> <span class="s2">"export"</span><span class="p">,</span>
          <span class="s2">"Properties"</span> <span class="o">:</span> <span class="p">{</span>
            <span class="s2">"JAVA_HOME"</span> <span class="o">:</span> <span class="s2">"/usr/lib/jvm/java-1.8.0"</span>
          <span class="p">}</span>
        <span class="p">}</span>
      <span class="p">],</span>
      <span class="s2">"Properties"</span> <span class="o">:</span> <span class="p">{}</span>
    <span class="p">}</span>
  <span class="p">])</span>

  <span class="c1">#: What instances are needed for master and core nodes</span>
  <span class="c1"># Using bid price ensures that it will be a spot instance</span>
  <span class="nx">master_instance_group</span> <span class="o">=</span> <span class="p">{</span>
    <span class="nx">name</span>           <span class="o">=</span> <span class="s2">"master-group"</span>
    <span class="nx">instance_count</span> <span class="o">=</span> <span class="mi">1</span>
    <span class="nx">instance_type</span>  <span class="o">=</span> <span class="s2">"m5.xlarge"</span>
    <span class="nx">bid_price</span>      <span class="o">=</span> <span class="s2">"0.25"</span>
  <span class="p">}</span>
  <span class="c1"># core nodes</span>
  <span class="nx">core_instance_group</span> <span class="o">=</span> <span class="p">{</span>
    <span class="nx">name</span>           <span class="o">=</span> <span class="s2">"core-group"</span>
    <span class="nx">instance_count</span> <span class="o">=</span> <span class="mi">1</span>
    <span class="nx">instance_type</span>  <span class="o">=</span> <span class="s2">"c4.2xlarge"</span>
    <span class="nx">bid_price</span>      <span class="o">=</span> <span class="s2">"0.25"</span>
  <span class="p">}</span>

  <span class="c1"># What private subnet to launch the EMR into, and the key to login</span>
  <span class="nx">ebs_root_volume_size</span> <span class="o">=</span> <span class="mi">64</span>
  <span class="nx">ec2_attributes</span> <span class="o">=</span> <span class="p">{</span>
    <span class="nx">subnet_id</span> <span class="o">=</span> <span class="nx">element</span><span class="p">(</span><span class="nx">module</span><span class="p">.</span><span class="nx">vpc</span><span class="p">.</span><span class="nx">private_subnets</span><span class="p">,</span> <span class="mi">0</span><span class="p">)</span>
    <span class="nx">key_name</span>  <span class="o">=</span> <span class="s2">"Login-1"</span>
  <span class="p">}</span>
  <span class="nx">vpc_id</span>             <span class="o">=</span> <span class="nx">module</span><span class="p">.</span><span class="nx">vpc</span><span class="p">.</span><span class="nx">vpc_id</span>
  <span class="nx">is_private_cluster</span> <span class="o">=</span> <span class="kc">true</span>

  <span class="c1">#: Allow ssh traffic to connect to it</span>
  <span class="nx">master_security_group_rules</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s2">"rule1"</span> <span class="p">=</span> <span class="p">{</span>
      <span class="nx">description</span> <span class="o">=</span> <span class="s2">"Allow ssh ingress traffic"</span>
      <span class="nx">type</span>        <span class="o">=</span> <span class="s2">"ingress"</span>
      <span class="nx">from_port</span>   <span class="o">=</span> <span class="mi">22</span>
      <span class="nx">to_port</span>     <span class="o">=</span> <span class="mi">22</span>
      <span class="nx">protocol</span>    <span class="o">=</span> <span class="s2">"tcp"</span>
      <span class="nx">cidr_blocks</span> <span class="o">=</span> <span class="p">[</span><span class="s2">"0.0.0.0/0"</span><span class="p">]</span>     <span class="c1">// Allow traffic coming from EC2 instance connect endpoint</span>
    <span class="p">}</span>
    <span class="c1">#: Allow egress so EMR nodes can reach internet if needed (via NAT gateway)</span>
    <span class="s2">"rule2"</span> <span class="p">=</span> <span class="p">{</span>
      <span class="nx">description</span> <span class="o">=</span> <span class="s2">"Allow all egress traffic"</span>
      <span class="nx">type</span>        <span class="o">=</span> <span class="s2">"egress"</span>
      <span class="nx">from_port</span>   <span class="o">=</span> <span class="mi">0</span>
      <span class="nx">to_port</span>     <span class="o">=</span> <span class="mi">0</span>
      <span class="nx">protocol</span>    <span class="o">=</span> <span class="s2">"-1"</span>
      <span class="nx">cidr_blocks</span> <span class="o">=</span> <span class="p">[</span><span class="s2">"0.0.0.0/0"</span><span class="p">]</span>     <span class="c1">// Outbound traffic is okay as internet access may be needed later</span>
    <span class="p">}</span>
  <span class="p">}</span>

  <span class="nx">keep_job_flow_alive_when_no_steps</span> <span class="o">=</span> <span class="kc">true</span>
  <span class="nx">list_steps_states</span>                 <span class="o">=</span> <span class="p">[</span><span class="s2">"PENDING"</span><span class="p">,</span> <span class="s2">"RUNNING"</span><span class="p">,</span> <span class="s2">"CANCEL_PENDING"</span><span class="p">,</span> <span class="s2">"CANCELLED"</span><span class="p">,</span> <span class="s2">"FAILED"</span><span class="p">,</span> <span class="s2">"INTERRUPTED"</span><span class="p">,</span> <span class="s2">"COMPLETED"</span><span class="p">]</span>
  <span class="nx">log_uri</span>                           <span class="o">=</span> <span class="s2">"s3://${module.s3_bucket.s3_bucket_id}/"</span>

  <span class="nx">step_concurrency_level</span> <span class="o">=</span> <span class="mi">3</span>
  <span class="nx">termination_protection</span> <span class="o">=</span> <span class="kc">false</span>
  <span class="nx">visible_to_all_users</span>   <span class="o">=</span> <span class="kc">true</span>

  <span class="nx">tags</span>       <span class="o">=</span> <span class="nx">var</span><span class="err">.</span><span class="nx">tags</span>
  <span class="nx">depends_on</span> <span class="o">=</span> <span class="p">[</span><span class="nx">module</span><span class="p">.</span><span class="nx">vpc</span><span class="p">,</span> <span class="nx">module</span><span class="p">.</span><span class="nx">s3_bucket</span><span class="p">]</span>

<span class="p">}</span>
</code></pre></div></div>

<p>In this configuration, we define the EMR cluster’s specifications, including the EMR release label, applications, auto-termination policy, bootstrap action, configurations, instance groups, and security group rules.</p>

<p class="notice--info">When launching EMR, you can create the cluster by selecting instance group of instance fleet. Instance group means that the master or say core nodes need to of same instance type. Instance fleet allows you to use a mix of instance types, and include spot instances in mix. This allows you to improve availability and cost effectiveness of cluster.</p>

<p>Some important things to note are:</p>
<ul>
  <li>Instance groups can only be launched in one private subnet, where as instance fleets can be launched in multiple.</li>
  <li>Security group rules need to modified so that ssh connection is allowed</li>
  <li>In case of instance fleets, you can use EMR Managed policies for automatic scaling up and down of cluster</li>
</ul>

<h2 id="step-5-configuring-the-vpc">Step 5: Configuring the VPC</h2>

<p>To create a VPC for our EMR cluster, we use the Terraform AWS VPC module:</p>

<div class="language-hcl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">module</span> <span class="s2">"vpc"</span> <span class="p">{</span>
  <span class="nx">source</span> <span class="o">=</span> <span class="s2">"terraform-aws-modules/vpc/aws"</span>

  <span class="nx">name</span>            <span class="o">=</span> <span class="nx">local</span><span class="p">.</span><span class="nx">vpc_name</span>
  <span class="nx">cidr</span>            <span class="o">=</span> <span class="nx">local</span><span class="p">.</span><span class="nx">vpc_cidr</span>
  <span class="nx">azs</span>             <span class="o">=</span> <span class="nx">local</span><span class="p">.</span><span class="nx">azs</span>
  <span class="nx">public_subnets</span>  <span class="o">=</span> <span class="p">[</span><span class="nx">for</span> <span class="nx">k</span><span class="p">,</span> <span class="nx">v</span> <span class="nx">in</span> <span class="nx">local</span><span class="p">.</span><span class="nx">azs</span> <span class="o">:</span> <span class="nx">cidrsubnet</span><span class="p">(</span><span class="nx">local</span><span class="p">.</span><span class="nx">vpc_cidr</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="nx">k</span><span class="p">)]</span>
  <span class="nx">private_subnets</span> <span class="o">=</span> <span class="p">[</span><span class="nx">for</span> <span class="nx">k</span><span class="p">,</span> <span class="nx">v</span> <span class="nx">in</span> <span class="nx">local</span><span class="p">.</span><span class="nx">azs</span> <span class="o">:</span> <span class="nx">cidrsubnet</span><span class="p">(</span><span class="nx">local</span><span class="p">.</span><span class="nx">vpc_cidr</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="nx">k</span> <span class="o">+</span> <span class="mi">8</span><span class="p">)]</span>

  <span class="c1">#: Nat gateway to allows private subnet to reach internet</span>
  <span class="nx">enable_nat_gateway</span> <span class="o">=</span> <span class="kc">true</span>
  <span class="nx">single_nat_gateway</span> <span class="o">=</span> <span class="kc">true</span>

  <span class="c1">#: Enable private DNS support</span>
  <span class="nx">default_vpc_enable_dns_hostnames</span>  <span class="o">=</span> <span class="kc">true</span>
  <span class="nx">default_vpc_enable_dns_support</span> <span class="o">=</span> <span class="kc">true</span>

  <span class="c1">#: Required for the subnet used by EMR cluster</span>
  <span class="nx">private_subnet_tags</span> <span class="o">=</span> <span class="p">{</span> <span class="s2">"for-use-with-amazon-emr-managed-policies"</span> <span class="p">=</span> <span class="kc">true</span> <span class="p">}</span>
  <span class="nx">tags</span>                <span class="o">=</span> <span class="nx">var</span><span class="err">.</span><span class="nx">tags</span>

  <span class="nx">vpc_tags</span> <span class="o">=</span> <span class="p">{</span>
    <span class="nx">Name</span> <span class="o">=</span> <span class="nx">local</span><span class="p">.</span><span class="nx">vpc_name</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Here, we define the VPC’s specifications, including the VPC name, CIDR block, availability zones, and subnets.</p>

<h2 id="step-6-configuring-the-vpc-endpoints">Step 6: Configuring the VPC Endpoints</h2>

<p>While launching EMR cluster in private subnet, you need to</p>

<div class="language-hcl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">// Endpoint for the VPC to allow EMR to access S3 over private network</span>
<span class="nx">module</span> <span class="s2">"vpc_endpoint"</span> <span class="p">{</span>
  <span class="nx">source</span> <span class="o">=</span> <span class="s2">"./.terraform/modules/vpc/modules/vpc-endpoints"</span>
  <span class="nx">vpc_id</span>                     <span class="o">=</span> <span class="nx">module</span><span class="p">.</span><span class="nx">vpc</span><span class="p">.</span><span class="nx">vpc_id</span>

  <span class="c1">#: Security group used by Interface Gateway to allow/disallow traffic</span>
  <span class="c1"># Note - Security group allows ingress from private subnet </span>
  <span class="nx">security_group_ids</span>         <span class="o">=</span> <span class="p">[</span><span class="nx">module</span><span class="p">.</span><span class="nx">vpc_endpoints_sg</span><span class="p">.</span><span class="nx">security_group_id</span><span class="p">]</span>

  <span class="nx">endpoints</span> <span class="o">=</span> <span class="nx">merge</span><span class="p">({</span>
    <span class="c1">#: Gateway S3 endpoint</span>
    <span class="nx">s3</span> <span class="o">=</span> <span class="p">{</span>
      <span class="nx">service</span>         <span class="o">=</span> <span class="s2">"s3"</span>
      <span class="nx">service_type</span>    <span class="o">=</span> <span class="s2">"Gateway"</span>
      <span class="nx">private_dns_enabled</span> <span class="o">=</span> <span class="kc">true</span>
      
      <span class="c1"># Gateway endpoint required route table IDs of private route tables to create the entry</span>
      <span class="nx">route_table_ids</span> <span class="o">=</span> <span class="nx">flatten</span><span class="p">([</span><span class="nx">module</span><span class="p">.</span><span class="nx">vpc</span><span class="p">.</span><span class="nx">private_route_table_ids</span><span class="p">])</span>
      
      <span class="c1"># This policy allows all actions if traffic is coming from the VPC</span>
      <span class="nx">policy</span>          <span class="o">=</span> <span class="nx">data</span><span class="p">.</span><span class="nx">aws_iam_policy_document</span><span class="p">.</span><span class="nx">generic_s3_policy</span><span class="p">.</span><span class="nx">json</span>
      <span class="nx">tags</span>            <span class="o">=</span> <span class="p">{</span> <span class="nx">Name</span> <span class="o">=</span> <span class="s2">"${local.vpc_name}-s3"</span> <span class="p">}</span>
    <span class="p">}</span>
    <span class="p">},</span>

    <span class="c1">#: Interface endpoint for EMR and STS service</span>
    <span class="p">{</span>
      <span class="nx">for</span> <span class="nx">service</span> <span class="nx">in</span> <span class="nx">toset</span><span class="p">([</span><span class="s2">"elasticmapreduce"</span><span class="p">,</span> <span class="s2">"sts"</span><span class="p">])</span> <span class="o">:</span>
      <span class="nx">service</span> <span class="o">=&gt;</span> <span class="p">{</span>
        <span class="nx">service</span>             <span class="o">=</span> <span class="nx">service</span>
        <span class="nx">service_type</span>        <span class="o">=</span> <span class="s2">"Interface"</span>

        <span class="c1"># List of private subnets where the ENI will be attached</span>
        <span class="nx">subnet_ids</span>          <span class="o">=</span> <span class="nx">module</span><span class="p">.</span><span class="nx">vpc</span><span class="p">.</span><span class="nx">private_subnets</span>
        <span class="nx">private_dns_enabled</span> <span class="o">=</span> <span class="kc">true</span>
        <span class="nx">tags</span>                <span class="o">=</span> <span class="p">{</span> <span class="nx">Name</span> <span class="o">=</span> <span class="s2">"${local.vpc_name}-${service}"</span> <span class="p">}</span>
      <span class="p">}</span>
  <span class="p">}</span>
  <span class="p">)</span>

  <span class="nx">tags</span> <span class="o">=</span> <span class="nx">var</span><span class="p">.</span><span class="nx">tags</span>
  <span class="nx">depends_on</span> <span class="o">=</span> <span class="p">[</span><span class="nx">module</span><span class="p">.</span><span class="nx">vpc</span><span class="p">,</span> <span class="nx">module</span><span class="p">.</span><span class="nx">vpc_endpoints_sg</span><span class="p">]</span>

<span class="p">}</span>

</code></pre></div></div>

<p>To allow the EMR cluster to access S3 over a private network, we configure VPC endpoints. This configuration creates VPC endpoints for services like S3, EMR, and STS, allowing the EMR cluster to access these services over a private network.</p>

<h2 id="step-7-configuring-the-s3-bucket">Step 7: Configuring the S3 Bucket</h2>

<p>Finally, we configure an S3 bucket for the EMR cluster to use:</p>

<div class="language-hcl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">module</span> <span class="s2">"s3_bucket"</span> <span class="p">{</span>
  <span class="nx">source</span>  <span class="o">=</span> <span class="s2">"terraform-aws-modules/s3-bucket/aws"</span>
  <span class="nx">version</span> <span class="o">=</span> <span class="s2">"~&gt; 3.0"</span>

  <span class="nx">bucket</span> <span class="o">=</span> <span class="nx">local</span><span class="p">.</span><span class="nx">bucket_name</span>

  <span class="c1">// Other configurations...</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This configuration creates an S3 bucket with secure settings and server-side encryption enabled.</p>

<h2 id="step-8-deploying-the-configuration">Step 8: Deploying the Configuration</h2>

<p>To deploy the Terraform configuration and create the EMR cluster, follow these steps:</p>

<ol>
  <li>Initialize the Terraform configuration <code class="language-plaintext highlighter-rouge">terraform init</code></li>
  <li>Review the planned changes <code class="language-plaintext highlighter-rouge">terraform plan</code></li>
  <li>Apply the Terraform configuration to create the EMR cluster <code class="language-plaintext highlighter-rouge">terraform apply</code></li>
  <li>Confirm the changes by entering <code class="language-plaintext highlighter-rouge">yes</code> when prompted.</li>
</ol>

<h2 id="conclusion">Conclusion</h2>

<p>In this guide, we’ve demonstrated how to create an Amazon EMR cluster in a private subnet using Terraform. By following these steps, you can securely provision an EMR cluster for your big data processing needs. Feel free to customize the configurations to fit your specific requirements and environments.</p>

<p>Checkout the official article for reference <a href="https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-clusters-in-a-vpc.html" class="btn btn--xsmall btn--info">Link</a>.</p>]]></content><author><name>Pulkit Kapoor</name><email>pulkit42041@gmail.com</email></author><category term="aws" /><category term="aws" /><category term="emr" /><category term="terraform" /><category term="compute" /><category term="bigdata" /><category term="dataengineering" /><summary type="html"><![CDATA[How to setup your EMR Cluster in Private subnet and access it using EC2 Endpoint]]></summary></entry><entry><title type="html">Apache Spark Unified Memory</title><link href="https://www.pulkitkapoor.com/dataengineering/Apache-spark-memory-management/" rel="alternate" type="text/html" title="Apache Spark Unified Memory" /><published>2024-04-06T00:00:00+00:00</published><updated>2024-04-06T00:00:00+00:00</updated><id>https://www.pulkitkapoor.com/dataengineering/Apache-spark-memory-management</id><content type="html" xml:base="https://www.pulkitkapoor.com/dataengineering/Apache-spark-memory-management/"><![CDATA[<h2 id="introduction">Introduction</h2>

<p>Apache Spark, a powerful distributed processing engine, relies heavily on memory management for optimal performance. The Unified Memory Manager (<abbr title="Unified Memory Model">UMM</abbr>) introduced in Spark 1.6 plays a critical role in this by efficiently allocating and managing memory resources across your cluster.</p>

<h2 id="understanding-memory-pools-in-spark">Understanding Memory Pools in Spark</h2>
<p>Understanding concepts like reserved memory, executor memory, executor memory fraction, storage fraction, and overhead memory can help optimize memory usage and improve Spark application performance. The <abbr title="Unified Memory Model">UMM</abbr> manages two primary memory pools within the broader execution memory, storage and execution:</p>

<h5 id="storage-memory">Storage Memory</h5>
<p>This part of memory is used for storing RDDs when they are cached using <code class="language-plaintext highlighter-rouge">persist</code> and <code class="language-plaintext highlighter-rouge">cache</code><sup id="fnref:Caching"><a href="#fn:Caching" class="footnote" rel="footnote" role="doc-noteref">1</a></sup>, and also served to store <code class="language-plaintext highlighter-rouge">broadcast</code><sup id="fnref:Broadcast"><a href="#fn:Broadcast" class="footnote" rel="footnote" role="doc-noteref">2</a></sup> data. You can tune this by using the config <code class="language-plaintext highlighter-rouge">spark.executor.storage.fraction</code></p>

<h5 id="execution-memory">Execution Memory</h5>
<p>For certain data manipulations, spark needs to work on data like combining data using joins, sorting, aggregations etc. For performing this active computations, spark makes use of execution memory.
Examples: In-memory joins, sorting and aggregations</p>

<p class="notice--info">In addition to the Unified Memory, we have other parts of memory reserved for internal processes, user objects etc.</p>

<h2 id="reserved-and-overhead-memory">Reserved and Overhead Memory</h2>

<h5 id="overhead-memory">Overhead Memory</h5>
<p>Overhead memory is additional memory required by each executor for off-heap memory, task execution, and other internal overheads. The default overhead memory is 384MB or 10% or executor memory whichever is higher, which is typically sufficient for most workloads.</p>

<h5 id="reserved-memory">Reserved Memory</h5>
<p>Spark reserves a portion of the Unified Memory for internal metadata and other purposes not related to storage or execution. By default, Spark reserves 300MB of memory for these purposes.</p>

<h2 id="simple-example">Simple Example</h2>

<p>Consider a Spark job running on a physical node with 20GB memory. Requesting an executor with <code class="language-plaintext highlighter-rouge">spark.executor.memory = 10GB</code> and<code class="language-plaintext highlighter-rouge"> spark.executor.offHeap.memory = 1GB</code> would distribute the Spark executor’s container memory accordingly:.</p>

<figure style="max-width: 450px" class="align-center">
  <div class="image-wrapper">
    <img src="/assets/images/collections/posts/2024-03-12-Apache-spark-memory-management/Spark Memory.png" alt="Spark executor memory distribution" />

  </div>
  <figcaption>Executor Memory Distribution</figcaption>
</figure>

<ul>
  <li><strong>Overheads (1G)</strong> - There are certain parts of memory that are required for managing JVM, Spark’s internal processes, Yarn’s processes. These are shown by red blocks and known as <code class="language-plaintext highlighter-rouge">reserved memory</code> (used by spark) and <code class="language-plaintext highlighter-rouge">overhead</code> (used by YARN).</li>
  <li><strong>On-Heap Memory (<code class="language-plaintext highlighter-rouge">spark.executor.memory = 10G</code>)</strong> - This is JVM managed memory. Objects in on-heap are often garbage collected when needed, and this results in Garbage collection pauses. If you notice very high garbage collection times, then using off-heap memory is a good aid to the issue</li>
  <li><strong>Off-Heap Memory (<code class="language-plaintext highlighter-rouge">spark.executor.offHeap.memory = 1G</code>)</strong> - This piece of memory resides outside control of JVM and is managed by the OS. Off-heap memory is disabled by default and is often used to reduce the garbage collection cycles</li>
</ul>

<p>In case of On-heap memory, it is typically split into <code class="language-plaintext highlighter-rouge">Unified Memory</code> (Execution + Storage) memory, <code class="language-plaintext highlighter-rouge">User Memory</code> and <code class="language-plaintext highlighter-rouge">Reserved</code>. The amount of memory that goes to each depends on the below configs -</p>

<ul>
  <li><strong>Execution <code class="language-plaintext highlighter-rouge">spark.executor.memory.fraction (default 0.6)</code></strong> - Executor memory fraction is the ratio of Unified Memory that should be allocated to the execution memory pool. It is configured using the spark.memory.fraction property and defaults to 0.75, meaning that 75% of the Unified Memory is allocated to execution memory.</li>
  <li><strong>Storage <code class="language-plaintext highlighter-rouge">spark.executor.storage.fraction (default 0.5)</code></strong> - Storage fraction is the ratio of executor memory that should be used for storage purposes. It is configured using the spark.memory.storageFraction property and defaults to 0.5, meaning that 50% of the executor memory is allocated for storage.</li>
</ul>

<h2 id="optimization-tips">Optimization Tips</h2>
<ol>
  <li>Tune Memory Fractions: Adjust the spark.executor.memory.fraction and spark.executor.storage.fraction configurations based on your workload to optimize memory allocation for execution and storage.</li>
  <li>Monitor and Tune: Regularly monitor memory usage and performance metrics to identify bottlenecks and adjust configurations accordingly.</li>
  <li>Use Efficient Data Structures: Use efficient data structures like DataFrames and Datasets, which can help reduce memory usage and improve performance.</li>
</ol>

<h2 id="memory-calculator">Memory Calculator</h2>
<p>Below is a simple Javascript interactive Diagram to help you understand how parameters affect the allocation of On-Heap memory.</p>

<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Spark Memory Management Visualization</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-datalabels"></script>
    <style>
        .container {
            background-color: #fff;
            border-radius: 8px;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.3);
            text-align: left;
            max-width: 570px;
            width: 100%;
            margin: 0 auto;
            border-radius:20px;
            margin-top:1.3em;
            margin-bottom:1.8em;
        }
        
        canvas {
            margin-top: 30px;
            margin-bottom: 25px;
        }

        h1 {
            margin-top: 0;
            margin-bottom: 20px;
            text-align: center;
        }

        label {
            padding-right: 5px;
            font-weight: semibold;
            font-size: 0.8em;
            display: inline-block;
            width: 45%;
            margin-right: 10px;
        }

        input[type="number"] {
            font-size: 0.8em;
            padding: 5px;
            background-color: white;
            border: 0.2px solid gray;
        }

        input[type="range"],
        input[type="number"] {
            flex: 1;
            margin: 10px 0;
        }

        .form-group {
            display: flex;
            align-items: center;
        }

        .range-value {
            font-size: 0.8em;
            margin-left: 10px;
        }

        span {
            margin-right: 10px;
            margin-left: 0px !important;
        }
    </style>
</head>
<body class="viz-body">
    <div class="container">
        <h1>Spark Memory Management Visualization</h1>

        <canvas id="chart" height="140"></canvas>
        
        <div class="form-group">
            <label for="heapMemory">Executor.memory</label>
            <input type="number" id="heapMemory" value="1024" />
        </div>

        <div class="form-group">
            <label for="sparkMemoryFraction">Executor.memory.fraction</label>
            <span class="range-value" id="sparkMemoryFractionValue">0.75</span>
            <input type="range" id="sparkMemoryFraction" min="0" max="1" step="0.01" value="0.75" />
        </div>
        
        <div class="form-group">
            <label for="sparkStorageFraction">Executor.storage.fraction</label>
            <span class="range-value" id="sparkStorageFractionValue">0.5</span>
            <input type="range" id="sparkStorageFraction" min="0" max="1" step="0.01" value="0.5" />
        </div>

        
    </div>

    <script>
        const ctx = document.getElementById('chart').getContext('2d');

        const chart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: ['Java Heap Memory'],
                datasets: [
                    {
                        label: 'Reserved Memory',
                        backgroundColor: 'rgba(255, 99, 132, 0.6)',
                        data: [300],
                    },
                    {
                        label: 'User Memory',
                        backgroundColor: 'rgba(54, 162, 235, 0.6)',
                        data: [0],
                    },
                    {
                        label: 'Spark Storage Memory',
                        backgroundColor: 'rgba(255, 206, 86, 0.6)',
                        data: [0],
                    },
                    {
                        label: 'Spark Execution Memory',
                        backgroundColor: 'rgba(75, 192, 192, 0.6)',
                        data: [0],
                    },
                ],
            },
            options: {
                responsive: true,
                scales: {
                    x: { display: false, stacked: true },
                    y: { display: false, stacked: true, max: 1024, beforeFit: function(axis) {
                            axis.max = parseInt(document.getElementById('heapMemory').value)
                    } },
                },
                plugins: {
                    legend: { display: false },
                    datalabels: {
                        anchor: 'center',
                        align: 'center',
                        color: 'black',
                        font: { weight: 'semibold' },
                        formatter: function (value, context) {
                            return context.dataset.label + ' (' + Math.round(value) + 'MB' + ')';
                        },
                    },
                    tooltip: {
                        footerMarginTop:10,
                        callbacks: {
                            label: function (context) {
                                var label = '';
                                var per = 0;
                                label += Math.round(context.parsed.y) + ' MB';
                                per = Math.round(100 * context.parsed.y / parseInt(document.getElementById('heapMemory').value))
                                return `${label} (${per}%)`;
                            },
                            title: function (contexts) {
                                return contexts[0].dataset.label || '';
                            },
                            footer: function (contexts) {
                                var title = contexts[0].dataset.label || '';
                                var definitions = {
                                    'Reserved Memory': 'The memory reserved for non-Spark usage.',
                                    'User Memory': 'The memory available for caching and propagating internal data via shuffle operations.',
                                    'Spark Storage Memory': 'The memory used for caching RDDs, broadcast variables, and output data.',
                                    'Spark Execution Memory': 'The memory used for computation in shuffles, joins, sorts, and aggregations.'
                                };

                                return "" + ':: ' + definitions[title];
                            }
                        }
                    }
                },
            },
            plugins: [ChartDataLabels],
        });

        function updateChart() {
            const sparkMemoryFraction = parseFloat(document.getElementById('sparkMemoryFraction').value);
            const heapMemory = parseInt(document.getElementById('heapMemory').value);
            const sparkStorageFraction = parseFloat(document.getElementById('sparkStorageFraction').value);

            // Ensure spark.executor.memory is at least 300MB
            if (isNaN(heapMemory) || heapMemory < 300) {
                heapMemoryInput.value = 300;
                heapMemory = 300;
                alert("Executor memory cannot be less than reserved memory!")
            }

            const sparkMemory = heapMemory - 300;
            const userMemory = sparkMemory * (1.0 - sparkMemoryFraction);
            const unifiedMemory = sparkMemory - userMemory;
            const storageMemory = unifiedMemory * sparkStorageFraction;
            const execMemory = unifiedMemory - storageMemory;

            chart.data.datasets[1].data = [userMemory];
            chart.data.datasets[2].data = [storageMemory];
            chart.data.datasets[3].data = [execMemory];

            chart.update();

            document.getElementById('sparkMemoryFractionValue').textContent = sparkMemoryFraction;
            document.getElementById('sparkStorageFractionValue').textContent = sparkStorageFraction;
        }

        document.getElementById('sparkMemoryFraction').addEventListener('input', updateChart);
        document.getElementById('heapMemory').addEventListener('input', updateChart);
        document.getElementById('sparkStorageFraction').addEventListener('input', updateChart);

        updateChart();
    </script>
</body>
</html>

<h2 id="conclusion">Conclusion</h2>
<p>Understanding Apache Spark’s memory management is crucial for optimizing performance and avoiding memory-related issues. By understanding the different memory pools and how they are allocated, you can effectively tune your Spark applications for better performance.</p>

<hr />

<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:Caching">
      <p>Caching - While processing data, you can cache results of a time-consuming data process to ensure that this data is not recomputed if needed by downstream processes. Caching can speed up data pipelines that reuse data RDDs. <a href="#fnref:Caching" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:Broadcast">
      <p>Broadcast - Very useful when you want to perform table joins and one of the tables is small enough to be transferred over to every executor. This enables map side join, as data required for join is accessible in executor memory. <a href="#fnref:Broadcast" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Pulkit Kapoor</name><email>pulkit42041@gmail.com</email></author><category term="dataengineering" /><category term="spark" /><category term="memorymodel" /><category term="unifiedmemory" /><category term="dataengineering" /><summary type="html"><![CDATA[How is memory managed by latest releases of Apache Spark.]]></summary></entry><entry><title type="html">Apache Hadoop - Background</title><link href="https://www.pulkitkapoor.com/dataengineering/Apache-hadoop-background/" rel="alternate" type="text/html" title="Apache Hadoop - Background" /><published>2024-03-07T00:00:00+00:00</published><updated>2024-03-07T00:00:00+00:00</updated><id>https://www.pulkitkapoor.com/dataengineering/Apache-hadoop-background</id><content type="html" xml:base="https://www.pulkitkapoor.com/dataengineering/Apache-hadoop-background/"><![CDATA[<blockquote>
  <p>Technologies come and go, but data is here to grow!</p>
</blockquote>

<h2 id="introduction">Introduction</h2>
<p>Data is at the core of every application, driving decision-making and improving user experiences. Over time, organizations have continually invested in better ways to collect, analyze, and utilize data. This evolution has led to the development of various technologies, each building upon the successes and shortcomings of its predecessors.</p>

<ul>
  <li>Excel</li>
  <li>Oracle SQL, Microsoft SQL Server</li>
  <li>Hadoop</li>
  <li>Spark</li>
</ul>

<p>Each evolution aimed to solve a specific outcoming of previous generation of solutions.</p>
<h2 id="the-big-data-problem">The Big Data Problem</h2>
<p><img src="/assets/images/collections/posts/2024-03-07-Apache-hadoop-background/spark-articles-big-data-problems.png" alt="image-right" class="align-left" />
With the advent of the internet and mobile devices, the volume and variety of data exploded. Data came in various formats, including json, xml, doc, mp4, avro, among others. This increase in data volume and velocity posed a significant challenge for traditional data processing systems, such as relational database management systems (<abbr title="Relational Database Management Systems">RDBMS</abbr>).</p>

<p>These together, <mark>three Vs</mark>, contitute what we call the big data problem.</p>

<p>Event though <abbr title="Relational Database Management Systems">RDBMS</abbr> have evolved over many decades to meet the every changing industry demands, but they have not been designed to handle big data problems.</p>

<h3 id="distributed-computing">Distributed Computing</h3>
<p>To address the scalability, availability, and cost challenges posed by big data, distributed computing systems emerged. These systems, like Apache Hadoop and later Apache Spark, utilize clusters of machines to distribute and process data in parallel. This approach allows for efficient processing of large volumes of data while ensuring fault tolerance and scalability.</p>

<p>Apache Spark, in particular, has gained popularity for its speed and ease of use, becoming a preferred choice for many data engineers and analysts. By leveraging in-memory processing and a rich set of APIs, Spark has become a powerful tool for processing and analyzing large-scale data.</p>

<p>Hadoop like sytem have the following features -</p>
<ol>
  <li>Scalability: <em>If the demand rises, say now we have double the amount of data, how easy is it for us to store, process and serve the same.</em></li>
  <li>High Availability: <em>Is the system fault tolerant, what happens if there is a hardware failure, software, network or power failure! Does it keep working.</em></li>
  <li>Cost: <em>Is the solution expensive, how cost effective is it to scala or to increase availability?</em></li>
</ol>

<h2 id="basic-background-hadoop">Basic background: Hadoop</h2>
<p>In simplicity, hadoop consists of 3 main layers: <br />
<img src="/assets/images/collections/posts/2024-03-07-Apache-hadoop-background/spark-articles-hadoop-1.png" alt="image-right" class="align-right" /></p>
<ol>
  <li>YARN - Cluster operating system, responsible for managing resources of the <abbr title="Group of physical or virtual servers that make up the distributed cluster">cluster</abbr>.</li>
  <li><abbr title="hadoop file system">HDFS</abbr> - Forms the storage layer. Data stored is split, replicated and distributed across <abbr title="Group of physical or virtual servers that make up the distributed cluster">cluster</abbr> making it reliable and fault tolerant.</li>
  <li>Map / Reduce - Allows users to write Java programs to process the data stored on hadoop.</li>
</ol>

<blockquote>
  <p>Just like windows makes laptop hardware usable, <abbr title="Group of physical or virtual servers that make up the distributed cluster">cluster</abbr> os allows to run applications like spark on a <abbr title="Group of physical or virtual servers that make up the distributed cluster">cluster</abbr></p>
</blockquote>

<p>The point is hadoop was designed to allow working with <abbr title="Group of physical or virtual servers that make up the distributed cluster">cluster</abbr> of computers easier. Today’s distributed processing engines are so powerful that they totally abstract away the complexity and so we can pretty much write programs in the same as we would do for a single computer.</p>

<h3 id="hadoop-ecosystem">Hadoop ecosystem</h3>
<p>The core hadoop consist of Yarn, <abbr title="hadoop file system">HDFS</abbr> and Map/Reduce. Over years the innovate big data community has developed several other tools that are designed to work in hadoop and making it better. Some examples are:</p>
<ul>
  <li>Hive: Data warehousing and SQL-like query language for Hadoop.</li>
  <li>Hbase: Distributed, scalable, NoSQL database for Hadoop.</li>
  <li>Sqoop: Tool for transferring data between Hadoop and structured databases.</li>
  <li>Oozie: Workflow scheduler for managing Hadoop jobs.</li>
</ul>

<h3 id="hadoop-architecture">Hadoop architecture</h3>
<p>To understand the core architecture of Hadoop, we have to understand 3 compoenents which are <abbr title="hadoop file system">HDFS</abbr> (storage layer), YARN (os layer) and Map-Reduce (compute framework). The key thing to remember is that hadoop is written in java, so each component, lets say <abbr title="hadoop file system">HDFS</abbr>, will have it daemon java process run on all machines to manage the distributed storage. For explanation purpose, we will assume we have a 5 node <abbr title="Group of physical or virtual servers that make up the distributed cluster">cluster</abbr>.</p>

<h3 id="hdfs-hadoop-file-system"><abbr title="hadoop file system">HDFS</abbr> (Hadoop File System)</h3>
<p>Hadoop File System is the hadoop solution to distributed storage. <abbr title="hadoop file system">HDFS</abbr> is open-source and it got its inspiiration from Google’s white paper on GFS or Google File System.</p>

<p>The below diagram shows the basic architecture of <abbr title="hadoop file system">HDFS</abbr>. In this diagram we can see a <abbr title="Group of physical or virtual servers that make up the distributed cluster">cluster</abbr> of 5 nodes, one master and 4 slaves. This is known as the master-slave architecture, you can think as master as the coordiator and the slaves as workers following orders from master.</p>

<figure style="max-width: 590px" class="align-center">
  <div class="image-wrapper">
    <img src="/assets/images/collections/posts/2024-03-07-Apache-hadoop-background/spark-article-hdfs-arch.png" alt="HDFS architecture diagram" />
  </div>
  <figcaption>HDFS architecture</figcaption>
</figure>

<p><abbr title="hadoop file system">HDFS</abbr> consists of 2 type of services (which as java processes running on nodes under the hood ). These services are:</p>
<ol>
  <li>Name Node (runs on master)</li>
  <li>Data Node (runs on workers)</li>
</ol>

<h4 id="name-node">Name node</h4>
<p>Name node runs on the master node and is reponsible for book-keeping. Whenever you read or write data to <abbr title="hadoop file system">HDFS</abbr>, name node is going to store and track meta data about the data stored on data nodes. So, think of name node as the librarian and data-node as the shelves where actual information is stored away.</p>

<h4 id="data-node">Data node</h4>
<p>Data node is where the actual data being written to <abbr title="hadoop file system">HDFS</abbr> is stored. When you want to store a big file say 1GB file on <abbr title="hadoop file system">HDFS</abbr>, it is not stored as a single file. The file is broken down into what is called blocks, and these blocks are stored in data nodes. The blocks stored are also replicated to ease data recovery if one of the nodes fail. This is controlled by replication factor.</p>

<p class="notice--info">Default block size in <abbr title="hadoop file system">HDFS</abbr> is 128MB</p>

<h4 id="what-exactly-is-stored-in-name-node">What exactly is stored in name node?</h4>
<p>As mentioned before, name node stores the metadata about original data. To make the idea concrete, consider an example of file metadata stored by name node.</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code>- NAMENODE
    FILE - example.txt
    DIRECTORY - /data
    FILE_SIZE - 1GB
    FILE BLOCKS - 
      - BLOCK1
        BLOCK_ID - e3245243
        BLOCK_LOCATION - DATANODE1/disk1/data/rufrebv34343223.txt
      ...
      - BLOCKN
        BLOCK_ID - e3245243
        BLOCK_LOCATION - DATANODE1/disk1/data/rufrebv34343223.txt
</code></pre></div></div>
<p>In case you have a hadoop <abbr title="Group of physical or virtual servers that make up the distributed cluster">cluster</abbr> up and running, you can fetch above info by running <code class="language-plaintext highlighter-rouge">hdfs fsck hdfs://file -location -blocks -files</code>.</p>

<h4 id="how-reading-from-hdfs-works">How reading from <abbr title="hadoop file system">HDFS</abbr> works?</h4>
<p>Say you made a request to hdfs to read contents of a file using command <code class="language-plaintext highlighter-rouge">hdfs dfs -cat hdfs://&lt;filepath&gt;</code>. Then the following will happen:</p>
<ol>
  <li><abbr title="hadoop file system">HDFS</abbr> client on your machine connects to namenode</li>
  <li>Name node responds back with metadata about where different blocks are stored</li>
  <li><abbr title="hadoop file system">HDFS</abbr> client connects to the data nodes directly to get the respective blocks</li>
  <li><abbr title="hadoop file system">HDFS</abbr> client uses metadata about file to assemble the blocks in right order and create the file</li>
</ol>

<h4 id="how-writing-to-hdfs-works">How writing to <abbr title="hadoop file system">HDFS</abbr> works?</h4>
<p>Say you decide to write a file to <abbr title="hadoop file system">HDFS</abbr>, so you issue command <code class="language-plaintext highlighter-rouge">hdfs dfs -copyFromLocal localpath hdfspath</code>. When you issue this command:</p>
<ol>
  <li>Your <abbr title="hadoop file system">HDFS</abbr> client connects to namenode for the write operation</li>
  <li>Name node responds back redirections to data nodes</li>
  <li><abbr title="hadoop file system">HDFS</abbr> client splits the file into blocks and sends write requests to data nodes</li>
  <li>Once the client receive acknowledgment that all blocks were written it passes the info the name node</li>
  <li>Name node persists the meta data for file usage</li>
</ol>

<h3 id="common-hdfs-commands">Common <abbr title="hadoop file system">HDFS</abbr> commands</h3>
<p>Even though, your data is stored in a distributed fashion, working with <abbr title="hadoop file system">HDFS</abbr> is as easy as interacting with your local file system. Some useful commands are:</p>
<ul>
  <li>List files - <code class="language-plaintext highlighter-rouge">hdfs dfs -ls &lt;path&gt;</code></li>
  <li>Copy files - <code class="language-plaintext highlighter-rouge">hdfs dfs -copyFromLocal &lt;local-src&gt; &lt;hdfs-dest&gt;</code></li>
  <li>Change file permissions - <code class="language-plaintext highlighter-rouge">hdfs dfs chmod 777 &lt;path&gt;</code></li>
  <li>Rename files - <code class="language-plaintext highlighter-rouge">hdfs dfs -mv &lt;src&gt; &lt;dest&gt;</code></li>
  <li>List contents - <code class="language-plaintext highlighter-rouge">hdfs dfs -cat &lt;file&gt;</code></li>
  <li>Get disk usage - <code class="language-plaintext highlighter-rouge">hdfs dfs -du -s -h /user/test</code></li>
</ul>

<h2 id="hadoop-yarn">Hadoop YARN</h2>
<p>In the previous sections, we talked about <abbr title="hadoop file system">HDFS</abbr> which forms the storage layer of hadoop ecosystem. Once you have the data in place, you may want to run some computation on it and make use of it. This is where YARN comes into picture. Just like <abbr title="hadoop file system">HDFS</abbr> has 2 kind of java processes (namenode and datanode), YARN follows a similar master slave architecture. The master and slave components of YARN are -</p>
<ol>
  <li>Resource Manager</li>
  <li>Node Manager</li>
</ol>]]></content><author><name>Pulkit Kapoor</name><email>pulkit42041@gmail.com</email></author><category term="dataengineering" /><category term="hadoop" /><category term="learn" /><category term="history" /><category term="dataengineering" /><summary type="html"><![CDATA[Understand the background and basics of Hadoop environment.]]></summary></entry><entry><title type="html">Email Reminders - React &amp;amp; AWS</title><link href="https://www.pulkitkapoor.com/project/Reminder-App-Aws-React/" rel="alternate" type="text/html" title="Email Reminders - React &amp;amp; AWS" /><published>2024-03-04T00:00:00+00:00</published><updated>2024-04-03T00:00:00+00:00</updated><id>https://www.pulkitkapoor.com/project/Reminder-App-Aws-React</id><content type="html" xml:base="https://www.pulkitkapoor.com/project/Reminder-App-Aws-React/"><![CDATA[<p><a href="https://github.com/k-pulkit/EmailReminders-React_Aws_IaC" class="btn btn--info">Checkout the project repo!</a></p>

<p class="notice--warning">Every big project is done one step at a time. Slowly and steadily you can dig at new concepts, learn and so can build any complex application</p>

<!-- <figure class="">
    <a href="https://github.com/k-pulkit/EmailReminders-React_Aws_IaC/assets/71238192/386d3778-eedc-4a33-b50f-ed5a44b63b62"><img src="https://github.com/k-pulkit/EmailReminders-React_Aws_IaC/assets/71238192/386d3778-eedc-4a33-b50f-ed5a44b63b62"></a>
</figure> -->

<h2 id="objective">Objective</h2>

<!-- ![image-center](https://github.com/k-pulkit/EmailReminders-React_Aws_IaC/assets/71238192/386d3778-eedc-4a33-b50f-ed5a44b63b62){: .align-center} -->

<p>In this blog post, we’ll explore the development of a Reminder App using a modern tech stack, including various AWS services for the backend and React for the frontend. This application provides a seamless authentication flow and a robust reminder management system.</p>

<h2 id="tech-stack">Tech Stack</h2>

<p>The application uses serverless architecture. The front is a modern SPA (Single Page Application) written in React, and the backend consists of AWS services like <code class="language-plaintext highlighter-rouge">Cognito, Lambda, API Gateway</code>.</p>

<figure class="">
    <a href="https://github.com/k-pulkit/EmailReminders-React_Aws_IaC/assets/71238192/4614ccaa-bf9b-4762-9c8e-675540150664"><img src="https://github.com/k-pulkit/EmailReminders-React_Aws_IaC/assets/71238192/4614ccaa-bf9b-4762-9c8e-675540150664" alt="Reminder app screenshot" /></a>
</figure>

<h3 id="frontend">Frontend</h3>
<ul>
  <li><strong>React</strong>: A JavaScript library for building user interfaces, React allows developers to create reusable UI components that can update efficiently when the data changes.</li>
  <li><strong>JavaScript</strong>: The programming language used for implementing the app’s logic and interactions.</li>
  <li><strong>Tailwind CSS</strong>: A utility-first CSS framework used for styling the app, providing a customizable and responsive design.</li>
</ul>

<h3 id="backend-aws">Backend (AWS)</h3>
<ul>
  <li><strong>Cognito User Pools</strong>: AWS Cognito provides user authentication and authorization for the app. User Pools allow you to manage user sign-up and sign-in processes.</li>
  <li><strong>API Gateway</strong>: AWS API Gateway is used to create, publish, maintain, monitor, and secure APIs. It acts as a front door for the app’s backend services.</li>
  <li><strong>IAM (Identity and Access Management)</strong>: IAM is used to securely control access to AWS services and resources for the app’s users and services.</li>
  <li><strong>Lambda Functions</strong>: AWS Lambda is used for executing serverless functions that respond to events triggered by the app, such as setting reminders and sending emails.</li>
  <li><strong>Simple Notification Service (SNS)</strong>: SNS is used for sending notifications to users’ email addresses when reminders are due.</li>
  <li><strong>Step Functions</strong>: AWS Step Functions coordinate multiple AWS services into serverless workflows, allowing for the orchestration of reminder creation and management processes.</li>
</ul>

<h3 id="infrastructure-as-code-iac">Infrastructure as Code (IaC)</h3>
<ul>
  <li><strong>Serverless Framework</strong>: The Serverless Framework is used for defining and deploying AWS infrastructure as code, enabling the app’s infrastructure to be managed and deployed easily.</li>
</ul>

<h3 id="deployment">Deployment</h3>
<ul>
  <li><strong>GitHub Pages</strong>: The app is deployed using GitHub Pages, providing a simple and free hosting solution for static websites.</li>
</ul>

<h2 id="how-it-works">How it Works</h2>

<h3 id="authentication-flow-with-cognito">Authentication Flow with Cognito</h3>
<ul>
  <li>When a user signs up for the app, their information is stored securely in a user pool managed by AWS Cognito.</li>
  <li>Upon successful sign-in, the app receives an authentication token that is used to authenticate subsequent API requests.</li>
</ul>

<h3 id="reminder-creation-and-management">Reminder Creation and Management</h3>
<ul>
  <li>Users can set reminders through the app’s user interface, specifying the delay after which reminders are sent to their email.</li>
  <li>Lambda functions are triggered to create reminders and schedule them on Step functions for delivery using SNS.</li>
  <li>Users can view a list of active reminders and have completed reminders automatically deleted. They can also manually abort reminders.</li>
</ul>

<h3 id="deployment-with-serverless-framework-and-github-pages">Deployment with Serverless Framework and GitHub Pages</h3>
<ul>
  <li>The app’s infrastructure is defined using the Serverless Framework, which allows for easy deployment and management of AWS resources.</li>
  <li>GitHub Pages is used to host the frontend of the app, providing a simple and cost-effective hosting solution.</li>
</ul>

<h2 id="how-to-run-the-app">How to Run the App</h2>

<p>To run the application, clone the repository and execute the following commands:</p>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Deploy infrastructure</span>
npm init <span class="nt">-y</span>
sls deploy

<span class="c"># Run locally</span>
<span class="nb">cd</span> ./frontend/reminder-all
npm run dev
</code></pre></div></div>

<h2 id="conclusion">Conclusion</h2>

<p>The Reminder App demonstrates the power and flexibility of modern tech stacks, leveraging AWS services and React to create a robust and user-friendly application. By understanding the underlying technologies and their interactions, developers can build similar applications with ease.</p>]]></content><author><name>Pulkit Kapoor</name><email>pulkit42041@gmail.com</email></author><category term="project" /><category term="project" /><category term="react" /><category term="aws" /><category term="development" /><category term="modern" /><summary type="html"><![CDATA[AWS Reminder application built using React and AWS services like Lambda, cognito etc.]]></summary></entry><entry><title type="html">React concepts you must-know!</title><link href="https://www.pulkitkapoor.com/frontend/React-for-begginers/" rel="alternate" type="text/html" title="React concepts you must-know!" /><published>2024-02-24T00:00:00+00:00</published><updated>2024-04-03T00:00:00+00:00</updated><id>https://www.pulkitkapoor.com/frontend/React-for-begginers</id><content type="html" xml:base="https://www.pulkitkapoor.com/frontend/React-for-begginers/"><![CDATA[<p><a href="https://github.com/k-pulkit/react-store-app-demo" class="btn btn--info">Checkout my first react project!</a></p>

<p class="notice--warning">My approach to learning react has been hands on. Watch some basic videos to familiarize yourself and just start. I recommend using Javascript mastery to practice the concepts.</p>

<h2 id="introduction-to-react">Introduction to React</h2>

<p>React is a JavaScript library for building user interfaces. It allows developers to create interactive UI components that respond to user input. React uses a declarative approach, meaning you describe the desired outcome and let React handle the details of updating the UI when the underlying data changes.</p>

<h2 id="components">Components</h2>

<p>Components are the building blocks of a React application. They are reusable, self-contained pieces of UI that can be composed together to create complex interfaces. There are two main types of components in React: functional components and class components.</p>

<h3 id="functional-components">Functional Components</h3>

<p>Functional components are JavaScript functions that return JSX (a syntax extension for JavaScript).</p>

<div class="language-jsx highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">Welcome</span> <span class="o">=</span> <span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="k">return</span> <span class="p">&lt;</span><span class="nt">h1</span><span class="p">&gt;</span>Hello, <span class="si">{</span><span class="nx">props</span><span class="p">.</span><span class="nx">name</span><span class="si">}</span><span class="p">&lt;/</span><span class="nt">h1</span><span class="p">&gt;;</span>
<span class="p">};</span>
</code></pre></div></div>
<p>They are simpler and easier to understand than class components.</p>

<h3 id="class-components">Class Components</h3>

<p>Class components are ES6 classes that extend <code class="language-plaintext highlighter-rouge">React.Component</code>. They have additional features such as state and lifecycle methods.</p>

<div class="language-jsx highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">class</span> <span class="nc">Welcome</span> <span class="kd">extends</span> <span class="nc">React</span><span class="p">.</span><span class="nx">Component</span> <span class="p">{</span>
  <span class="nf">render</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">return</span> <span class="p">&lt;</span><span class="nt">h1</span><span class="p">&gt;</span>Hello, <span class="si">{</span><span class="k">this</span><span class="p">.</span><span class="nx">props</span><span class="p">.</span><span class="nx">name</span><span class="si">}</span><span class="p">&lt;/</span><span class="nt">h1</span><span class="p">&gt;;</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h2 id="jsx">JSX</h2>

<p>JSX allows you to write HTML-like code in your JavaScript files. It makes your React components more readable and expressive.</p>

<div class="language-jsx highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">element</span> <span class="o">=</span> <span class="p">&lt;</span><span class="nt">h1</span><span class="p">&gt;</span>Hello, world!<span class="p">&lt;/</span><span class="nt">h1</span><span class="p">&gt;;</span>
<span class="nx">ReactDOM</span><span class="p">.</span><span class="nf">render</span><span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nb">document</span><span class="p">.</span><span class="nf">getElementById</span><span class="p">(</span><span class="dl">'</span><span class="s1">root</span><span class="dl">'</span><span class="p">));</span>
</code></pre></div></div>

<h2 id="props">Props</h2>

<p>Props (short for properties) are used to pass data from parent components to child components in React. They are read-only and cannot be modified within the child component.</p>

<div class="language-jsx highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">Welcome</span> <span class="o">=</span> <span class="p">(</span><span class="nx">props</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="k">return</span> <span class="p">&lt;</span><span class="nt">h1</span><span class="p">&gt;</span>Hello, <span class="si">{</span><span class="nx">props</span><span class="p">.</span><span class="nx">name</span><span class="si">}</span><span class="p">&lt;/</span><span class="nt">h1</span><span class="p">&gt;;</span>
<span class="p">};</span>

<span class="kd">const</span> <span class="nx">element</span> <span class="o">=</span> <span class="p">&lt;</span><span class="nc">Welcome</span> <span class="na">name</span><span class="p">=</span><span class="s">"Alice"</span> <span class="p">/&gt;;</span>
<span class="nx">ReactDOM</span><span class="p">.</span><span class="nf">render</span><span class="p">(</span><span class="nx">element</span><span class="p">,</span> <span class="nb">document</span><span class="p">.</span><span class="nf">getElementById</span><span class="p">(</span><span class="dl">'</span><span class="s1">root</span><span class="dl">'</span><span class="p">));</span>
</code></pre></div></div>

<h2 id="state">State</h2>

<p>State is used to manage the internal state of a component in React. It allows components to change their output over time in response to user actions, network responses, and other events. State is declared using the <code class="language-plaintext highlighter-rouge">useState</code> hook in functional components.</p>

<div class="language-jsx highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">Clock</span> <span class="o">=</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="kd">const</span> <span class="p">[</span><span class="nx">date</span><span class="p">,</span> <span class="nx">setDate</span><span class="p">]</span> <span class="o">=</span> <span class="nf">useState</span><span class="p">(</span><span class="k">new</span> <span class="nc">Date</span><span class="p">());</span>

  <span class="nf">useEffect</span><span class="p">(()</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="kd">const</span> <span class="nx">timerID</span> <span class="o">=</span> <span class="nf">setInterval</span><span class="p">(()</span> <span class="o">=&gt;</span> <span class="nf">setDate</span><span class="p">(</span><span class="k">new</span> <span class="nc">Date</span><span class="p">()),</span> <span class="mi">1000</span><span class="p">);</span>
    <span class="k">return </span><span class="p">()</span> <span class="o">=&gt;</span> <span class="nf">clearInterval</span><span class="p">(</span><span class="nx">timerID</span><span class="p">);</span>
  <span class="p">},</span> <span class="p">[]);</span>

  <span class="k">return</span> <span class="p">&lt;</span><span class="nt">div</span><span class="p">&gt;</span><span class="si">{</span><span class="nx">date</span><span class="p">.</span><span class="nf">toLocaleTimeString</span><span class="p">()</span><span class="si">}</span><span class="p">&lt;/</span><span class="nt">div</span><span class="p">&gt;;</span>
<span class="p">};</span>
</code></pre></div></div>

<h2 id="state-management">State Management</h2>

<p>As your React applications grow in complexity, you may need a more robust solution for state management. Two common approaches are using Redux Toolkit and Context API.</p>

<h3 id="redux-toolkit">Redux Toolkit</h3>

<p>Redux is a state management library for JavaScript applications, and Redux Toolkit is its official toolset for simplifying Redux development. It helps you write Redux logic more efficiently with fewer lines of code.</p>

<div class="language-jsx highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">import</span> <span class="p">{</span> <span class="nx">configureStore</span> <span class="p">}</span> <span class="k">from</span> <span class="dl">'</span><span class="s1">@reduxjs/toolkit</span><span class="dl">'</span><span class="p">;</span>

<span class="kd">const</span> <span class="nx">store</span> <span class="o">=</span> <span class="nf">configureStore</span><span class="p">({</span>
  <span class="na">reducer</span><span class="p">:</span> <span class="p">{</span>
    <span class="c1">// Define your reducers here</span>
  <span class="p">},</span>
<span class="p">});</span>

<span class="c1">// Access the store's state</span>
<span class="kd">const</span> <span class="nx">state</span> <span class="o">=</span> <span class="nx">store</span><span class="p">.</span><span class="nf">getState</span><span class="p">();</span>
</code></pre></div></div>

<h3 id="context-api">Context API</h3>

<p>Context API is a feature in React that allows you to pass data through the component tree without having to pass props down manually at every level. It’s useful for sharing data that needs to be accessible by many components.</p>

<div class="language-jsx highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">import</span> <span class="nx">React</span><span class="p">,</span> <span class="p">{</span> <span class="nx">createContext</span><span class="p">,</span> <span class="nx">useContext</span> <span class="p">}</span> <span class="k">from</span> <span class="dl">'</span><span class="s1">react</span><span class="dl">'</span><span class="p">;</span>

<span class="kd">const</span> <span class="nx">MyContext</span> <span class="o">=</span> <span class="nf">createContext</span><span class="p">();</span>

<span class="kd">const</span> <span class="nx">MyProvider</span> <span class="o">=</span> <span class="p">({</span> <span class="nx">children</span> <span class="p">})</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="kd">const</span> <span class="nx">sharedState</span> <span class="o">=</span> <span class="p">{</span> <span class="cm">/* Your shared state */</span> <span class="p">};</span>

  <span class="k">return </span><span class="p">(</span>
    <span class="p">&lt;</span><span class="nc">MyContext</span><span class="p">.</span><span class="nc">Provider</span> <span class="na">value</span><span class="p">=</span><span class="si">{</span><span class="nx">sharedState</span><span class="si">}</span><span class="p">&gt;</span>
      <span class="si">{</span><span class="nx">children</span><span class="si">}</span>
    <span class="p">&lt;/</span><span class="nc">MyContext</span><span class="p">.</span><span class="nc">Provider</span><span class="p">&gt;</span>
  <span class="p">);</span>
<span class="p">};</span>

<span class="kd">const</span> <span class="nx">useSharedState</span> <span class="o">=</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="nf">useContext</span><span class="p">(</span><span class="nx">MyContext</span><span class="p">);</span>

<span class="c1">// Usage</span>
<span class="kd">const</span> <span class="nx">Component</span> <span class="o">=</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="kd">const</span> <span class="nx">sharedState</span> <span class="o">=</span> <span class="nf">useSharedState</span><span class="p">();</span>
  <span class="c1">// Use sharedState</span>
<span class="p">};</span>
</code></pre></div></div>

<h2 id="conclusion">Conclusion</h2>

<p>These are some of the fundamental concepts every beginner should know when starting with React using functional components. Understanding state management using Redux Toolkit and Context API can help you build more complex and maintainable React applications. Happy coding!</p>]]></content><author><name>Pulkit Kapoor</name><email>pulkit42041@gmail.com</email></author><category term="frontend" /><category term="frontend" /><category term="react" /><category term="ui" /><category term="modern" /><summary type="html"><![CDATA[Most important concepts to get started with react covered in this post.]]></summary></entry><entry><title type="html">What is serverless framework</title><link href="https://www.pulkitkapoor.com/infra%20as%20code/The-serverless-framework/" rel="alternate" type="text/html" title="What is serverless framework" /><published>2024-01-22T00:00:00+00:00</published><updated>2024-01-09T00:00:00+00:00</updated><id>https://www.pulkitkapoor.com/infra%20as%20code/The-serverless-framework</id><content type="html" xml:base="https://www.pulkitkapoor.com/infra%20as%20code/The-serverless-framework/"><![CDATA[<p><a href="https://github.com/k-pulkit/source-demo-serverless-framework/tree/main" class="btn btn--info">Checkout the github repository for this!</a></p>

<p class="notice--warning">In addition to basic examples shown in this code, there are other use cases that have been explored in repository</p>

<h2 id="introduction">Introduction</h2>
<p>In this series, we are going to focus our attention on Serverless. If you have read my series on terraform, or you already have used Terraform, then you know how awesome it is for deploying infra in matter of minutes. If so, why learn another tool for the same ?</p>

<p>Well, the <a href="https://www.serverless.com/">serverless framework</a> has been created specifically for the creating serverless apps in as little time as possible. It abstracts away a lot of details and just a bunch of lines can create infrastructure that would otherwise take hundreds (if we were to write a cloudformation stack for the same). We will see what makes serverless so great for this use-case.</p>

<p class="notice">Just like terraform, serverless is cloud agnositic, so it supports multiple providers like AWS, GCP and Azure.</p>

<h2 id="setting-up">Setting up</h2>
<p class="notice--info">I recommend the official <a href="(https://www.serverless.com/framework/docs/getting-started)">page</a> for the setup and installation of serverless on your system.</p>

<blockquote>
  <p>Before starting, I just want to give a shout out to <strong>WSL (Windows Subsystem for Linux)</strong>. If you are a developer with windows machine, and do not currently use it, I highly recommend it as it will make your development experience a breeze.</p>
</blockquote>

<p>Once you have setup serverless on your machine, it is time to configure it.
To start using serverless on your local machine, you do not need to configure it if you already have AWS-CLI setup, as serverless will use the default profile to perform deployments.</p>

<p class="notice--info">While creating policies in production, always follow principal of least priveleges.</p>

<p>In case you have not configured AWS-CLI with a default user, then you perform the following steps -</p>
<ol>
  <li>Open AWS console, go to IAM, then Users and create new user called serverless.</li>
  <li>Attach AdministratorFullAccess policy to the user (to make things easy).</li>
  <li>Create Access Key and Secret, using <strong>Create Access Keys</strong> option for the user just created</li>
</ol>

<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Command to configure serverless </span>
serverless <span class="nt">--version</span>
serverless config credentials <span class="nt">--provider</span> aws <span class="nt">--key</span> yourKey <span class="nt">--secret</span> yourSecret
</code></pre></div></div>

<h2 id="test-setup">Test setup</h2>
<p>To test everything has been setup properly, we will quicky deploy a lambda function.
To create the starter code for this practice.</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Create a test project</span>
serverless create <span class="nt">--template</span> aws-python <span class="nt">--path</span> new_project <span class="nt">--name</span> testFunc

<span class="c"># This creates the project directory</span>
new_project
├── handler.py
└── serverless.yml
</code></pre></div></div>

<p>In the directory that has been created, if you remove the comments, you are left with <code class="language-plaintext highlighter-rouge">serverless.yml</code> as below -</p>
<div class="language-yml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Serverless.ynl</span>
<span class="na">service</span><span class="pi">:</span> <span class="s">testFunc</span>
<span class="na">frameworkVersion</span><span class="pi">:</span> <span class="s1">'</span><span class="s">3'</span>

<span class="na">provider</span><span class="pi">:</span>
  <span class="na">name</span><span class="pi">:</span> <span class="s">aws</span>
  <span class="na">runtime</span><span class="pi">:</span> <span class="s">python3.8</span>

<span class="na">functions</span><span class="pi">:</span>
  <span class="na">hello</span><span class="pi">:</span>
    <span class="na">handler</span><span class="pi">:</span> <span class="s">handler.hello</span>
</code></pre></div></div>

<p>Let’s quicky run the command <code class="language-plaintext highlighter-rouge">sls-deploy</code> and wait for the deployment to finish.</p>

<p><img src="/assets/images/collections/posts/2024-01-22-The-serverless-framework/sls-depl-1.png" alt="image-right" class="align-center" /></p>

<p>As you can see in the figure above, we were able to create the function as required. To remove this stack you can run <code class="language-plaintext highlighter-rouge">sls remove</code></p>

<p class="notice--success">Congratulation, and good job.</p>

<h2 id="invoking-the-function">Invoking the function</h2>
<p>When developing lambda functions, you may want to test the same. Having to open AWS Console defeats the purpose. So, the serverless framework provides us with a handy way to do the same.</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Invoke and log the output</span>
sls invoke <span class="nt">-f</span> hello <span class="nt">--log</span>

<span class="c"># View previous logs</span>
sls logs <span class="nt">-f</span> hello <span class="nt">--tail</span>
</code></pre></div></div>

<p>Output</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">$ </span>sls invoke <span class="nt">-f</span> hello <span class="nt">--log</span>
<span class="o">{</span>
    <span class="s2">"statusCode"</span>: 200,
    <span class="s2">"body"</span>: <span class="s2">"{</span><span class="se">\"</span><span class="s2">message</span><span class="se">\"</span><span class="s2">: </span><span class="se">\"</span><span class="s2">Go Serverless v1.0! Your function executed successfully!</span><span class="se">\"</span><span class="s2">, </span><span class="se">\"</span><span class="s2">input</span><span class="se">\"</span><span class="s2">: {}}"</span>
<span class="o">}</span>
<span class="nt">--------------------------------------------------------------------</span>
START
END Duration: 1.33 ms <span class="o">(</span>init: 130.95 ms<span class="o">)</span> Memory Used: 38 MB
</code></pre></div></div>

<h2 id="using-external-libraries">Using external libraries</h2>
<p>It may be required for you to package 3rd party python libraries. There are essentially 2 ways to do that -</p>
<ol>
  <li>Package them as a zip file and upload along with your code.</li>
  <li>Upload them to <a href="https://aws.amazon.com/blogs/compute/using-lambda-layers-to-simplify-your-development-process/">lambda layers</a>.<sup id="fnref:layers"><a href="#fn:layers" class="footnote" rel="footnote" role="doc-noteref">1</a></sup></li>
</ol>

<p>For both above, we will make use of a plugin called <a href="https://github.com/serverless/serverless-python-requirements">serverless-python-requirements</a>. You can install the same by running <code class="language-plaintext highlighter-rouge">sls install -n serverless-python-requirements</code>.</p>

<p>Make sure to add the below in serverless.yml file.</p>
<div class="language-yml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="na">plugins</span><span class="pi">:</span>
  <span class="pi">-</span> <span class="s">serverless-python-requirements</span>

<span class="c1"># How to use ZIP file</span>
<span class="na">custom</span><span class="pi">:</span>
  <span class="na">pythonRequirements</span><span class="pi">:</span>
    <span class="na">dockerizePip</span><span class="pi">:</span> <span class="kc">true</span>
    <span class="na">zip</span><span class="pi">:</span> <span class="kc">true</span>

<span class="c1"># How to use lambda layer</span>
<span class="na">custom</span><span class="pi">:</span>
  <span class="na">pythonRequirements</span><span class="pi">:</span>
    <span class="na">dockerizePip</span><span class="pi">:</span> <span class="kc">true</span>
    <span class="na">layer</span><span class="pi">:</span>
      <span class="na">name</span><span class="pi">:</span> <span class="s">PandasLayer</span>
</code></pre></div></div>

<p>In both approaches below, we will use a <code class="language-plaintext highlighter-rouge">requirements.txt</code> file where we mention the libraries to install such as <code class="language-plaintext highlighter-rouge">pandas==1.0.1</code>.
Serverless framework really names it super easy to be able to deploy third party libraries as layers or as zipfile.</p>

<p>In case of zip file, there is an additional step to run <code class="language-plaintext highlighter-rouge">import unzip_requirements</code> at top of script for the zipped libraries to become available for use.</p>

<h1 id="footnotes">Footnotes</h1>

<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:layers">
      <p>Lambda layers allow you to upload modules that can be shared across multiple lambda functions. <a href="#fnref:layers" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Pulkit Kapoor</name><email>pulkit42041@gmail.com</email></author><category term="Infra as code" /><category term="iac" /><category term="serverless" /><category term="aws" /><summary type="html"><![CDATA[What is serverless framework and how to use it for infra deployment on AWS.]]></summary></entry><entry><title type="html">AWS S3 Multi-Part Uploads</title><link href="https://www.pulkitkapoor.com/aws/S3-Multipart-upload/" rel="alternate" type="text/html" title="AWS S3 Multi-Part Uploads" /><published>2024-01-12T00:00:00+00:00</published><updated>2024-01-12T00:00:00+00:00</updated><id>https://www.pulkitkapoor.com/aws/S3-Multipart-upload</id><content type="html" xml:base="https://www.pulkitkapoor.com/aws/S3-Multipart-upload/"><![CDATA[<h2 id="understanding-multi-part-uploads">Understanding multi-part uploads</h2>
<p>Once you have created a bucket on AWS S3<sup id="fnref:aws-s3"><a href="#fn:aws-s3" class="footnote" rel="footnote" role="doc-noteref">1</a></sup>, you may want to transfer some data. It may so happen often that the data you want to transfer is very large, order of GB or even TBs.</p>

<p class="notice--info">AWS S3 allow you to create objects of upto 5TB in size, but the maximum you can upload via S3 put API is 5GB.</p>

<p>To allow you to upload bigger files, there is a concept called multi-part upload. This essentially means, we break the file we want to upload, then upload individual parts and allow S3 service to reassemble this to create the target file in the cloud. This makes the upload process resumable in cause of faults, and also faster as parts can be uploaded parallely.</p>

<h2 id="rules-rules-and-rules">Rules, rules and rules</h2>
<p>Before diving into the code, there are some rules to remember when using the S3 multi-part upload API -</p>
<ol>
  <li>A file can be split into a maximum of 10,000 parts.</li>
  <li>Each part needs to have a size between 5MB and 100MB.</li>
</ol>

<p class="notice--warning"><strong>Tip:</strong> You can use lifecycle policies to abort multipart uploads that take too much time</p>

<h2 id="steps-for-a-multi-part-upload">Steps for a multi-part upload</h2>
<p>Broadly speaking, there are three basic steps to perform the upload -</p>
<ul>
  <li>Register you multi-part upload via the <code class="language-plaintext highlighter-rouge">CreateMultipartUpload</code> API, which gives you an <strong>UploadId</strong> in its response.</li>
  <li>Then you upload individual parts using the <code class="language-plaintext highlighter-rouge">UploadPart</code> API. Each upload responds back with an <strong>ETag</strong>.</li>
</ul>

<p>Finally, when all uploads are finished, you make a call to <code class="language-plaintext highlighter-rouge">CompleteMultipartUpload</code> which requires the <strong>UploadID, PartNumbers and ETags</strong> to consolidate the file on cloud. Interesting thing to note is that it is possible to overwrite the individual parts when the uploads are being performed, this gives writer the ability to apply modifications to a very big file while the upload is in progress.</p>

<h2 id="hands-on">Hands-on</h2>
<h5 id="get-uploadid">Get UploadID</h5>
<p>We will use the <code class="language-plaintext highlighter-rouge">create_multipart_upload</code> function call. 
For this aspect, we will create a handy function.</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">start_upload</span><span class="p">(</span><span class="n">bucket</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
    <span class="sh">"</span><span class="s">Returns the UploadId for multi-part upload</span><span class="sh">"</span>
    <span class="n">client</span> <span class="o">=</span> <span class="n">boto3</span><span class="p">.</span><span class="nf">client</span><span class="p">(</span><span class="sh">"</span><span class="s">s3</span><span class="sh">"</span><span class="p">)</span>
    <span class="n">response</span> <span class="o">=</span> <span class="n">client</span><span class="p">.</span><span class="nf">create_multipart_upload</span><span class="p">(</span>
        <span class="n">Bucket</span> <span class="o">=</span> <span class="n">bucket</span><span class="p">,</span>
        <span class="n">Key</span> <span class="o">=</span> <span class="n">key</span>
    <span class="p">)</span>
    <span class="k">return</span> <span class="n">response</span><span class="p">[</span><span class="sh">"</span><span class="s">UploadId</span><span class="sh">"</span><span class="p">]</span>
</code></pre></div></div>
<p>The function allows us to supply the bucket, key and get a UploadID for our upload process.</p>

<h5 id="upload-one-part">Upload one Part</h5>
<p>We need a function to be able to upload one part for our upload. Later, we can use a multi-threading approach to upload in parallel.</p>
<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">upload_part</span><span class="p">(</span><span class="n">bucket</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">part_num</span><span class="p">,</span> <span class="n">upload_id</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
    <span class="sh">"</span><span class="s">Upload a part to S3</span><span class="sh">"</span>
    <span class="n">client</span> <span class="o">=</span> <span class="n">boto3</span><span class="p">.</span><span class="nf">client</span><span class="p">(</span><span class="sh">"</span><span class="s">s3</span><span class="sh">"</span><span class="p">)</span>
    <span class="n">response</span> <span class="o">=</span> <span class="n">client</span><span class="p">.</span><span class="nf">upload_part</span><span class="p">(</span>
        <span class="n">Bucket</span> <span class="o">=</span> <span class="n">bucket</span><span class="p">,</span>
        <span class="n">Key</span> <span class="o">=</span> <span class="n">key</span><span class="p">,</span>
        <span class="n">PartNumber</span> <span class="o">=</span> <span class="n">part_num</span><span class="p">,</span>
        <span class="n">UploadId</span> <span class="o">=</span> <span class="n">upload_id</span><span class="p">,</span>
        <span class="n">Body</span> <span class="o">=</span> <span class="n">data</span>
    <span class="p">)</span>
    <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Uploaded part </span><span class="si">{</span><span class="n">part_num</span><span class="si">}</span><span class="s"> and received ETag </span><span class="si">{</span><span class="n">response</span><span class="p">[</span><span class="sh">'</span><span class="s">ETag</span><span class="sh">'</span><span class="p">]</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
    <span class="k">return</span> <span class="p">{</span>
        <span class="sh">'</span><span class="s">PartNumber</span><span class="sh">'</span><span class="p">:</span> <span class="n">part_num</span><span class="p">,</span>
        <span class="sh">'</span><span class="s">ETag</span><span class="sh">'</span><span class="p">:</span> <span class="n">response</span><span class="p">[</span><span class="sh">'</span><span class="s">ETag</span><span class="sh">'</span><span class="p">]</span>
    <span class="p">}</span>
</code></pre></div></div>
<p>As you may notice, all function calls are self-explanatory. When we need to upload a specific part, we need to tell S3, what UploadID is it realted to, where it sits in the upload sequence, and what data are we uploading in this part.</p>

<h5 id="putting-it-together">Putting it together</h5>
<p>To make everything work, we call the first funtion to get UploadID and use concurrent futures to upload multiple parts in parallel.
Concurrent futures<sup id="fnref:1"><a href="#fn:1" class="footnote" rel="footnote" role="doc-noteref">2</a></sup> is a very handy library to quickly write code running on multiple threads or processes.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1"># Start upload
</span><span class="n">upload_id</span> <span class="o">=</span> <span class="nf">start_upload</span><span class="p">(</span><span class="n">bucket</span><span class="p">,</span> <span class="n">key</span><span class="p">)</span>
<span class="c1"># Upload parts
</span><span class="n">futures</span> <span class="o">=</span> <span class="p">[]</span>
<span class="k">with</span> <span class="nc">ProcessPoolExecutor</span><span class="p">(</span><span class="n">max_workers</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span> <span class="k">as</span> <span class="n">executor</span><span class="p">:</span>
    <span class="k">with</span> <span class="nf">open</span><span class="p">(</span><span class="n">file_name</span><span class="p">,</span> <span class="sh">"</span><span class="s">rb</span><span class="sh">"</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
        <span class="n">i</span> <span class="o">=</span> <span class="mi">1</span>
        <span class="n">chunk</span> <span class="o">=</span> <span class="n">f</span><span class="p">.</span><span class="nf">read</span><span class="p">(</span><span class="n">chunk_size_bytes</span><span class="p">)</span>
        <span class="k">while</span> <span class="nf">len</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span>
            <span class="n">future</span> <span class="o">=</span> <span class="n">executor</span><span class="p">.</span><span class="nf">submit</span><span class="p">(</span><span class="n">upload_part</span><span class="p">,</span> <span class="n">bucket</span><span class="o">=</span><span class="n">bucket</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">key</span><span class="p">,</span> <span class="n">part_num</span><span class="o">=</span><span class="n">i</span><span class="p">,</span> <span class="n">upload_id</span><span class="o">=</span><span class="n">upload_id</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">chunk</span><span class="p">)</span>
            <span class="n">futures</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="n">future</span><span class="p">)</span>
            <span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
            <span class="n">chunk</span> <span class="o">=</span> <span class="n">f</span><span class="p">.</span><span class="nf">read</span><span class="p">(</span><span class="n">chunk_size_bytes</span><span class="p">)</span>
    
<span class="n">results</span> <span class="o">=</span> <span class="p">[]</span>    
<span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="nf">as_completed</span><span class="p">(</span><span class="n">futures</span><span class="p">):</span>
    <span class="n">results</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="n">f</span><span class="p">.</span><span class="nf">result</span><span class="p">())</span>
    
<span class="c1"># Finalize the upload
</span><span class="n">response</span> <span class="o">=</span> <span class="n">boto3</span><span class="p">.</span><span class="nf">client</span><span class="p">(</span><span class="sh">"</span><span class="s">s3</span><span class="sh">"</span><span class="p">).</span><span class="nf">complete_multipart_upload</span><span class="p">(</span>
    <span class="n">Bucket</span> <span class="o">=</span> <span class="n">bucket</span><span class="p">,</span>
    <span class="n">Key</span> <span class="o">=</span> <span class="n">key</span><span class="p">,</span>
    <span class="n">UploadId</span> <span class="o">=</span> <span class="n">upload_id</span><span class="p">,</span>
    <span class="n">MultipartUpload</span> <span class="o">=</span> <span class="p">{</span>
        <span class="sh">'</span><span class="s">Parts</span><span class="sh">'</span><span class="p">:</span> <span class="nf">sorted</span><span class="p">(</span><span class="n">results</span><span class="p">,</span> <span class="n">key</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">e</span><span class="p">:</span> <span class="n">e</span><span class="p">[</span><span class="sh">"</span><span class="s">PartNumber</span><span class="sh">"</span><span class="p">])</span>
    <span class="p">}</span>
<span class="p">)</span>
</code></pre></div></div>

<p>Finally, to test the program, you need to create a test bucket and a test file which is large enough for multi-part upload test.</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Create test bucket</span>
aws s3 mb test-3224-random <span class="nt">--region</span> us-east-1

<span class="c"># Run program</span>
python3 ./upload.py <span class="nt">--file</span> app.msi <span class="nt">--bucket</span> test-3224-random <span class="nt">--key</span> app.msi <span class="nt">--chunk_size</span> 6
</code></pre></div></div>

<blockquote>
  <p>Thats it, and it was that simple. Do leave comments for discussion and share if you like it!!</p>
</blockquote>

<h2 id="solution-code">Solution code</h2>
<p class="notice--info">In case you are missing part of the puzzle, below is the entire code for this exercise.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="n">boto3</span>
<span class="kn">import</span> <span class="n">argparse</span>
<span class="kn">import</span> <span class="n">json</span>
<span class="kn">import</span> <span class="n">time</span>
<span class="kn">from</span> <span class="n">concurrent.futures</span> <span class="kn">import</span> <span class="n">ProcessPoolExecutor</span><span class="p">,</span> <span class="n">wait</span><span class="p">,</span> <span class="n">ALL_COMPLETED</span><span class="p">,</span> <span class="n">as_completed</span>


<span class="k">def</span> <span class="nf">start_upload</span><span class="p">(</span><span class="n">bucket</span><span class="p">,</span> <span class="n">key</span><span class="p">):</span>
    <span class="sh">"</span><span class="s">Returns the UploadId for multi-part upload</span><span class="sh">"</span>
    <span class="n">client</span> <span class="o">=</span> <span class="n">boto3</span><span class="p">.</span><span class="nf">client</span><span class="p">(</span><span class="sh">"</span><span class="s">s3</span><span class="sh">"</span><span class="p">)</span>
    <span class="n">response</span> <span class="o">=</span> <span class="n">client</span><span class="p">.</span><span class="nf">create_multipart_upload</span><span class="p">(</span>
        <span class="n">Bucket</span> <span class="o">=</span> <span class="n">bucket</span><span class="p">,</span>
        <span class="n">Key</span> <span class="o">=</span> <span class="n">key</span>
    <span class="p">)</span>
    <span class="k">return</span> <span class="n">response</span><span class="p">[</span><span class="sh">"</span><span class="s">UploadId</span><span class="sh">"</span><span class="p">]</span>

<span class="k">def</span> <span class="nf">upload_part</span><span class="p">(</span><span class="n">bucket</span><span class="p">,</span> <span class="n">key</span><span class="p">,</span> <span class="n">part_num</span><span class="p">,</span> <span class="n">upload_id</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
    <span class="sh">"</span><span class="s">Upload a part to S3</span><span class="sh">"</span>
    <span class="n">client</span> <span class="o">=</span> <span class="n">boto3</span><span class="p">.</span><span class="nf">client</span><span class="p">(</span><span class="sh">"</span><span class="s">s3</span><span class="sh">"</span><span class="p">)</span>
    <span class="n">response</span> <span class="o">=</span> <span class="n">client</span><span class="p">.</span><span class="nf">upload_part</span><span class="p">(</span>
        <span class="n">Bucket</span> <span class="o">=</span> <span class="n">bucket</span><span class="p">,</span>
        <span class="n">Key</span> <span class="o">=</span> <span class="n">key</span><span class="p">,</span>
        <span class="n">PartNumber</span> <span class="o">=</span> <span class="n">part_num</span><span class="p">,</span>
        <span class="n">UploadId</span> <span class="o">=</span> <span class="n">upload_id</span><span class="p">,</span>
        <span class="n">Body</span> <span class="o">=</span> <span class="n">data</span>
    <span class="p">)</span>
    <span class="nf">print</span><span class="p">(</span><span class="sa">f</span><span class="sh">"</span><span class="s">Uploaded part </span><span class="si">{</span><span class="n">part_num</span><span class="si">}</span><span class="s"> and received ETag </span><span class="si">{</span><span class="n">response</span><span class="p">[</span><span class="sh">'</span><span class="s">ETag</span><span class="sh">'</span><span class="p">]</span><span class="si">}</span><span class="sh">"</span><span class="p">)</span>
    <span class="k">return</span> <span class="p">{</span>
        <span class="sh">'</span><span class="s">PartNumber</span><span class="sh">'</span><span class="p">:</span> <span class="n">part_num</span><span class="p">,</span>
        <span class="sh">'</span><span class="s">ETag</span><span class="sh">'</span><span class="p">:</span> <span class="n">response</span><span class="p">[</span><span class="sh">'</span><span class="s">ETag</span><span class="sh">'</span><span class="p">]</span>
    <span class="p">}</span>

<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="sh">'</span><span class="s">__main__</span><span class="sh">'</span><span class="p">:</span>
    <span class="n">MB</span> <span class="o">=</span> <span class="mi">1024</span> <span class="o">*</span> <span class="mi">1024</span> 
    <span class="c1"># Read the file name
</span>    <span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="p">.</span><span class="nc">ArgumentParser</span><span class="p">()</span>
    <span class="n">parser</span><span class="p">.</span><span class="nf">add_argument</span><span class="p">(</span><span class="sh">"</span><span class="s">--file</span><span class="sh">"</span><span class="p">,</span> <span class="n">required</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
    <span class="n">parser</span><span class="p">.</span><span class="nf">add_argument</span><span class="p">(</span><span class="sh">"</span><span class="s">--bucket</span><span class="sh">"</span><span class="p">,</span> <span class="n">required</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
    <span class="n">parser</span><span class="p">.</span><span class="nf">add_argument</span><span class="p">(</span><span class="sh">"</span><span class="s">--key</span><span class="sh">"</span><span class="p">,</span> <span class="n">required</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
    <span class="n">parser</span><span class="p">.</span><span class="nf">add_argument</span><span class="p">(</span><span class="sh">"</span><span class="s">--chunk_size</span><span class="sh">"</span><span class="p">,</span> <span class="n">required</span><span class="o">=</span><span class="bp">True</span><span class="p">,</span> <span class="nb">help</span> <span class="o">=</span> <span class="sh">"</span><span class="s">Size of individual parts in MB.</span><span class="sh">"</span><span class="p">)</span>
    <span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="p">.</span><span class="nf">parse_args</span><span class="p">()</span>
    <span class="c1"># Get args
</span>    <span class="n">file_name</span> <span class="o">=</span> <span class="n">args</span><span class="p">.</span><span class="nb">file</span>
    <span class="n">bucket</span> <span class="o">=</span> <span class="n">args</span><span class="p">.</span><span class="n">bucket</span>
    <span class="n">key</span> <span class="o">=</span> <span class="n">args</span><span class="p">.</span><span class="n">key</span>
    <span class="n">chunk_size_bytes</span> <span class="o">=</span> <span class="nf">int</span><span class="p">(</span><span class="n">args</span><span class="p">.</span><span class="n">chunk_size</span><span class="p">)</span> <span class="o">*</span> <span class="n">MB</span>
    <span class="c1"># Start upload
</span>    <span class="n">upload_id</span> <span class="o">=</span> <span class="nf">start_upload</span><span class="p">(</span><span class="n">bucket</span><span class="p">,</span> <span class="n">key</span><span class="p">)</span>
    <span class="c1"># Upload parts
</span>    <span class="n">futures</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">with</span> <span class="nc">ProcessPoolExecutor</span><span class="p">(</span><span class="n">max_workers</span><span class="o">=</span><span class="mi">10</span><span class="p">)</span> <span class="k">as</span> <span class="n">executor</span><span class="p">:</span>
        <span class="k">with</span> <span class="nf">open</span><span class="p">(</span><span class="n">file_name</span><span class="p">,</span> <span class="sh">"</span><span class="s">rb</span><span class="sh">"</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>
            <span class="n">i</span> <span class="o">=</span> <span class="mi">1</span>
            <span class="n">chunk</span> <span class="o">=</span> <span class="n">f</span><span class="p">.</span><span class="nf">read</span><span class="p">(</span><span class="n">chunk_size_bytes</span><span class="p">)</span>
            <span class="k">while</span> <span class="nf">len</span><span class="p">(</span><span class="n">chunk</span><span class="p">)</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">:</span>
                <span class="n">future</span> <span class="o">=</span> <span class="n">executor</span><span class="p">.</span><span class="nf">submit</span><span class="p">(</span><span class="n">upload_part</span><span class="p">,</span> <span class="n">bucket</span><span class="o">=</span><span class="n">bucket</span><span class="p">,</span> <span class="n">key</span><span class="o">=</span><span class="n">key</span><span class="p">,</span> <span class="n">part_num</span><span class="o">=</span><span class="n">i</span><span class="p">,</span> <span class="n">upload_id</span><span class="o">=</span><span class="n">upload_id</span><span class="p">,</span> <span class="n">data</span><span class="o">=</span><span class="n">chunk</span><span class="p">)</span>
                <span class="n">futures</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="n">future</span><span class="p">)</span>
                <span class="n">i</span> <span class="o">+=</span> <span class="mi">1</span>
                <span class="n">chunk</span> <span class="o">=</span> <span class="n">f</span><span class="p">.</span><span class="nf">read</span><span class="p">(</span><span class="n">chunk_size_bytes</span><span class="p">)</span>
        
    <span class="n">results</span> <span class="o">=</span> <span class="p">[]</span>    
    <span class="k">for</span> <span class="n">f</span> <span class="ow">in</span> <span class="nf">as_completed</span><span class="p">(</span><span class="n">futures</span><span class="p">):</span>
        <span class="n">results</span><span class="p">.</span><span class="nf">append</span><span class="p">(</span><span class="n">f</span><span class="p">.</span><span class="nf">result</span><span class="p">())</span>
        
    <span class="c1"># Finalize the upload
</span>    <span class="n">response</span> <span class="o">=</span> <span class="n">boto3</span><span class="p">.</span><span class="nf">client</span><span class="p">(</span><span class="sh">"</span><span class="s">s3</span><span class="sh">"</span><span class="p">).</span><span class="nf">complete_multipart_upload</span><span class="p">(</span>
        <span class="n">Bucket</span> <span class="o">=</span> <span class="n">bucket</span><span class="p">,</span>
        <span class="n">Key</span> <span class="o">=</span> <span class="n">key</span><span class="p">,</span>
        <span class="n">UploadId</span> <span class="o">=</span> <span class="n">upload_id</span><span class="p">,</span>
        <span class="n">MultipartUpload</span> <span class="o">=</span> <span class="p">{</span>
            <span class="sh">'</span><span class="s">Parts</span><span class="sh">'</span><span class="p">:</span> <span class="nf">sorted</span><span class="p">(</span><span class="n">results</span><span class="p">,</span> <span class="n">key</span> <span class="o">=</span> <span class="k">lambda</span> <span class="n">e</span><span class="p">:</span> <span class="n">e</span><span class="p">[</span><span class="sh">"</span><span class="s">PartNumber</span><span class="sh">"</span><span class="p">])</span>
        <span class="p">}</span>
    <span class="p">)</span>
    
    <span class="nf">print</span><span class="p">(</span><span class="n">json</span><span class="p">.</span><span class="nf">dumps</span><span class="p">(</span><span class="n">response</span><span class="p">))</span>
</code></pre></div></div>

<h5 id="footnotes">Footnotes</h5>

<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:aws-s3">
      <p>https://www.google.com <a href="#fnref:aws-s3" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:1">
      <p>https://stackoverflow.com/questions/49358473/how-to-use-concurrent-futures-in-python <a href="#fnref:1" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>Pulkit Kapoor</name><email>pulkit42041@gmail.com</email></author><category term="aws" /><category term="awss3" /><category term="upload" /><category term="aws" /><category term="storage" /><category term="dataengineering" /><summary type="html"><![CDATA[How to upload large files to S3 using multi-part uploads.]]></summary></entry><entry><title type="html">Terraform dynamic blocks</title><link href="https://www.pulkitkapoor.com/infra%20as%20code/Dynamic-blocks-in-terraform/" rel="alternate" type="text/html" title="Terraform dynamic blocks" /><published>2023-12-22T00:00:00+00:00</published><updated>2023-12-22T00:00:00+00:00</updated><id>https://www.pulkitkapoor.com/infra%20as%20code/Dynamic-blocks-in-terraform</id><content type="html" xml:base="https://www.pulkitkapoor.com/infra%20as%20code/Dynamic-blocks-in-terraform/"><![CDATA[<h2 id="introduction">Introduction</h2>
<p>In this part I am going to introduce you to some advanced features of terraform. We will understand the use of <code class="language-plaintext highlighter-rouge">variable types</code>, constructs like <code class="language-plaintext highlighter-rouge">for_each</code> and use <code class="language-plaintext highlighter-rouge">dynamic</code> blocks to write terraform code that is not verbose.</p>

<h2 id="introduction-to-variables">Introduction to <code class="language-plaintext highlighter-rouge">variables</code></h2>
<p>Just like other programming languages, <strong>HCL</strong> has the construct of data-types, and we can create variables using them. For example, we now know that modules or even resource block accept arbitary inputs from user. The best practice is to supply these variables by creating a <code class="language-plaintext highlighter-rouge">terraform.tfvars</code> file which is used by terraform to instantiate the variables to the user supplied values.</p>

<p>We will start with a simple example.</p>

<h3 id="example-usage">Example usage</h3>
<p>In this example, we will use terraform to create a S3 bucket. We will need 3 files, <code class="language-plaintext highlighter-rouge">main.tf</code>, <code class="language-plaintext highlighter-rouge">variables.tf</code> and <code class="language-plaintext highlighter-rouge">.tfvars</code> inside the demo-project directory.</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nb">.</span>
├── backend.tf
├── main.tf
├── terraform.tfvars
└── variables.tf
</code></pre></div></div>

<h4 id="maintf">Main.tf</h4>
<p>This file houses the code to create our <code class="language-plaintext highlighter-rouge">s3</code> resource. As you can see, we have used variables using the syntax <code class="language-plaintext highlighter-rouge">var.variableName</code> to use the value of variable in resource and provider blocks.</p>
<div class="language-hcl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">provider</span> <span class="s2">"aws"</span> <span class="p">{</span>
  <span class="nx">profile</span> <span class="o">=</span> <span class="nx">var</span><span class="p">.</span><span class="nx">profile</span>
  <span class="nx">region</span>  <span class="o">=</span> <span class="nx">var</span><span class="p">.</span><span class="nx">region</span>
<span class="p">}</span>

<span class="nx">resource</span> <span class="s2">"aws_s3_bucket"</span> <span class="s2">"testbucket"</span> <span class="p">{</span>
  <span class="nx">bucket</span> <span class="o">=</span> <span class="nx">var</span><span class="p">.</span><span class="nx">bucket_name</span>
<span class="p">}</span>
</code></pre></div></div>

<h4 id="variablestf">Variables.tf</h4>
<p>This is the file where we are going to declare the variables that we need to use in code.</p>
<div class="language-hcl highlighter-rouge"><div class="highlight"><pre class="highlight"><code>
<span class="nx">variable</span> <span class="s2">"region"</span> <span class="p">{</span>
  <span class="nx">type</span>    <span class="o">=</span> <span class="nx">string</span>
  <span class="nx">default</span> <span class="o">=</span> <span class="s2">"us-east-1"</span>
<span class="p">}</span>

<span class="nx">variable</span> <span class="s2">"profile"</span> <span class="p">{</span>
  <span class="nx">type</span>    <span class="o">=</span> <span class="nx">string</span>
  <span class="nx">default</span> <span class="o">=</span> <span class="s2">"profile-name-to-use"</span>
<span class="p">}</span>

<span class="nx">variable</span> <span class="s2">"bucket_name"</span> <span class="p">{</span>
  <span class="nx">type</span>    <span class="o">=</span> <span class="nx">string</span>
  <span class="nx">description</span> <span class="o">=</span> <span class="s2">"Name of S3 bucket to create"</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Along with basic parameters, you can use other parameters like sensitive, and add condition checks to validate the variables passed by user.</p>

<h4 id="terraformtfvars">Terraform.tfvars</h4>
<p>Finally, we can supply the value of variables using the <code class="language-plaintext highlighter-rouge">.tfvars</code> file.</p>
<div class="language-hcl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">bucket_name</span> <span class="o">=</span> <span class="s2">"test_bucket"</span>
</code></pre></div></div>

<p>Running the program is quite simple. I used the below sequence in every terraform project</p>
<div class="language-bash highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c"># Initialize the backend and provider</span>
terraform init

<span class="c"># Format the code</span>
terraform <span class="nb">fmt</span>

<span class="c"># Validate for syntax errors</span>
terraform validate

<span class="c"># Create plan</span>
terraform plan

<span class="c"># Apply the changes</span>
terraform apply

<span class="c"># Decommission </span>
terrafrom destroy
</code></pre></div></div>

<h2 id="types-of-variables">Types of <code class="language-plaintext highlighter-rouge">variables</code></h2>
<p>There are two types or variables in terraform -</p>
<ul>
  <li>Primitives - String, Boolean, Numeric</li>
  <li>Complex - Set, Map, Object, Tuple, List, Any</li>
</ul>

<p>You have already seen example of <strong>string</strong> variable when we introduced the idea of types in HCL. Let’s look at a complex variable declaration to make the idea more concrete.</p>

<div class="language-hcl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">variable</span> <span class="s2">"igress_params"</span> <span class="p">{</span>
  <span class="nx">type</span> <span class="o">=</span> <span class="nx">map</span><span class="p">(</span><span class="nx">object</span><span class="p">({</span>
    <span class="nx">port</span>  <span class="o">=</span> <span class="nx">number</span>
    <span class="nx">proto</span> <span class="o">=</span> <span class="nx">string</span>
    <span class="nx">cidr</span>  <span class="o">=</span> <span class="nx">list</span><span class="err">(</span><span class="nx">string</span><span class="p">)</span>
  <span class="p">}))</span>
  <span class="nx">default</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s2">"rule1"</span> <span class="p">=</span> <span class="p">{</span>
      <span class="nx">port</span>  <span class="o">=</span> <span class="mi">22</span>
      <span class="nx">proto</span> <span class="o">=</span> <span class="s2">"tcp"</span>
      <span class="nx">cidr</span>  <span class="o">=</span> <span class="p">[</span><span class="s2">"0.0.0.0/0"</span><span class="p">]</span>
    <span class="p">},</span>
    <span class="s2">"rule2"</span> <span class="p">=</span> <span class="p">{</span>
      <span class="nx">port</span>  <span class="o">=</span> <span class="mi">80</span>
      <span class="nx">proto</span> <span class="o">=</span> <span class="s2">"tcp"</span>
      <span class="nx">cidr</span>  <span class="o">=</span> <span class="p">[</span><span class="s2">"1.2.3.4/32"</span><span class="p">]</span>
    <span class="p">}</span>
  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>In the above block of code, we create a variable of type <code class="language-plaintext highlighter-rouge">map(object)</code> and use it to carry all the rules for a AWS security group that we can use later when creating VPC and Security Group.</p>

<h2 id="introduction-to-for_each">Introduction to <code class="language-plaintext highlighter-rouge">for_each</code></h2>
<p>The <code class="language-plaintext highlighter-rouge">for_each</code> blocks are very good utility blocks when you want to create multiple resources of same type but different variable values. Such as, you have to create three S3 buckets for dev, uat and prod.</p>

<p>Below is an example use of how to use these blocks.</p>

<div class="language-hcl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">provider</span> <span class="s2">"aws"</span> <span class="p">{</span>
  <span class="nx">profile</span> <span class="o">=</span> <span class="s2">"aws-profile-to-use"</span>
  <span class="nx">region</span>  <span class="o">=</span> <span class="s2">"us-east-1"</span>
<span class="p">}</span>

<span class="nx">variable</span> <span class="s2">"s3_buckets"</span> <span class="p">{</span>
  <span class="nx">type</span>        <span class="o">=</span> <span class="nx">set</span><span class="p">(</span><span class="nx">string</span><span class="p">)</span>
  <span class="nx">description</span> <span class="o">=</span> <span class="s2">"Name of S3 buckets to create"</span>
  <span class="nx">default</span>     <span class="o">=</span> <span class="p">[</span><span class="s2">"test-dev"</span><span class="p">,</span> <span class="s2">"test-uat"</span><span class="p">,</span> <span class="s2">"test-prod"</span><span class="p">]</span>
<span class="p">}</span>

<span class="nx">resource</span> <span class="s2">"aws_s3_bucket"</span> <span class="s2">"testbucket"</span> <span class="p">{</span>
  <span class="nx">for_each</span> <span class="o">=</span> <span class="nx">var</span><span class="p">.</span><span class="nx">s3_buckets</span>
  <span class="nx">bucket</span>   <span class="o">=</span> <span class="nx">each</span><span class="p">.</span><span class="nx">value</span>
<span class="p">}</span>
</code></pre></div></div>

<p>The above code iterates through each value of the <code class="language-plaintext highlighter-rouge">s3_buckets</code> variable and create 3 buckets.</p>

<h2 id="dynamic-keyword">Dynamic <code class="language-plaintext highlighter-rouge">keyword</code></h2>
<p>When creating a VPC followed by a security group, we often need to specify the inbound and outbound rules. It is often the case that the list of these rules and be length and hence not easy to maintain. Example of defining a security group without dynamic keyword.</p>

<div class="language-hcl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">resource</span> <span class="s2">"aws_security_group"</span> <span class="s2">"my-sg"</span> <span class="p">{</span>
  <span class="nx">vpc_id</span> <span class="o">=</span> <span class="nx">aws_vpc</span><span class="p">.</span><span class="nx">my-vpc</span><span class="p">.</span><span class="nx">id</span>

  <span class="nx">ingress</span> <span class="p">{</span>
    <span class="nx">from_port</span>   <span class="o">=</span> <span class="mi">80</span>
    <span class="nx">to_port</span>     <span class="o">=</span> <span class="mi">80</span>
    <span class="nx">protocol</span>    <span class="o">=</span> <span class="s2">"tcp"</span>
    <span class="nx">cidr_blocks</span> <span class="o">=</span> <span class="p">[</span><span class="s2">"0.0.0.0/0"</span><span class="p">]</span>
  <span class="p">}</span>

  <span class="nx">ingress</span> <span class="p">{</span>
    <span class="nx">from_port</span>   <span class="o">=</span> <span class="mi">22</span>
    <span class="nx">to_port</span>     <span class="o">=</span> <span class="mi">22</span>
    <span class="nx">protocol</span>    <span class="o">=</span> <span class="s2">"tcp"</span>
    <span class="nx">cidr_blocks</span> <span class="o">=</span> <span class="p">[</span><span class="s2">"0.0.0.0/0"</span><span class="p">]</span>
  <span class="p">}</span>
</code></pre></div></div>

<p>As you can see, this approach is very verbose, plus to add to this issue the rules are intermingled with the intra code. Whenever possible, the best practice is the seperate variable like structures from actual logic.</p>

<p>Below is how we achieve the same using dynamic keyword.</p>

<div class="language-hcl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nx">variable</span> <span class="s2">"igress_params"</span> <span class="p">{</span>
  <span class="nx">type</span> <span class="o">=</span> <span class="nx">map</span><span class="p">(</span><span class="nx">object</span><span class="p">({</span>
    <span class="nx">port</span>  <span class="o">=</span> <span class="nx">number</span>
    <span class="nx">proto</span> <span class="o">=</span> <span class="nx">string</span>
    <span class="nx">cidr</span>  <span class="o">=</span> <span class="nx">list</span><span class="err">(</span><span class="nx">string</span><span class="p">)</span>
  <span class="p">}))</span>
  <span class="nx">default</span> <span class="o">=</span> <span class="p">{</span>
    <span class="s2">"rule1"</span> <span class="p">=</span> <span class="p">{</span>
      <span class="nx">port</span>  <span class="o">=</span> <span class="mi">22</span>
      <span class="nx">proto</span> <span class="o">=</span> <span class="s2">"tcp"</span>
      <span class="nx">cidr</span>  <span class="o">=</span> <span class="p">[</span><span class="s2">"0.0.0.0/0"</span><span class="p">]</span>
    <span class="p">},</span>
    <span class="s2">"rule2"</span> <span class="p">=</span> <span class="p">{</span>
      <span class="nx">port</span>  <span class="o">=</span> <span class="mi">80</span>
      <span class="nx">proto</span> <span class="o">=</span> <span class="s2">"tcp"</span>
      <span class="nx">cidr</span>  <span class="o">=</span> <span class="p">[</span><span class="s2">"1.2.3.4/32"</span><span class="p">]</span>
    <span class="p">}</span>
  <span class="p">}</span>
<span class="p">}</span>

<span class="nx">resource</span> <span class="s2">"aws_vpc"</span> <span class="s2">"my-vpc"</span> <span class="p">{</span>
  <span class="nx">cidr_block</span> <span class="o">=</span> <span class="s2">"10.0.0.0/16"</span>
<span class="p">}</span>

<span class="nx">resource</span> <span class="s2">"aws_security_group"</span> <span class="s2">"my-sg"</span> <span class="p">{</span>
  <span class="nx">vpc_id</span> <span class="o">=</span> <span class="nx">aws_vpc</span><span class="p">.</span><span class="nx">my-vpc</span><span class="p">.</span><span class="nx">id</span>

  <span class="nx">egress</span> <span class="p">{</span>
    <span class="nx">from_port</span>   <span class="o">=</span> <span class="mi">0</span>
    <span class="nx">to_port</span>     <span class="o">=</span> <span class="mi">0</span>
    <span class="nx">protocol</span>    <span class="o">=</span> <span class="s2">"-1"</span>
    <span class="nx">cidr_blocks</span> <span class="o">=</span> <span class="p">[</span><span class="s2">"0.0.0.0/0"</span><span class="p">]</span>
  <span class="p">}</span>

  <span class="nx">dynamic</span> <span class="s2">"ingress"</span> <span class="p">{</span>
    <span class="nx">for_each</span> <span class="o">=</span> <span class="nx">var</span><span class="p">.</span><span class="nx">igress_params</span>

    <span class="nx">content</span> <span class="p">{</span>
      <span class="nx">from_port</span>   <span class="o">=</span> <span class="nx">ingress</span><span class="p">.</span><span class="nx">value</span><span class="p">[</span><span class="s2">"port"</span><span class="p">]</span>
      <span class="nx">to_port</span>     <span class="o">=</span> <span class="nx">ingress</span><span class="p">.</span><span class="nx">value</span><span class="p">[</span><span class="s2">"port"</span><span class="p">]</span>
      <span class="nx">protocol</span>    <span class="o">=</span> <span class="nx">ingress</span><span class="p">.</span><span class="nx">value</span><span class="p">[</span><span class="s2">"proto"</span><span class="p">]</span>
      <span class="nx">cidr_blocks</span> <span class="o">=</span> <span class="nx">ingress</span><span class="p">.</span><span class="nx">value</span><span class="p">[</span><span class="s2">"cidr"</span><span class="p">]</span>
    <span class="p">}</span>

  <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Using the <strong>dynamic</strong> block, terraform will create multiple ingress blocks while iterating through the list of values.</p>]]></content><author><name>Pulkit Kapoor</name><email>pulkit42041@gmail.com</email></author><category term="Infra as code" /><category term="iac" /><category term="terraform" /><category term="tricks" /><category term="aws" /><category term="basics" /><summary type="html"><![CDATA[Using dynamic blocks helps to avoid repeat code and be more concise in logic]]></summary></entry></feed>