<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Beyond Backfills]]></title><description><![CDATA[Beyond Backfills is a space to explore the art and craft of data engineering. The goal isn’t just moving bytes—it’s understanding the systems that shape them, a]]></description><link>https://blog.pulkitkapoor.com</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1761798374541/8f8fde8e-f7a6-4193-bb59-b27466a73f53.png</url><title>Beyond Backfills</title><link>https://blog.pulkitkapoor.com</link></image><generator>RSS for Node</generator><lastBuildDate>Mon, 09 Nov 2026 17:36:12 GMT</lastBuildDate><atom:link href="https://blog.pulkitkapoor.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Apache Hadoop — Background]]></title><description><![CDATA[Technologies come and go, but data is here to grow! Data is the core of every modern application, driving insights, automation, and user experiences. Over…]]></description><link>https://blog.pulkitkapoor.com/apache-hadoop-background</link><guid isPermaLink="true">https://blog.pulkitkapoor.com/apache-hadoop-background</guid><category><![CDATA[data-engineering]]></category><category><![CDATA[hadoop]]></category><dc:creator><![CDATA[Pulkit]]></dc:creator><pubDate>Tue, 20 May 2025 04:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/658086d044672d510fd7b205/54e854d9-9f5b-4b2b-a143-05af9c0d6ae9.webp" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>Technologies come and go, but data is here to grow!</p>
</blockquote>
<h2>Introduction</h2>
<p>Data is the <strong>core of every modern application</strong>, driving insights, automation, and user experiences. Over time, technologies have evolved to collect, process, and analyze this data more efficiently.</p>
<p>Here’s a quick historical view of that evolution:</p>
<ul>
<li><p><strong>Excel</strong></p>
</li>
<li><p><strong>Oracle SQL, Microsoft SQL Server</strong></p>
</li>
<li><p><strong>Hadoop</strong></p>
</li>
<li><p><strong>Spark</strong></p>
</li>
</ul>
<p>Each stage emerged to overcome limitations of its predecessors — particularly in scale, performance, and flexibility.</p>
<hr />
<h2>The Big Data Problem</h2>
<p>With the rise of the <strong>internet</strong>, <strong>smartphones</strong>, and <strong>IoT</strong>, data exploded in both <strong>volume</strong> and <strong>variety</strong>.</p>
<p>We began dealing with massive datasets in formats like JSON, XML, DOC, MP4, and Avro — data streaming in at high velocity from diverse sources.</p>
<p>Traditional RDBMS systems struggled because they weren’t designed for:</p>
<ul>
<li><p><strong>Volume</strong> – petabytes and beyond</p>
</li>
<li><p><strong>Variety</strong> – structured + unstructured</p>
</li>
<li><p><strong>Velocity</strong> – real-time and streaming workloads</p>
</li>
</ul>
<p>These three challenges together form what we call the <strong>3 Vs of Big Data</strong>.</p>
<p>Despite decades of improvements, traditional databases were not built to handle these scale problems efficiently — leading to the rise of <strong>distributed computing</strong>.</p>
<hr />
<h2>Distributed Computing</h2>
<p>To solve challenges around <strong>scalability</strong>, <strong>availability</strong>, and <strong>cost</strong>, distributed systems like <strong>Apache Hadoop</strong> and <strong>Apache Spark</strong> emerged.</p>
<p>They distribute data across clusters of machines and process them <strong>in parallel</strong>, allowing:</p>
<ul>
<li><p>High throughput</p>
</li>
<li><p>Fault tolerance</p>
</li>
<li><p>Linear scalability</p>
</li>
</ul>
<h3>Key Features of Distributed Systems</h3>
<ol>
<li><p><strong>Scalability</strong> — Handle growing data volumes easily.</p>
</li>
<li><p><strong>High Availability</strong> — Tolerate node failures without losing data.</p>
</li>
<li><p><strong>Cost Efficiency</strong> — Scale horizontally using commodity hardware.</p>
</li>
</ol>
<p>Among these, <strong>Apache Spark</strong> later gained traction due to its <strong>in-memory computation</strong> and ease of use — but Hadoop laid the foundation.</p>
<hr />
<h2>Basic Background: Hadoop</h2>
<p>At its core, Hadoop consists of <strong>three major layers</strong>:</p>
<pre><code class="language-text">YARN        - Cluster resource manager
HDFS        - Distributed storage layer
MapReduce   - Computation framework
</code></pre>
<img src="https://chatgpt.com/c/spark-articles-hadoop-1.png" alt="Hadoop Architecture" />

<ul>
<li><p><strong>YARN</strong> acts as the operating system of the cluster, managing resources and scheduling jobs.</p>
</li>
<li><p><strong>HDFS</strong> stores data in blocks across nodes, ensuring replication and fault tolerance.</p>
</li>
<li><p><strong>MapReduce</strong> provides a computation framework for processing data in parallel using Java-based programs.</p>
</li>
</ul>
<p>You can think of Hadoop as a <strong>distributed operating system</strong> for big data — simplifying how you work with clusters of machines.</p>
<p>Modern engines like Spark now build on this foundation while abstracting away much of the complexity.</p>
<hr />
<h2>Hadoop Ecosystem</h2>
<p>While Hadoop originally consisted of <strong>HDFS</strong>, <strong>YARN</strong>, and <strong>MapReduce</strong>, a broader ecosystem has evolved around it.</p>
<table>
<thead>
<tr>
<th>Component</th>
<th>Purpose</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Hive</strong></td>
<td>SQL-like data warehousing on Hadoop</td>
</tr>
<tr>
<td><strong>HBase</strong></td>
<td>NoSQL database for large datasets</td>
</tr>
<tr>
<td><strong>Sqoop</strong></td>
<td>Transfer data between RDBMS and Hadoop</td>
</tr>
<tr>
<td><strong>Oozie</strong></td>
<td>Workflow scheduler for Hadoop jobs</td>
</tr>
</tbody></table>
<p>These tools extend Hadoop’s capabilities, turning it into a complete big data platform.</p>
<hr />
<h2>Hadoop Architecture</h2>
<p>To understand Hadoop deeply, you need to know its three main subsystems:</p>
<ol>
<li><p><strong>HDFS (Storage Layer)</strong></p>
</li>
<li><p><strong>YARN (Resource Management Layer)</strong></p>
</li>
<li><p><strong>MapReduce (Computation Layer)</strong></p>
</li>
</ol>
<p>Hadoop runs on <strong>clusters of commodity hardware</strong>. Each component runs as a <strong>Java daemon process</strong> — a long-running background service.</p>
<p>Let’s break this down starting with HDFS.</p>
<hr />
<h2>HDFS — Hadoop Distributed File System</h2>
<p>HDFS was inspired by Google’s <strong>GFS (Google File System)</strong>.<br />It allows reliable storage and access to very large datasets using a <strong>master-slave architecture</strong>.</p>
<img src="https://chatgpt.com/c/spark-article-hdfs-arch.png" alt="HDFS Architecture" />

<h3>Key Components</h3>
<h4>1. NameNode (Master)</h4>
<ul>
<li><p>Runs on the master node.</p>
</li>
<li><p>Stores <strong>metadata</strong> about files — directories, block locations, and replication info.</p>
</li>
<li><p>Think of it as the <strong>librarian</strong> that knows where every book (data block) is stored.</p>
</li>
</ul>
<h4>2. DataNode (Worker)</h4>
<ul>
<li><p>Stores the <strong>actual data blocks</strong>.</p>
</li>
<li><p>Each file is split into <strong>blocks</strong> (default size: <strong>128 MB</strong>) which are <strong>replicated</strong> across nodes for reliability.</p>
</li>
</ul>
<hr />
<h3>Example — Metadata in NameNode</h3>
<p>When you store a 1GB file, it’s split into 8 blocks (assuming 128MB each). The NameNode keeps metadata like:</p>
<pre><code class="language-plaintext">FILE: example.txt
DIRECTORY: /data
SIZE: 1GB
BLOCKS:
  - BLOCK1: ID=blk_001, LOCATION=datanode1:/disk1/data/block1
  - BLOCK2: ID=blk_002, LOCATION=datanode2:/disk1/data/block2
  ...
</code></pre>
<p>You can view file metadata using:</p>
<pre><code class="language-bash">hdfs fsck hdfs://&lt;file-path&gt; -location -blocks -files
</code></pre>
<hr />
<h3>How Reading from HDFS Works</h3>
<ol>
<li><p>Client sends read request → <strong>NameNode</strong></p>
</li>
<li><p>NameNode returns <strong>block locations</strong></p>
</li>
<li><p>Client fetches blocks directly from <strong>DataNodes</strong></p>
</li>
<li><p>Client reassembles blocks into the full file</p>
</li>
</ol>
<hr />
<h3>How Writing to HDFS Works</h3>
<ol>
<li><p>Client sends write request → <strong>NameNode</strong></p>
</li>
<li><p>NameNode responds with <strong>target DataNodes</strong> for each block</p>
</li>
<li><p>Client splits file into blocks and writes sequentially</p>
</li>
<li><p>DataNodes send acknowledgment back to NameNode</p>
</li>
<li><p>NameNode updates metadata once all blocks are written</p>
</li>
</ol>
<hr />
<h3>Common HDFS Commands</h3>
<table>
<thead>
<tr>
<th>Action</th>
<th>Command</th>
</tr>
</thead>
<tbody><tr>
<td>List files</td>
<td><code>hdfs dfs -ls &lt;path&gt;</code></td>
</tr>
<tr>
<td>Copy to HDFS</td>
<td><code>hdfs dfs -copyFromLocal &lt;local&gt; &lt;hdfs&gt;</code></td>
</tr>
<tr>
<td>Change permissions</td>
<td><code>hdfs dfs -chmod 777 &lt;path&gt;</code></td>
</tr>
<tr>
<td>Rename file</td>
<td><code>hdfs dfs -mv &lt;src&gt; &lt;dest&gt;</code></td>
</tr>
<tr>
<td>View contents</td>
<td><code>hdfs dfs -cat &lt;file&gt;</code></td>
</tr>
<tr>
<td>Check disk usage</td>
<td><code>hdfs dfs -du -s -h /user/test</code></td>
</tr>
</tbody></table>
<hr />
<h2>Hadoop YARN</h2>
<p>Once the data is stored in HDFS, it needs to be processed.<br />This is where <strong>YARN</strong> (Yet Another Resource Negotiator) comes in — it manages resources across the cluster.</p>
<p>Like HDFS, YARN also follows a <strong>master-slave architecture</strong>:</p>
<table>
<thead>
<tr>
<th>Component</th>
<th>Role</th>
</tr>
</thead>
<tbody><tr>
<td><strong>ResourceManager</strong></td>
<td>Manages overall cluster resources</td>
</tr>
<tr>
<td><strong>NodeManager</strong></td>
<td>Runs on each worker node, reporting usage and launching containers</td>
</tr>
</tbody></table>
<p>YARN decouples <strong>resource management</strong> from <strong>computation</strong>, enabling multiple frameworks (e.g., MapReduce, Spark, Hive) to run simultaneously on the same cluster.</p>
<hr />
<h2>Summary</h2>
<p>Hadoop revolutionized big data processing by introducing:</p>
<ul>
<li><p><strong>Distributed storage (HDFS)</strong></p>
</li>
<li><p><strong>Cluster resource management (YARN)</strong></p>
</li>
<li><p><strong>Parallel computation (MapReduce)</strong></p>
</li>
</ul>
<p>It laid the foundation for modern data platforms and continues to influence technologies like <strong>Spark</strong>, <strong>Flink</strong>, and <strong>Databricks</strong>.</p>
]]></content:encoded></item><item><title><![CDATA[AWS EMR – Private Subnets]]></title><description><![CDATA[In this guide, we’ll walk through creating an Amazon EMR cluster in a private subnet using Terraform. By placing your EMR cluster in a private subnet, you…]]></description><link>https://blog.pulkitkapoor.com/aws-emr-private-subnets</link><guid isPermaLink="true">https://blog.pulkitkapoor.com/aws-emr-private-subnets</guid><category><![CDATA[AWS]]></category><category><![CDATA[Terraform]]></category><category><![CDATA[data-engineering]]></category><category><![CDATA[emr]]></category><category><![CDATA[Private Cloud]]></category><category><![CDATA[privacy]]></category><dc:creator><![CDATA[Pulkit]]></dc:creator><pubDate>Wed, 09 Apr 2025 04:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1761801446105/8151d9b9-28b2-48f7-86fd-dbb26626521c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In this guide, we’ll walk through <strong>creating an Amazon EMR cluster in a private subnet</strong> using Terraform.</p>
<p>By placing your EMR cluster in a <strong>private subnet</strong>, you prevent it from being directly accessible from the internet — improving both <strong>security</strong> and <strong>compliance posture</strong>.</p>
<p><img src="https://www.pulkitkapoor.com/assets/images/collections/posts/2024-04-10-EMR-Private-Cluster-Infra/arch.png" alt="EMR private cluster architecture" /></p>
<p>👉 <a target="_blank" href="https://github.com/k-pulkit/learning-central-engineering/tree/main/topic-EMR/lab1">View the complete code on GitHub</a></p>
<hr />
<h2 id="heading-prerequisites">Prerequisites</h2>
<p>Before proceeding, make sure you have:</p>
<ul>
<li><p>An <strong>AWS account</strong> with permissions to create resources</p>
</li>
<li><p><strong>Terraform</strong> installed on your local machine</p>
</li>
</ul>
<hr />
<h2 id="heading-step-1-setting-up-the-terraform-configuration">Step 1: Setting Up the Terraform Configuration</h2>
<p>Create a new Terraform configuration file (<code>emr_cluster.tf</code>) and define the AWS provider:</p>
<pre><code class="lang-plaintext">provider "aws" {
  profile = "terraform"
  region  = var.region
}

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~&gt; 5.42.0"
    }
  }
}
</code></pre>
<blockquote>
<p>Here, we configure the AWS provider to use the “terraform” profile and region defined in <code>var.region</code>.</p>
</blockquote>
<hr />
<h2 id="heading-step-2-declaring-data-sources">Step 2: Declaring Data Sources</h2>
<p>Fetch dynamic data from AWS — for example, available Availability Zones:</p>
<pre><code class="lang-plaintext">data "aws_availability_zones" "available" {}
</code></pre>
<hr />
<h2 id="heading-step-3-defining-local-variables">Step 3: Defining Local Variables</h2>
<p>Define reusable local variables:</p>
<pre><code class="lang-plaintext">locals {
  name        = replace(basename(path.cwd), "-cluster", "")
  vpc_name    = "MyVPC1"
  vpc_cidr    = "10.0.0.0/16"
  bucket_name = "slvr-emr-bucket-443"
  azs         = slice(data.aws_availability_zones.available.names, 0, 3)
}
</code></pre>
<blockquote>
<p><code>azs</code> takes the first 3 availability zones from your AWS region.</p>
</blockquote>
<hr />
<h2 id="heading-step-4-configuring-the-emr-module">Step 4: Configuring the EMR Module</h2>
<p>Define the EMR module to launch your cluster:</p>
<pre><code class="lang-plaintext">module "emr_instance_group" {
  source  = "terraform-aws-modules/emr/aws"
  version = "~&gt; 1.2.1"

  name = "${local.name}-instance-group"

  release_label_filters = {
    emr6 = { prefix = "emr-6" }
  }

  applications = ["spark", "hadoop"]
  auto_termination_policy = { idle_timeout = 3600 }

  bootstrap_action = {
    example = {
      path = "file:/bin/echo"
      name = "Just an example"
      args = ["Hello World!"]
    }
  }

  configurations_json = jsonencode([
    {
      "Classification" : "spark-env",
      "Configurations" : [
        {
          "Classification" : "export",
          "Properties" : { "JAVA_HOME" : "/usr/lib/jvm/java-1.8.0" }
        }
      ],
      "Properties" : {}
    }
  ])

  master_instance_group = {
    name           = "master-group"
    instance_count = 1
    instance_type  = "m5.xlarge"
    bid_price      = "0.25"
  }

  core_instance_group = {
    name           = "core-group"
    instance_count = 1
    instance_type  = "c4.2xlarge"
    bid_price      = "0.25"
  }

  ebs_root_volume_size = 64

  ec2_attributes = {
    subnet_id = element(module.vpc.private_subnets, 0)
    key_name  = "Login-1"
  }

  vpc_id            = module.vpc.vpc_id
  is_private_cluster = true

  master_security_group_rules = {
    "rule1" = {
      description = "Allow SSH ingress"
      type        = "ingress"
      from_port   = 22
      to_port     = 22
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    },
    "rule2" = {
      description = "Allow all egress traffic"
      type        = "egress"
      from_port   = 0
      to_port     = 0
      protocol    = "-1"
      cidr_blocks = ["0.0.0.0/0"]
    }
  }

  keep_job_flow_alive_when_no_steps = true
  log_uri = "s3://${module.s3_bucket.s3_bucket_id}/"
  step_concurrency_level = 3
  termination_protection = false
  visible_to_all_users = true

  tags = var.tags
  depends_on = [module.vpc, module.s3_bucket]
}
</code></pre>
<h3 id="heading-notes">Notes:</h3>
<ul>
<li><p>Instance Groups = Same instance type for master/core nodes.</p>
</li>
<li><p>Instance Fleets = Mix of types (with spot support) → more cost-effective.</p>
</li>
<li><p>Instance Groups launch in <strong>one private subnet</strong>; Fleets can span <strong>multiple</strong>.</p>
</li>
</ul>
<hr />
<h2 id="heading-step-5-configuring-the-vpc">Step 5: Configuring the VPC</h2>
<p>Define your VPC and subnet layout:</p>
<pre><code class="lang-plaintext">module "vpc" {
  source = "terraform-aws-modules/vpc/aws"

  name = local.vpc_name
  cidr = local.vpc_cidr
  azs  = local.azs

  public_subnets  = [for k, v in local.azs : cidrsubnet(local.vpc_cidr, 8, k)]
  private_subnets = [for k, v in local.azs : cidrsubnet(local.vpc_cidr, 8, k + 8)]

  enable_nat_gateway = true
  single_nat_gateway = true

  default_vpc_enable_dns_hostnames = true
  default_vpc_enable_dns_support   = true

  private_subnet_tags = {
    "for-use-with-amazon-emr-managed-policies" = true
  }

  tags     = var.tags
  vpc_tags = { Name = local.vpc_name }
}
</code></pre>
<blockquote>
<p>NAT Gateway is critical — allows private subnets to reach the internet (e.g., for S3 access).</p>
</blockquote>
<hr />
<h2 id="heading-step-6-configuring-vpc-endpoints">Step 6: Configuring VPC Endpoints</h2>
<p>Add private network access to AWS services:</p>
<pre><code class="lang-plaintext">module "vpc_endpoint" {
  source = "./.terraform/modules/vpc/modules/vpc-endpoints"

  vpc_id = module.vpc.vpc_id
  security_group_ids = [module.vpc_endpoints_sg.security_group_id]

  endpoints = merge(
    {
      s3 = {
        service = "s3"
        service_type = "Gateway"
        private_dns_enabled = true
        route_table_ids = flatten([module.vpc.private_route_table_ids])
        policy = data.aws_iam_policy_document.generic_s3_policy.json
        tags = { Name = "${local.vpc_name}-s3" }
      }
    },
    {
      for service in toset(["elasticmapreduce", "sts"]) :
      service =&gt; {
        service = service
        service_type = "Interface"
        subnet_ids = module.vpc.private_subnets
        private_dns_enabled = true
        tags = { Name = "${local.vpc_name}-${service}" }
      }
    }
  )

  tags = var.tags
  depends_on = [module.vpc, module.vpc_endpoints_sg]
}
</code></pre>
<blockquote>
<p>These endpoints allow EMR to reach <strong>S3</strong>, <strong>EMR API</strong>, and <strong>STS</strong> privately, without Internet Gateway access.</p>
</blockquote>
<hr />
<h2 id="heading-step-7-configuring-the-s3-bucket">Step 7: Configuring the S3 Bucket</h2>
<p>Set up a dedicated bucket for EMR logs and scripts:</p>
<pre><code class="lang-plaintext">module "s3_bucket" {
  source  = "terraform-aws-modules/s3-bucket/aws"
  version = "~&gt; 3.0"
  bucket  = local.bucket_name
  # Additional configurations like encryption can go here
}
</code></pre>
<hr />
<h2 id="heading-step-8-deploying-the-configuration">Step 8: Deploying the Configuration</h2>
<p>Once everything is set up:</p>
<pre><code class="lang-bash">terraform init
terraform plan
terraform apply
</code></pre>
<p>Confirm with <code>yes</code> when prompted.</p>
<p>This will:</p>
<ul>
<li><p>Create your <strong>VPC</strong>, <strong>subnets</strong>, <strong>endpoints</strong>, and <strong>S3 bucket</strong></p>
</li>
<li><p>Launch an <strong>EMR cluster</strong> inside your <strong>private subnet</strong></p>
</li>
</ul>
<hr />
<h2 id="heading-conclusion">Conclusion</h2>
<p>You’ve successfully deployed an <strong>Amazon EMR cluster inside a private subnet</strong> using Terraform 🎯</p>
<p>This setup:</p>
<ul>
<li><p>Ensures EMR operates without public exposure</p>
</li>
<li><p>Uses <strong>VPC endpoints</strong> for S3 &amp; AWS APIs</p>
</li>
<li><p>Can be extended for cost optimization (spot fleets, autoscaling)</p>
</li>
</ul>
<p>📘 <strong>Official AWS Reference:</strong><br /><a target="_blank" href="https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-clusters-in-a-vpc.html">Creating EMR clusters in a VPC (AWS Docs)</a></p>
]]></content:encoded></item><item><title><![CDATA[Apache Spark Unified Memory]]></title><description><![CDATA[Apache Spark, a powerful distributed processing engine, relies heavily on memory management for optimal performance.The Unified Memory Manager (UMM)…]]></description><link>https://blog.pulkitkapoor.com/apache-spark-unified-memory</link><guid isPermaLink="true">https://blog.pulkitkapoor.com/apache-spark-unified-memory</guid><category><![CDATA[data-engineering]]></category><category><![CDATA[spark]]></category><category><![CDATA[apache]]></category><category><![CDATA[#apache-spark]]></category><category><![CDATA[memory-management]]></category><dc:creator><![CDATA[Pulkit]]></dc:creator><pubDate>Thu, 27 Mar 2025 04:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/658086d044672d510fd7b205/a3e301c9-19fd-47ca-95c7-9998644f02a3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>Apache Spark, a powerful distributed processing engine, relies heavily on <strong>memory management</strong> for optimal performance.<br />The <strong>Unified Memory Manager (UMM)</strong> — introduced in Spark 1.6 — plays a key role in efficiently allocating and managing memory resources across executors in your cluster.</p>
<hr />
<h2>Understanding Memory Pools in Spark</h2>
<p>To optimize Spark performance, it’s important to understand terms like:</p>
<ul>
<li><p><strong>Reserved memory</strong></p>
</li>
<li><p><strong>Executor memory</strong></p>
</li>
<li><p><strong>Executor memory fraction</strong></p>
</li>
<li><p><strong>Storage fraction</strong></p>
</li>
<li><p><strong>Overhead memory</strong></p>
</li>
</ul>
<p>The UMM manages <strong>two primary memory pools</strong> inside the broader executor memory:</p>
<h3>🧠 Storage Memory</h3>
<p>Used to:</p>
<ul>
<li><p>Store <strong>RDDs</strong> when cached (<code>persist()</code> / <code>cache()</code>).</p>
</li>
<li><p>Hold <strong>broadcast</strong> variables for joins and lookups.</p>
</li>
</ul>
<p>You can control it using:</p>
<pre><code class="language-bash">spark.executor.storage.fraction
</code></pre>
<h3>⚙️ Execution Memory</h3>
<p>Used for active computations like:</p>
<ul>
<li><p>Joins</p>
</li>
<li><p>Sorting</p>
</li>
<li><p>Aggregations</p>
</li>
</ul>
<p>These operations rely on temporary in-memory structures to perform efficiently.</p>
<hr />
<h2>Reserved and Overhead Memory</h2>
<h3>🔸 Overhead Memory</h3>
<p>Extra memory required for:</p>
<ul>
<li><p>Off-heap operations</p>
</li>
<li><p>Task execution</p>
</li>
<li><p>JVM &amp; YARN overhead</p>
</li>
</ul>
<p>By default:</p>
<pre><code class="language-plaintext">max(384MB, 10% of executor memory)
</code></pre>
<p>is allocated as overhead — typically sufficient for most workloads.</p>
<h3>🔸 Reserved Memory</h3>
<p>Spark internally reserves <strong>300 MB</strong> for metadata and non-execution operations.<br />This space is <strong>not</strong> available to storage or execution tasks.</p>
<hr />
<h2>Simple Example</h2>
<p>Consider a Spark job running on a node with <strong>20 GB total memory</strong>.<br />You allocate:</p>
<pre><code class="language-bash">spark.executor.memory = 10G
spark.executor.offHeap.memory = 1G
</code></pre>
<p>Here’s how Spark divides memory:</p>
<img src="https://www.pulkitkapoor.com/assets/images/collections/posts/2024-03-12-Apache-spark-memory-management/Spark%20Memory.png" alt="Spark executor memory distribution" style="display:block;margin:0 auto" />

<table>
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Overheads (1G)</strong></td>
<td>Memory for JVM, YARN, and Spark internal processes — shown as red blocks.</td>
</tr>
<tr>
<td><strong>On-Heap (10G)</strong></td>
<td>JVM-managed memory. Subject to Garbage Collection (GC). If GC times are high, move some data to off-heap.</td>
</tr>
<tr>
<td><strong>Off-Heap (1G)</strong></td>
<td>Outside JVM control, managed by OS. Reduces GC pressure and improves performance for heavy compute workloads.</td>
</tr>
</tbody></table>
<hr />
<h3>Memory Split Inside On-Heap Memory</h3>
<table>
<thead>
<tr>
<th>Memory Type</th>
<th>Config</th>
<th>Default</th>
<th>Description</th>
</tr>
</thead>
<tbody><tr>
<td><strong>Execution Memory</strong></td>
<td><code>spark.memory.fraction</code></td>
<td>0.75</td>
<td>Used for shuffle, joins, sorts, aggregations</td>
</tr>
<tr>
<td><strong>Storage Memory</strong></td>
<td><code>spark.memory.storageFraction</code></td>
<td>0.5</td>
<td>Portion of unified memory reserved for caching/persistence</td>
</tr>
<tr>
<td><strong>User + Reserved Memory</strong></td>
<td>N/A</td>
<td>Remaining</td>
<td>Used for user data structures, Spark internals</td>
</tr>
</tbody></table>
<hr />
<h2>Optimization Tips</h2>
<p>✅ <strong>Tune Memory Fractions</strong><br />Adjust <code>spark.executor.memory.fraction</code> and <code>spark.executor.storage.fraction</code> based on workload type (compute vs cache heavy).</p>
<p>✅ <strong>Monitor &amp; Tune</strong><br />Regularly review Spark UI or CloudWatch metrics to detect GC issues, OOM errors, and shuffle spills.</p>
<p>✅ <strong>Use Efficient Data Structures</strong><br />Prefer <strong>DataFrames</strong> or <strong>Datasets</strong> over RDDs. They use Catalyst optimization and are more memory efficient.</p>
<p>✅ <strong>Enable Off-Heap Memory</strong><br />Useful for long-running jobs where GC overhead becomes significant.</p>
<hr />
<h2>Memory Calculator (Interactive Concept)</h2>
<p>A simple visualization to understand how Spark divides memory:</p>
<p><a class="embed-card" href="https://codepen.io/pulkit42041/pen/XJXPMjE">https://codepen.io/pulkit42041/pen/XJXPMjE</a></p>

<blockquote>
<p>Tweak these values to find the optimal balance for your workloads.</p>
</blockquote>
<hr />
<h2>Conclusion</h2>
<p>Understanding <strong>Apache Spark’s memory model</strong> is essential for performance tuning.<br />By knowing how Spark partitions memory between execution, storage, and overhead, you can:</p>
<ul>
<li><p>Reduce <strong>OOM</strong> errors</p>
</li>
<li><p>Improve <strong>shuffle performance</strong></p>
</li>
<li><p>Speed up <strong>caching and re-use</strong></p>
</li>
</ul>
<blockquote>
<p>💡 <em>Caching</em> can drastically accelerate pipelines that reuse the same data across stages.<br /><em>Broadcast joins</em> help optimize large joins when one table fits in executor memory.</p>
</blockquote>
<hr />
<p><strong>References:</strong></p>
<ol>
<li><p><a href="https://chatgpt.com/c/69017f81-a078-8327-a66f-afed99d11d37?ref=mini-sidebar#">Caching in Spark</a> — Store intermediate RDDs to reuse results.</p>
</li>
<li><p><a href="https://chatgpt.com/c/69017f81-a078-8327-a66f-afed99d11d37?ref=mini-sidebar#">Broadcast Joins</a> — Send small lookup tables to executors for fast map-side joins.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Serverless Framework]]></title><description><![CDATA[In this series, we’ll focus on Serverless Framework, one of the fastest ways to build and deploy serverless applications. If you’ve already worked with…]]></description><link>https://blog.pulkitkapoor.com/serverless-framework</link><guid isPermaLink="true">https://blog.pulkitkapoor.com/serverless-framework</guid><category><![CDATA[AWS]]></category><category><![CDATA[serverless]]></category><category><![CDATA[Devops]]></category><category><![CDATA[data-engineering]]></category><dc:creator><![CDATA[Pulkit]]></dc:creator><pubDate>Wed, 05 Mar 2025 05:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/uploads/covers/658086d044672d510fd7b205/4bea02e8-a6df-483e-9318-dc0fa60bd35f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>In this series, we’ll focus on <strong>Serverless Framework</strong>, one of the fastest ways to build and deploy serverless applications.</p>
<p>If you’ve already worked with <strong>Terraform</strong>, you know how great it is for infrastructure automation. So why another tool?<br />Because <strong>Serverless Framework</strong> is built specifically for deploying <strong>serverless apps</strong> — it abstracts away the heavy lifting of infrastructure management and lets you deploy complex setups in just a few lines of configuration.</p>
<p>Just like Terraform, Serverless is <strong>cloud-agnostic</strong> — it supports <strong>AWS</strong>, <strong>GCP</strong>, and <strong>Azure</strong> out of the box.</p>
<p>👉 <a href="https://www.serverless.com/">Official website</a></p>
<hr />
<h2>Setting Up</h2>
<p>Refer to the <a href="https://www.serverless.com/framework/docs/getting-started">official setup guide</a> for installation instructions.</p>
<p>If you’re on Windows, consider using <strong>WSL (Windows Subsystem for Linux)</strong> — it makes development smoother and closer to a native Linux experience, especially when working with AWS or Python.</p>
<p>Once Serverless is installed, it can use your <strong>existing AWS CLI credentials</strong> automatically.<br />If you already have AWS CLI configured with a default profile, you don’t need extra setup.</p>
<p>However, if you haven’t configured AWS yet, here’s how:</p>
<ol>
<li><p>Go to <strong>IAM → Users</strong> in AWS Console</p>
</li>
<li><p>Create a new user named <code>serverless</code></p>
</li>
<li><p>Attach the <strong>AdministratorFullAccess</strong> policy (for simplicity — use least privilege in production)</p>
</li>
<li><p>Create an <strong>Access Key</strong> and <strong>Secret Key</strong></p>
</li>
<li><p>Configure credentials locally:</p>
</li>
</ol>
<pre><code class="language-bash">serverless --version
serverless config credentials --provider aws --key &lt;yourKey&gt; --secret &lt;yourSecret&gt;
</code></pre>
<hr />
<h2>Test Setup</h2>
<p>To confirm everything works, let’s deploy a simple Lambda function.</p>
<h3>Create a Test Project</h3>
<pre><code class="language-bash">serverless create --template aws-python --path new_project --name testFunc
</code></pre>
<p>This will generate a project structure like:</p>
<pre><code class="language-plaintext">new_project/
├── handler.py
└── serverless.yml
</code></pre>
<h3>Minimal <code>serverless.yml</code></h3>
<p>Remove comments to simplify it:</p>
<pre><code class="language-yaml">service: testFunc
frameworkVersion: '3'

provider:
  name: aws
  runtime: python3.8

functions:
  hello:
    handler: handler.hello
</code></pre>
<h3>Deploy</h3>
<p>Now deploy the function:</p>
<pre><code class="language-bash">sls deploy
</code></pre>
<p>Once deployed, you’ll see a confirmation similar to this:</p>
<pre><code class="language-plaintext">Deploying testFunc to AWS...
Service Information
stage: dev
region: us-east-1
stack: testFunc-dev
</code></pre>
<p>To remove everything later:</p>
<pre><code class="language-bash">sls remove
</code></pre>
<p>🎉 <strong>Congratulations!</strong> You just deployed your first serverless function.</p>
<hr />
<h2>Invoking the Function</h2>
<p>Testing locally or through the CLI is straightforward:</p>
<pre><code class="language-bash"># Invoke and view output
sls invoke -f hello --log

# Stream recent logs
sls logs -f hello --tail
</code></pre>
<h3>Sample Output</h3>
<pre><code class="language-bash">$ sls invoke -f hello --log
{
  "statusCode": 200,
  "body": "{\"message\": \"Go Serverless v1.0! Your function executed successfully!\", \"input\": {}}"
}
--------------------------------------------------------------------
START
END Duration: 1.33 ms (init: 130.95 ms) Memory Used: 38 MB
</code></pre>
<hr />
<h2>Using External Libraries</h2>
<p>Most real-world Lambdas depend on external libraries (like <code>pandas</code> or <code>requests</code>).<br />Serverless makes it easy to package and deploy them in two ways:</p>
<h3>Option 1 — Include Dependencies as a Zip</h3>
<p>Bundle dependencies directly into your deployment zip.</p>
<h3>Option 2 — Use Lambda Layers</h3>
<p>Upload dependencies as a <strong>Lambda Layer</strong> to share across multiple functions.<br />Learn more: <a href="https://aws.amazon.com/blogs/compute/using-lambda-layers-to-simplify-your-development-process/">AWS Blog – Lambda Layers</a></p>
<hr />
<h3>Using the <code>serverless-python-requirements</code> Plugin</h3>
<p>Install the plugin:</p>
<pre><code class="language-bash">sls plugin install -n serverless-python-requirements
</code></pre>
<p>Then update <code>serverless.yml</code>:</p>
<h4>Using Zip Packaging</h4>
<pre><code class="language-yaml">plugins:
  - serverless-python-requirements

custom:
  pythonRequirements:
    dockerizePip: true
    zip: true
</code></pre>
<p>For zipped dependencies, include this at the top of your Python code:</p>
<pre><code class="language-python">import unzip_requirements
</code></pre>
<h4>Using Lambda Layers</h4>
<pre><code class="language-yaml">plugins:
  - serverless-python-requirements

custom:
  pythonRequirements:
    dockerizePip: true
    layer:
      name: PandasLayer
</code></pre>
<p>Define dependencies in <code>requirements.txt</code>, for example:</p>
<pre><code class="language-plaintext">pandas==1.0.1
</code></pre>
<p>Serverless will automatically build and deploy them as a Lambda Layer.</p>
<hr />
<h2>Summary</h2>
<p>The <strong>Serverless Framework</strong> offers a fast, cloud-agnostic way to create and manage serverless applications.<br />It simplifies deployment, testing, and packaging, letting developers focus on code — not infrastructure.</p>
<p>👉 Check out the GitHub repository for examples:<br /><a href="https://github.com/k-pulkit/source-demo-serverless-framework/tree/main">github.com/k-pulkit/source-demo-serverless-framework</a></p>
]]></content:encoded></item><item><title><![CDATA[AWS S3 Multi-Part Uploads]]></title><description><![CDATA[Once you’ve created an S3 bucket, you’ll likely need to transfer large files — sometimes in the order of gigabytes or even terabytes. AWS S3 allows object…]]></description><link>https://blog.pulkitkapoor.com/aws-s3-multi-part-uploads</link><guid isPermaLink="true">https://blog.pulkitkapoor.com/aws-s3-multi-part-uploads</guid><category><![CDATA[AWS]]></category><category><![CDATA[S3]]></category><category><![CDATA[bucket]]></category><category><![CDATA[upload]]></category><dc:creator><![CDATA[Pulkit]]></dc:creator><pubDate>Thu, 20 Feb 2025 05:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1761794206402/c92bcd19-2bb1-4739-9ddb-7399090b618c.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Once you’ve created an S3 bucket, you’ll likely need to transfer large files — sometimes in the order of gigabytes or even terabytes.</p>
<p>AWS S3 allows object sizes of up to <strong>5 TB</strong>, but a single <code>PUT</code> upload is limited to <strong>5 GB</strong>.
To handle larger uploads, S3 offers a <strong>Multi-Part Upload</strong> mechanism.</p>
<p>The idea is simple:</p>
<ul>
<li>Split the large file into smaller <strong>parts</strong></li>
<li>Upload each part individually (possibly in parallel)</li>
<li>S3 reassembles these parts into the final object</li>
</ul>
<p>This method provides two key advantages:</p>
<ol>
<li><strong>Fault tolerance:</strong> If an upload fails midway, you can resume from the failed part.</li>
<li><strong>Parallelism:</strong> Parts can be uploaded concurrently for faster throughput.</li>
</ol>
<hr />
<h2 id="heading-rules-to-remember">Rules to Remember</h2>
<p>Before jumping into implementation, note the following S3 Multi-Part Upload constraints:</p>
<ul>
<li>A file can be split into a <strong>maximum of 10,000 parts</strong>.</li>
<li>Each part must be between <strong>5 MB and 100 MB</strong> in size.</li>
<li>You can use <strong>S3 lifecycle policies</strong> to automatically abort unfinished multi-part uploads that exceed a time limit.</li>
</ul>
<hr />
<h2 id="heading-steps-for-a-multi-part-upload">Steps for a Multi-Part Upload</h2>
<p>The process involves three main stages:</p>
<ol>
<li><p><strong>Initiate the upload</strong>
Use <code>CreateMultipartUpload</code> API — this returns an <code>UploadId</code> used to reference the ongoing upload.</p>
</li>
<li><p><strong>Upload each part</strong>
Use the <code>UploadPart</code> API — each call returns an <code>ETag</code> (a checksum for that part).</p>
</li>
<li><p><strong>Complete the upload</strong>
Call <code>CompleteMultipartUpload</code> with the <code>UploadId</code>, part numbers, and their ETags.
S3 then assembles the file from these parts.</p>
</li>
</ol>
<blockquote>
<p>You can even overwrite parts while the upload is in progress — enabling in-flight file modifications.</p>
</blockquote>
<hr />
<h2 id="heading-hands-on-implementation">Hands-On Implementation</h2>
<p>We’ll walk through creating a Python script using <code>boto3</code> to perform a multi-part upload.</p>
<h3 id="heading-step-1-get-upload-id">Step 1 — Get Upload ID</h3>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> boto3

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">start_upload</span>(<span class="hljs-params">bucket, key</span>):</span>
    <span class="hljs-string">"""Returns the UploadId for multi-part upload"""</span>
    client = boto3.client(<span class="hljs-string">"s3"</span>)
    response = client.create_multipart_upload(Bucket=bucket, Key=key)
    <span class="hljs-keyword">return</span> response[<span class="hljs-string">"UploadId"</span>]
</code></pre>
<p>This initializes the upload and returns the <code>UploadId</code>.</p>
<hr />
<h3 id="heading-step-2-upload-one-part">Step 2 — Upload One Part</h3>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">upload_part</span>(<span class="hljs-params">bucket, key, part_num, upload_id, data</span>):</span>
    <span class="hljs-string">"""Upload a part to S3"""</span>
    client = boto3.client(<span class="hljs-string">"s3"</span>)
    response = client.upload_part(
        Bucket=bucket,
        Key=key,
        PartNumber=part_num,
        UploadId=upload_id,
        Body=data
    )
    print(<span class="hljs-string">f"Uploaded part <span class="hljs-subst">{part_num}</span> with ETag <span class="hljs-subst">{response[<span class="hljs-string">'ETag'</span>]}</span>"</span>)
    <span class="hljs-keyword">return</span> {<span class="hljs-string">'PartNumber'</span>: part_num, <span class="hljs-string">'ETag'</span>: response[<span class="hljs-string">'ETag'</span>]}
</code></pre>
<p>Each part requires the same <code>UploadId</code> and its sequence number.
The response contains an <code>ETag</code> that must be passed during final assembly.</p>
<hr />
<h3 id="heading-step-3-putting-it-together">Step 3 — Putting It Together</h3>
<p>You can parallelize uploads using the <code>concurrent.futures</code> module:</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> concurrent.futures <span class="hljs-keyword">import</span> ProcessPoolExecutor, as_completed
<span class="hljs-keyword">import</span> boto3

<span class="hljs-comment"># Start upload</span>
upload_id = start_upload(bucket, key)

<span class="hljs-comment"># Upload parts in parallel</span>
futures = []
<span class="hljs-keyword">with</span> ProcessPoolExecutor(max_workers=<span class="hljs-number">10</span>) <span class="hljs-keyword">as</span> executor:
    <span class="hljs-keyword">with</span> open(file_name, <span class="hljs-string">"rb"</span>) <span class="hljs-keyword">as</span> f:
        i = <span class="hljs-number">1</span>
        chunk = f.read(chunk_size_bytes)
        <span class="hljs-keyword">while</span> len(chunk) &gt; <span class="hljs-number">0</span>:
            future = executor.submit(
                upload_part,
                bucket=bucket,
                key=key,
                part_num=i,
                upload_id=upload_id,
                data=chunk
            )
            futures.append(future)
            i += <span class="hljs-number">1</span>
            chunk = f.read(chunk_size_bytes)

<span class="hljs-comment"># Collect results</span>
results = [f.result() <span class="hljs-keyword">for</span> f <span class="hljs-keyword">in</span> as_completed(futures)]

<span class="hljs-comment"># Complete upload</span>
boto3.client(<span class="hljs-string">"s3"</span>).complete_multipart_upload(
    Bucket=bucket,
    Key=key,
    UploadId=upload_id,
    MultipartUpload={<span class="hljs-string">'Parts'</span>: sorted(results, key=<span class="hljs-keyword">lambda</span> e: e[<span class="hljs-string">"PartNumber"</span>])}
)
</code></pre>
<hr />
<h3 id="heading-step-4-testing-the-program">Step 4 — Testing the Program</h3>
<pre><code class="lang-bash"><span class="hljs-comment"># Create a test bucket</span>
aws s3 mb s3://test-3224-random --region us-east-1

<span class="hljs-comment"># Run the program</span>
python3 upload.py --file app.msi --bucket test-3224-random --key app.msi --chunk_size 6
</code></pre>
<p>That’s it — the script uploads your file in multiple parallel parts, then assembles them in S3.</p>
<hr />
<h2 id="heading-full-solution-code">Full Solution Code</h2>
<p>Here’s the complete working script:</p>
<pre><code class="lang-python"><span class="hljs-keyword">import</span> boto3
<span class="hljs-keyword">import</span> argparse
<span class="hljs-keyword">import</span> json
<span class="hljs-keyword">from</span> concurrent.futures <span class="hljs-keyword">import</span> ProcessPoolExecutor, as_completed

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">start_upload</span>(<span class="hljs-params">bucket, key</span>):</span>
    <span class="hljs-string">"""Returns the UploadId for multi-part upload"""</span>
    client = boto3.client(<span class="hljs-string">"s3"</span>)
    response = client.create_multipart_upload(Bucket=bucket, Key=key)
    <span class="hljs-keyword">return</span> response[<span class="hljs-string">"UploadId"</span>]

<span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">upload_part</span>(<span class="hljs-params">bucket, key, part_num, upload_id, data</span>):</span>
    <span class="hljs-string">"""Upload a part to S3"""</span>
    client = boto3.client(<span class="hljs-string">"s3"</span>)
    response = client.upload_part(
        Bucket=bucket,
        Key=key,
        PartNumber=part_num,
        UploadId=upload_id,
        Body=data
    )
    print(<span class="hljs-string">f"Uploaded part <span class="hljs-subst">{part_num}</span> and received ETag <span class="hljs-subst">{response[<span class="hljs-string">'ETag'</span>]}</span>"</span>)
    <span class="hljs-keyword">return</span> {<span class="hljs-string">'PartNumber'</span>: part_num, <span class="hljs-string">'ETag'</span>: response[<span class="hljs-string">'ETag'</span>]}

<span class="hljs-keyword">if</span> __name__ == <span class="hljs-string">'__main__'</span>:
    MB = <span class="hljs-number">1024</span> * <span class="hljs-number">1024</span>

    parser = argparse.ArgumentParser()
    parser.add_argument(<span class="hljs-string">"--file"</span>, required=<span class="hljs-literal">True</span>)
    parser.add_argument(<span class="hljs-string">"--bucket"</span>, required=<span class="hljs-literal">True</span>)
    parser.add_argument(<span class="hljs-string">"--key"</span>, required=<span class="hljs-literal">True</span>)
    parser.add_argument(<span class="hljs-string">"--chunk_size"</span>, required=<span class="hljs-literal">True</span>, help=<span class="hljs-string">"Size of each part in MB."</span>)
    args = parser.parse_args()

    file_name = args.file
    bucket = args.bucket
    key = args.key
    chunk_size_bytes = int(args.chunk_size) * MB

    upload_id = start_upload(bucket, key)

    futures = []
    <span class="hljs-keyword">with</span> ProcessPoolExecutor(max_workers=<span class="hljs-number">10</span>) <span class="hljs-keyword">as</span> executor:
        <span class="hljs-keyword">with</span> open(file_name, <span class="hljs-string">"rb"</span>) <span class="hljs-keyword">as</span> f:
            i = <span class="hljs-number">1</span>
            chunk = f.read(chunk_size_bytes)
            <span class="hljs-keyword">while</span> len(chunk) &gt; <span class="hljs-number">0</span>:
                future = executor.submit(upload_part, bucket, key, i, upload_id, chunk)
                futures.append(future)
                i += <span class="hljs-number">1</span>
                chunk = f.read(chunk_size_bytes)

    results = [f.result() <span class="hljs-keyword">for</span> f <span class="hljs-keyword">in</span> as_completed(futures)]

    response = boto3.client(<span class="hljs-string">"s3"</span>).complete_multipart_upload(
        Bucket=bucket,
        Key=key,
        UploadId=upload_id,
        MultipartUpload={<span class="hljs-string">'Parts'</span>: sorted(results, key=<span class="hljs-keyword">lambda</span> e: e[<span class="hljs-string">"PartNumber"</span>])}
    )

    print(json.dumps(response))
</code></pre>
<hr />
<h2 id="heading-summary">Summary</h2>
<ul>
<li>Multi-part upload splits large files for parallel and resumable uploads.</li>
<li>Each part is individually uploaded and later combined by S3.</li>
<li>This method enhances reliability and performance for massive datasets.</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Terraform Dynamic Blocks]]></title><description><![CDATA[In this part, we’ll explore some advanced features of Terraform. You’ll learn about variable types, constructs like for_each, and how to use dynamic blocks…]]></description><link>https://blog.pulkitkapoor.com/terraform-dynamic-blocks</link><guid isPermaLink="true">https://blog.pulkitkapoor.com/terraform-dynamic-blocks</guid><category><![CDATA[Devops]]></category><category><![CDATA[AWS]]></category><category><![CDATA[data-engineering]]></category><category><![CDATA[terraform-cloud]]></category><dc:creator><![CDATA[Pulkit]]></dc:creator><pubDate>Thu, 13 Feb 2025 05:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1761793674198/270dcb4d-aa74-4a61-ac52-b6f75e137780.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2>Introduction</h2>
<p>In this part, we’ll explore some <strong>advanced features of Terraform</strong>. You’ll learn about variable types, constructs like <code>for_each</code>, and how to use <strong>dynamic blocks</strong> to make your Terraform code cleaner and less verbose.</p>
<hr />
<h2>Introduction to Variables</h2>
<p>Just like other programming languages, Terraform’s <strong>HCL (HashiCorp Configuration Language)</strong> supports variables and data types.</p>
<p>Modules and resource blocks often accept arbitrary user inputs. The best practice is to define variables in a <code>terraform.tfvars</code> file, which supplies values to Terraform during runtime.</p>
<p>Let’s start with a simple example.</p>
<hr />
<h2>Example Usage</h2>
<p>We’ll create a Terraform project that provisions an <strong>S3 bucket</strong>. This project will include the following files:</p>
<pre><code class="language-bash">.
├── backend.tf
├── main.tf
├── terraform.tfvars
└── variables.tf
</code></pre>
<h3><code>main.tf</code></h3>
<p>This file defines the S3 bucket and uses variables via the syntax <code>var.variable_name</code>.</p>
<pre><code class="language-plaintext">provider "aws" {
  profile = var.profile
  region  = var.region
}

resource "aws_s3_bucket" "testbucket" {
  bucket = var.bucket_name
}
</code></pre>
<h3><code>variables.tf</code></h3>
<p>Here we declare the variables used in the project:</p>
<pre><code class="language-plaintext">variable "region" {
  type    = string
  default = "us-east-1"
}

variable "profile" {
  type    = string
  default = "profile-name-to-use"
}

variable "bucket_name" {
  type        = string
  description = "Name of S3 bucket to create"
}
</code></pre>
<p>You can also mark variables as <code>sensitive</code> or add validation rules for stricter control.</p>
<h3><code>terraform.tfvars</code></h3>
<p>This file assigns values to the declared variables:</p>
<pre><code class="language-plaintext">bucket_name = "test_bucket"
</code></pre>
<h3>Terraform Commands</h3>
<p>Here’s a typical Terraform workflow:</p>
<pre><code class="language-bash">terraform init       # Initialize backend and providers
terraform fmt        # Format code
terraform validate   # Validate for syntax errors
terraform plan       # Preview changes
terraform apply      # Apply changes
terraform destroy    # Destroy resources
</code></pre>
<hr />
<h2>Types of Variables</h2>
<p>Terraform supports two broad categories of variables:</p>
<p><strong>1. Primitives:</strong><code>string</code>, <code>boolean</code>, <code>number</code></p>
<p><strong>2. Complex:</strong><code>set</code>, <code>map</code>, <code>object</code>, <code>tuple</code>, <code>list</code>, <code>any</code></p>
<p>Here’s an example of a complex variable definition:</p>
<pre><code class="language-plaintext">variable "igress_params" {
  type = map(object({
    port = number
    proto = string
    cidr  = list(string)
  }))

  default = {
    "rule1" = {
      port  = 22
      proto = "tcp"
      cidr  = ["0.0.0.0/0"]
    },
    "rule2" = {
      port  = 80
      proto = "tcp"
      cidr  = ["1.2.3.4/32"]
    }
  }
}
</code></pre>
<p>This <code>map(object)</code> variable defines ingress rules that you can later reference while creating security groups or VPCs.</p>
<hr />
<h2>Introduction to <code>for_each</code></h2>
<p>The <code>for_each</code> construct is useful when you want to create <strong>multiple resources of the same type</strong> with varying values. For example, creating three S3 buckets for <code>dev</code>, <code>uat</code>, and <code>prod</code>.</p>
<pre><code class="language-plaintext">provider "aws" {
  profile = "aws-profile-to-use"
  region  = "us-east-1"
}

variable "s3_buckets" {
  type        = set(string)
  description = "Name of S3 buckets to create"
  default     = ["test-dev", "test-uat", "test-prod"]
}

resource "aws_s3_bucket" "testbucket" {
  for_each = var.s3_buckets
  bucket   = each.value
}
</code></pre>
<p>Terraform will iterate through <code>s3_buckets</code> and create three separate S3 buckets.</p>
<hr />
<h2>The <code>dynamic</code> Keyword</h2>
<p>When defining resources like <strong>security groups</strong>, you might need multiple ingress or egress rules. Manually declaring them can get verbose and hard to maintain.</p>
<h3>Without Dynamic Blocks</h3>
<pre><code class="language-plaintext">resource "aws_security_group" "my-sg" {
  vpc_id = aws_vpc.my-vpc.id

  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  ingress {
    from_port   = 22
    to_port     = 22
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }
}
</code></pre>
<p>This approach quickly becomes messy for many rules.</p>
<hr />
<h3>With Dynamic Blocks</h3>
<p>We can make this clean and reusable using the <code>dynamic</code> keyword.</p>
<pre><code class="language-plaintext">variable "igress_params" {
  type = map(object({
    port  = number
    proto = string
    cidr  = list(string)
  }))

  default = {
    "rule1" = {
      port  = 22
      proto = "tcp"
      cidr  = ["0.0.0.0/0"]
    },
    "rule2" = {
      port  = 80
      proto = "tcp"
      cidr  = ["1.2.3.4/32"]
    }
  }
}

resource "aws_vpc" "my-vpc" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_security_group" "my-sg" {
  vpc_id = aws_vpc.my-vpc.id

  egress {
    from_port   = 0
    to_port     = 0
    protocol    = "-1"
    cidr_blocks = ["0.0.0.0/0"]
  }

  dynamic "ingress" {
    for_each = var.igress_params
    content {
      from_port   = ingress.value["port"]
      to_port     = ingress.value["port"]
      protocol    = ingress.value["proto"]
      cidr_blocks = ingress.value["cidr"]
    }
  }
}
</code></pre>
<p>Terraform will iterate through each map entry in <code>igress_params</code> and dynamically create multiple <code>ingress</code> blocks — one for each rule.</p>
<blockquote>
<p><strong>Key benefit:</strong> Your Terraform files stay concise, and you can easily scale your configuration by just editing variable definitions.</p>
</blockquote>
<hr />
<h2>In Summary</h2>
<p>Dynamic blocks and constructs like <code>for_each</code> bring <strong>programmability and flexibility</strong> into Terraform — reducing code repetition while improving readability and scalability.</p>
]]></content:encoded></item><item><title><![CDATA[Terraform Modules]]></title><description><![CDATA[divide and rule]]></description><link>https://blog.pulkitkapoor.com/terraform-modules</link><guid isPermaLink="true">https://blog.pulkitkapoor.com/terraform-modules</guid><category><![CDATA[Terraform]]></category><category><![CDATA[Devops]]></category><category><![CDATA[data-engineering]]></category><dc:creator><![CDATA[Pulkit]]></dc:creator><pubDate>Thu, 06 Feb 2025 05:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1761793660485/3b5287d0-8e95-46fc-bb15-4e2074f97dec.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-modules-what-are-they">Modules — What Are They?</h2>
<p>If you’re familiar with any programming language or the principles of software development, you already know the benefits of <strong>modular programming</strong> — maintainability, reusability, and scalability.</p>
<p>Terraform adopts the same philosophy. By breaking down your infrastructure code into smaller, self-contained <strong>modules</strong>, you can build complex infrastructure in a clean, organized, and reusable way.</p>
<blockquote>
<p><strong>In short:</strong> Modular Terraform code is easier to maintain, extend, and test.</p>
</blockquote>
<hr />
<h2 id="heading-sample-modular-terraform-project">Sample Modular Terraform Project</h2>
<p>Here’s a sample Terraform project structure showing how modules fit in:</p>
<pre><code class="lang-bash">.
├── backend.tf
├── main.tf
├── modules                 &lt;- Container <span class="hljs-keyword">for</span> all Terraform modules
│   ├── dynamodb
│   │   ├── main.tf
│   │   ├── outputs.tf
│   │   └── variables.tf
│   ├── ...
├── outputs.tf
├── terraform.tfstate
├── terraform.tfvars
└── variables.tf
</code></pre>
<p>You can reference modules in three main ways:</p>
<ol>
<li><p><strong>Terraform Public Registry</strong> – for reusable community modules</p>
</li>
<li><p><strong>Private Registry</strong> – for internal organization modules</p>
</li>
<li><p><strong>Local Modules</strong> – for modules within your own repo</p>
</li>
</ol>
<hr />
<h2 id="heading-how-to-reference-a-module">How to Reference a Module</h2>
<p>Example reference in <code>main.tf</code>:</p>
<pre><code class="lang-plaintext">module "my-dynamodb-module" {
  source  = "./modules/dynamodb"
  version = "0.0.1"
  region  = var.aws_region
}
</code></pre>
<p>Here, <code>module</code> is a reserved Terraform keyword. You define the module source (local or remote), specify the version, and pass variables the module expects — like <code>aws_region</code> in this case.</p>
<p>Modules can accept multiple inputs and expose outputs that can be reused elsewhere in your Terraform configuration.</p>
<hr />
<h2 id="heading-a-simple-module-example">A Simple Module Example</h2>
<p>Let’s create a simple Terraform module that provisions a DynamoDB table.</p>
<h3 id="heading-folder-setup">Folder Setup</h3>
<pre><code class="lang-plaintext">modules/
└── dynamodb/
    ├── main.tf
    ├── outputs.tf
    └── variables.tf
</code></pre>
<hr />
<h3 id="heading-variablestf"><code>variables.tf</code></h3>
<p>Define input variables for your module:</p>
<pre><code class="lang-plaintext">variable "aws_region" {
  type    = string
  default = "us-east-1"
}

variable "table_name" {
  description = "Name of the DynamoDB table"
  type        = string
}

variable "resource_tags" {
  description = "Project-specific tags for resources"
  type        = map(string)
}
</code></pre>
<p>Our module now takes three inputs: <code>aws_region</code>, <code>table_name</code>, and <code>resource_tags</code>.</p>
<p>Terraform supports both <strong>primitive types</strong> (like <code>string</code>, <code>bool</code>) and <strong>complex types</strong> (<code>list</code>, <code>set</code>, <code>map</code>, <code>object</code>).</p>
<hr />
<h3 id="heading-maintf"><code>main.tf</code></h3>
<p>Define the resource that the module will create:</p>
<pre><code class="lang-plaintext">provider "aws" {
  region = var.aws_region
}

resource "aws_dynamodb_table" "this" {
  name         = var.table_name
  hash_key     = "messageid"
  billing_mode = "PAY_PER_REQUEST"

  attribute {
    name = "messageid"
    type = "S"
  }

  tags = var.resource_tags
}
</code></pre>
<p>Each module can have its own provider configuration. If needed, you can override it when invoking the module using the <code>providers</code> argument.</p>
<p>This example creates a DynamoDB table with a single string hash key and uses your provided tags.</p>
<p>You can always refer to <a target="_blank" href="https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/dynamodb_table">Terraform Registry</a> for all available resource arguments.</p>
<hr />
<h3 id="heading-outputstf"><code>outputs.tf</code></h3>
<p>Outputs let you expose key values from a module for use elsewhere:</p>
<pre><code class="lang-plaintext">output "DynamoARN" {
  value = aws_dynamodb_table.this.arn
}

output "BillMode" {
  value = aws_dynamodb_table.this.billing_mode
}

output "TableName" {
  value = aws_dynamodb_table.this.name
}
</code></pre>
<p>You can now reference these in your main Terraform configuration like:</p>
<pre><code class="lang-plaintext">module.mytable.DynamoARN
</code></pre>
<p>This pattern allows you to <strong>chain modules</strong> and build infrastructure incrementally while keeping your code base modular and reusable.</p>
<hr />
<h2 id="heading-bonus-special-module-parameters">Bonus: Special Module Parameters</h2>
<p>Terraform modules support some powerful optional arguments:</p>
<ul>
<li><p><code>count</code> and <code>for_each</code> — iterate over input variables to create multiple instances of a module dynamically.</p>
</li>
<li><p><code>depends_on</code> — enforce module execution order when dependencies exist between modules.</p>
</li>
<li><p><code>provider</code> — assign a specific provider configuration to a module.</p>
</li>
</ul>
<p>These features give you extra control over complex, multi-module deployments.</p>
<hr />
<h2 id="heading-in-summary">In Summary</h2>
<p>Using modules makes infrastructure as code <strong>cleaner, reusable, and testable</strong>. You can isolate, test, and share modules across projects or teams, improving collaboration and maintainability.</p>
]]></content:encoded></item><item><title><![CDATA[What is Terraform State]]></title><description><![CDATA[In this section, we discuss the concept of Terraform state. Terraform is responsible for creating or altering resources on a platform (for example…]]></description><link>https://blog.pulkitkapoor.com/what-is-terraform-state</link><guid isPermaLink="true">https://blog.pulkitkapoor.com/what-is-terraform-state</guid><category><![CDATA[Terraform]]></category><category><![CDATA[data-engineering]]></category><category><![CDATA[Devops]]></category><category><![CDATA[AWS]]></category><dc:creator><![CDATA[Pulkit]]></dc:creator><pubDate>Thu, 30 Jan 2025 05:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1761793642355/94bfa3f4-d027-4083-94d2-df27403010f3.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-objective">Objective</h2>
<p>In this section, we discuss the concept of <strong>Terraform state</strong>.</p>
<p>Terraform is responsible for creating or altering resources on a platform (for example, deploying pods to Kubernetes or creating resources on AWS). To manage this, Terraform needs some sort of <em>memory</em> — a record of the current state of resources at any given time.</p>
<p>This “memory” is called the <strong>Terraform state</strong>.</p>
<p>It’s useful because, based on what you ask Terraform to do, it can look up the current state from its state file and generate the so-called <code>terraform plan</code>. In short:</p>
<blockquote>
<p>The current state + desired configuration → Terraform Plan</p>
</blockquote>
<hr />
<h2 id="heading-where-is-terraform-state-stored">Where is Terraform State Stored?</h2>
<p>When you initialize a Terraform project with <code>terraform init</code>, the state is often stored locally in a file named <code>.tfstate</code>.</p>
<p>At first glance, that seems fine — but losing this file means losing Terraform’s memory. Without it, Terraform can no longer understand what resources exist or what to change. Hence, securing this file and avoiding accidental deletion is critical.</p>
<h3 id="heading-best-practices">Best Practices</h3>
<ul>
<li><p><strong>Store the state file remotely</strong> — for example, in <strong>AWS S3</strong>, so that your team can share infrastructure changes safely. Using <strong>S3 versioning and locking</strong> also adds extra security and recoverability.</p>
</li>
<li><p>Alternatively, store it in <strong>HashiCorp Cloud</strong>, which provides fine-grained access controls and additional convenience.</p>
</li>
</ul>
<hr />
<h2 id="heading-how-to-store-the-state-file-in-s3">How to Store the State File in S3</h2>
<p>To store your Terraform state remotely in <strong>S3</strong>, follow these steps:</p>
<ol>
<li><p><strong>Create an S3 bucket</strong> to hold the state file. Example: <code>tf-state-bucket</code></p>
</li>
<li><p><strong>Create a DynamoDB table</strong> to manage state locking. Example: <code>tf-state-table</code> with partition key <code>LockID</code></p>
</li>
<li><p>Ensure your Terraform IAM role has <code>GetObject</code> and <code>PutObject</code> permissions for the S3 bucket.</p>
</li>
</ol>
<p>Then, configure your Terraform backend in a file named <code>backend.tf</code>:</p>
<pre><code class="lang-plaintext">terraform {
  backend "s3" {
    bucket         = "tf-state-bucket"
    key            = "key-for-deployment"
    region         = "us-east-2"
    dynamodb_table = "tf-state-table"
  }
}
</code></pre>
<p>This tells Terraform to use S3 as the remote backend. All changes to your infrastructure will now be reflected in the S3 state file.</p>
<p>This is particularly important when using <strong>GitHub Actions</strong> or other CI/CD workflows, since those runs are ephemeral — they don’t persist local state. A remote S3 backend ensures consistent state management across environments and runs.</p>
]]></content:encoded></item><item><title><![CDATA[Basics of IaC with Terraform]]></title><description><![CDATA[hands on terraform]]></description><link>https://blog.pulkitkapoor.com/basics-of-iac-with-terraform</link><guid isPermaLink="true">https://blog.pulkitkapoor.com/basics-of-iac-with-terraform</guid><category><![CDATA[Terraform]]></category><category><![CDATA[Devops]]></category><category><![CDATA[data-engineering]]></category><dc:creator><![CDATA[Pulkit]]></dc:creator><pubDate>Wed, 15 Jan 2025 05:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1761793614553/f152389d-f5dd-41ca-ac30-254ef7646e3f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-introduction">Introduction</h2>
<p>In this series, we are going to focus our attention on <strong>Terraform</strong>. This series is different in the sense that I will be learning along as I write about it.</p>
<p>Terraform is an open-source <strong>Infrastructure as Code (IaC)</strong> tool designed by <strong>HashiCorp</strong>. It enables users to define and provision infrastructure and resources in a declarative manner using a high-level configuration language.</p>
<p>One key thing about Terraform that makes it so powerful is that it is a <strong>cloud-agnostic tool</strong>, allowing provisioning of infrastructure across <strong>100+ providers</strong> including AWS, Azure, and GCP.</p>
<hr />
<h2 id="heading-basics-first">Basics First</h2>
<p>Before diving into the code, let’s walk through some basics first. Every Terraform project follows a standard lifecycle:</p>
<pre><code class="lang-plaintext">Init → Write → Plan → Apply
</code></pre>
<p>This lifecycle is consistent across all Terraform projects and defines how infrastructure is initialized, configured, reviewed, and deployed.</p>
<hr />
<h2 id="heading-first-code-snippets">First Code Snippets</h2>
<p>Any Terraform project starts by defining the <strong>provider</strong>. Here’s a simple example:</p>
<pre><code class="lang-plaintext">// This defines and sets the provider for the Terraform project.
// Terraform will use this to download the required provider code
// and interact with the provider APIs.

provider "google" {
  credentials = file("creds.json")
  project     = "Hello-World"
  region      = "us-east-1"
}
</code></pre>
<p>Once the provider is set, you can start creating <strong>resources</strong>:</p>
<pre><code class="lang-plaintext">resource "aws_instance" "hello-instance" {
  ami           = "ami-id-here"
  instance_type = "t2-micro"
}
</code></pre>
<p>In the above snippet:</p>
<ul>
<li><p><code>aws_instance</code> defines the <strong>type</strong> of resource.</p>
</li>
<li><p><code>"hello-instance"</code> is the <strong>user-defined name</strong>.</p>
</li>
<li><p>You can later refer to it as <code>aws_instance.hello-instance</code>.</p>
</li>
</ul>
<p>There’s also a <strong>data block</strong>, which is useful for referencing shared configuration such as AMI IDs or instance types without repeating values across multiple resources. We’ll use it later when the need arises.</p>
<hr />
<h2 id="heading-example-1-create-an-ec2-instance">Example 1 — Create an EC2 Instance</h2>
<p>In this example, we’ll create an <strong>EC2 instance</strong> using Terraform. To set up Terraform and AWS CLI, follow <a target="_blank" href="https://www.youtube.com/watch?v=QhmFnlbbwP4">this video tutorial</a>. I personally prefer using <strong>WSL on Windows</strong> for development.</p>
<hr />
<h2 id="heading-solution-code">Solution Code</h2>
<p>If required, you may need to read up about <strong>subnets</strong> and <strong>networking</strong> first.</p>
<pre><code class="lang-plaintext">// Setup the provider and mention the profile Terraform should use for login
provider "aws" {
  region  = "us-east-1"
  profile = "terraform"
}

// Step 1: Create a VPC for development
resource "aws_vpc" "vpcdev" {
  cidr_block = "10.0.0.0/16"

  tags = {
    environment = "development"
  }
}

// Step 2: Create a subnet in the VPC created above
resource "aws_subnet" "devsubnet1" {
  vpc_id            = aws_vpc.vpcdev.id
  cidr_block        = "10.0.1.0/24"
  availability_zone = "us-east-1a"

  depends_on = [aws_vpc.vpcdev]
}

// Step 3: Create an EC2 instance in the subnet
resource "aws_instance" "devvm1" {
  ami           = "ami-0be2609ba883822ec"
  instance_type = "t2.micro"
  subnet_id     = aws_subnet.devsubnet1.id

  depends_on = [aws_subnet.devsubnet1]
}
</code></pre>
<hr />
<h3 id="heading-references">References</h3>
<ul>
<li><p><a target="_blank" href="https://www.youtube.com/watch?v=bGDMeD6kOz0">AWS VPC &amp; Subnets</a></p>
</li>
<li><p><a target="_blank" href="https://registry.terraform.io/providers/-/aws/latest/docs/resources/subnet">AWS Subnets Docs</a></p>
</li>
<li><p><a target="_blank" href="https://www.youtube.com/results?search_query=understanding+CIDR+subnets+aws">Understanding CIDR and Subnets</a></p>
</li>
</ul>
<hr />
<p><strong>Tags:</strong> <code>aws</code>, <code>basics</code>, <code>getstarted</code>, <code>iac</code>, <code>terraform</code><strong>Category:</strong> <code>Infra as Code</code></p>
]]></content:encoded></item><item><title><![CDATA[Connecting Spark 2.4+ to Hive 1.2 via JDBC]]></title><description><![CDATA[Bridging backward compatibility gaps between legacy Hive and modern Spark]]></description><link>https://blog.pulkitkapoor.com/connecting-spark-24-to-hive-12-via-jdbc</link><guid isPermaLink="true">https://blog.pulkitkapoor.com/connecting-spark-24-to-hive-12-via-jdbc</guid><category><![CDATA[remotehive]]></category><category><![CDATA[hivejdbc]]></category><category><![CDATA[debugging]]></category><category><![CDATA[spark]]></category><category><![CDATA[hive]]></category><category><![CDATA[JDBC]]></category><category><![CDATA[dataengineering]]></category><category><![CDATA[data-engineering]]></category><dc:creator><![CDATA[Pulkit]]></dc:creator><pubDate>Wed, 01 Jan 2025 05:00:00 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1761793212799/f515320c-e222-4a59-8256-3ac12c96b9c6.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="heading-scenario">🧩 Scenario</h2>
<p>Apache Spark remains the de facto framework for large-scale data processing. Since its release, Spark has evolved rapidly—so has Apache Hive. But one persistent challenge with Hive is the <em>lack of backward compatibility</em> across its APIs.</p>
<p>If your production environment uses the latest Hive + Hadoop setup and you need to connect Spark to an older <strong>Hive 1.2</strong> instance, you’ll soon hit compatibility walls. So, how can we make it work?</p>
<hr />
<h2 id="heading-jdbc-to-the-rescue">☕ JDBC to the Rescue</h2>
<p>Incompatibility between <strong>Spark &gt; 2.4</strong> and <strong>Hive &lt; 2.0</strong> arises primarily from protocol and configuration changes.</p>
<ul>
<li><p><strong>Hive &lt; 2.0</strong> uses <code>hive-service.jar</code> to implement the Thrift protocol.</p>
</li>
<li><p><strong>Hive ≥ 2.0</strong> migrated to <code>hive-rpc-service.jar</code>.</p>
</li>
</ul>
<p>These architectural differences break backward compatibility, making direct integration with legacy Hive difficult.</p>
<blockquote>
<p><em>Backward compatibility in software is where ancient relics and cutting-edge tech awkwardly high-five each other.</em></p>
</blockquote>
<p>Fortunately, Hive supports multiple connection protocols — including <strong>JDBC</strong>, which allows Java (and by extension, Spark) to interact with HiveServer2 for query execution and table operations.</p>
<hr />
<h2 id="heading-required-jars-for-hive-12-jdbc">🧱 Required JARs for Hive 1.2 JDBC</h2>
<p>To connect Spark 2.4+ to Hive 1.2 via JDBC, you’ll need the following JARs in your Spark classpath:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td><strong>JAR</strong></td><td><strong>Version</strong></td><td><strong>Purpose</strong></td></tr>
</thead>
<tbody>
<tr>
<td><code>hive-jdbc-1.2.1.jar</code></td><td>1.2.1</td><td>Contains the driver class <code>org.apache.hive.jdbc.HiveDriver</code></td></tr>
<tr>
<td><code>hive-shims-common-1.2.1.jar</code>, <code>hive-shims-0.23-1.2.1.jar</code></td><td>1.2.1</td><td>Provides compatibility shims and Kerberos auth support</td></tr>
<tr>
<td><code>libthrift-0.9.3.jar</code></td><td>0.9.3</td><td>Implements Thrift communication protocol</td></tr>
<tr>
<td><code>hive-service-1.2.jar</code></td><td>1.2</td><td>Contains Thrift service definitions for Hive &lt; 2.0</td></tr>
<tr>
<td><code>hive-serde-1.2.1.jar</code></td><td>1.2.1</td><td>Supports serialization/deserialization logic</td></tr>
</tbody>
</table>
</div><hr />
<h2 id="heading-required-modifications-for-spark-24-compatibility">🛠️ Required Modifications for Spark 2.4 Compatibility</h2>
<p>Using Hive 1.2 JDBC drivers directly with Spark 2.4.8 (or newer) can lead to runtime errors. Below are the two common issues and their workarounds.</p>
<hr />
<h3 id="heading-error-1-unknown-hadoop-version-3">❌ Error 1: <em>Unknown Hadoop Version 3</em></h3>
<p><strong>Error message:</strong></p>
<pre><code class="lang-plaintext">Illegal Hadoop Version: 3.x (expected A.B.* format)
</code></pre>
<p><strong>Root cause:</strong><br />Found in <code>hive-shims-common.jar → ShimLoader.java</code>, the method <code>getMajorVersion()</code> doesn’t recognize Hadoop 3.x.</p>
<pre><code class="lang-java"><span class="hljs-comment">// Original code</span>
<span class="hljs-keyword">switch</span> (Integer.parseInt(parts[<span class="hljs-number">0</span>])) {
  <span class="hljs-keyword">case</span> <span class="hljs-number">1</span>:
    <span class="hljs-keyword">return</span> HADOOP20SVERSIONNAME;
  <span class="hljs-keyword">case</span> <span class="hljs-number">2</span>:
    <span class="hljs-keyword">return</span> HADOOP23VERSIONNAME;
  <span class="hljs-keyword">default</span>:
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalArgumentException(<span class="hljs-string">"Unrecognized Hadoop major version number: "</span> + vers);
}
</code></pre>
<p><strong>Fix:</strong><br />Modify the <code>default</code> block to return a valid version instead of throwing an exception:</p>
<pre><code class="lang-java"><span class="hljs-keyword">default</span>:
    <span class="hljs-keyword">return</span> HADOOP23VERSIONNAME; <span class="hljs-comment">// Cheat: treat 3.x as Hadoop 2.3</span>
</code></pre>
<p>Then recompile the JAR:</p>
<pre><code class="lang-bash">mvn clean install &amp;&amp; mvn package
</code></pre>
<p>This quick patch allows Hive 1.2 shims to function under Hadoop 3.x.</p>
<hr />
<h3 id="heading-error-2-unsupported-method-hivestatementsetquerytimeout">❌ Error 2: <em>Unsupported Method HiveStatement.setQueryTimeout()</em></h3>
<p><strong>Error message:</strong></p>
<pre><code class="lang-plaintext">java.sql.SQLException: Method not supported
</code></pre>
<p><strong>Root cause:</strong><br />In <code>HiveStatement.java</code>, the method <code>setQueryTimeout</code> throws an exception when invoked by Spark 2.4+.</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setQueryTimeout</span><span class="hljs-params">(<span class="hljs-keyword">int</span> seconds)</span> <span class="hljs-keyword">throws</span> SQLException </span>{
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> SQLException(<span class="hljs-string">"Method not supported"</span>);
}
</code></pre>
<p><strong>Fix:</strong><br />Comment out or remove the <code>throw</code> statement:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setQueryTimeout</span><span class="hljs-params">(<span class="hljs-keyword">int</span> seconds)</span> <span class="hljs-keyword">throws</span> SQLException </span>{
    <span class="hljs-comment">// No-op to maintain compatibility</span>
}
</code></pre>
<p>Rebuild the JAR to produce your patched version. Once both fixes are applied, your Hive 1.2 driver will operate smoothly with Spark 2.4.</p>
<hr />
<h2 id="heading-launching-spark-with-hive-12-jdbc">🚀 Launching Spark with Hive 1.2 JDBC</h2>
<p>After preparing all the patched JARs (e.g., in a directory named <code>hive1.2jars</code>), you can start <code>spark-shell</code> as follows:</p>
<pre><code class="lang-bash"><span class="hljs-built_in">cd</span> hive1.2jars

spark-shell \
  --master yarn \
  --jars hive-jdbc.jar,hive-shims-common.jar,hive-shims-0.23.0.jar,libthrift.jar,hive-serde.jar \
  --conf spark.driver.extraClassPath=hive-jdbc.jar:hive-shims-common.jar:hive-shims-0.23.0.jar:libthrift.jar:hive-serde.jar \
  --conf spark.executor.extraClassPath=hive-jdbc.jar:hive-shims-common.jar:hive-shims-0.23.0.jar:libthrift.jar:hive-serde.jar \
  --conf spark.driver.userClassPathFirst=<span class="hljs-literal">true</span> \
  --conf spark.executor.userClassPathFirst=<span class="hljs-literal">true</span>
</code></pre>
<hr />
<h2 id="heading-kerberos-amp-jaas-configuration">🔐 Kerberos &amp; JAAS Configuration</h2>
<p>When connecting to HiveServer2 in a secure (Kerberized) environment, the Hive JDBC driver may fail to automatically obtain service tokens.<br />You’ll need to manually configure JAAS for authentication:</p>
<pre><code class="lang-bash">--files ./jaas.conf \
--conf spark.executor.extraJavaOptions=<span class="hljs-string">"-Djavax.security.auth.useSubjectCredsOnly=false -Djava.security.auth.login.config=./jaas.conf"</span> \
--conf spark.security.credentials.hiveserver2.enabled=<span class="hljs-literal">true</span>
</code></pre>
<p>Ensure that <code>jaas.conf</code> defines the correct <code>serviceName="hiveserver2"</code> entry for your environment.</p>
<hr />
<h2 id="heading-summary">✅ Summary</h2>
<p>By applying minor source-level patches to the Hive 1.2 JDBC driver and shims, you can connect modern Spark clusters (Hadoop 3.x) to legacy Hive instances without major rewrites.<br />This approach is especially useful for <strong>data migration, legacy audits, or cross-version compatibility testing</strong>.</p>
<hr />
<h2 id="heading-references">🔗 References</h2>
<ol>
<li><p><a target="_blank" href="https://support.tibco.com/s/article/How-to-resolve-Illegal-Hadoop-Version-Unknown-expected-A-B-format">TIBCO Support – Illegal Hadoop Version Error</a></p>
</li>
<li><p><a target="_blank" href="https://stackoverflow.com/questions/62938360/unrecognised-hadoop-major-version-1-2-1-error-hive-and-impala-jdbc-connection">StackOverflow – Unrecognized Hadoop Major Version Error</a></p>
</li>
<li><p><a target="_blank" href="https://community.progress.com/s/article/setquerytimeout-is-not-working-with-apache-hive-jdbc-driver">Progress Community – setQueryTimeout Not Working</a></p>
</li>
<li><p><a target="_blank" href="https://querysurge.zendesk.com/hc/en-us/articles/115001218863-Setting-Up-a-Hive-Connection-with-Kerberos-using-Apache-JDBC-Drivers-Windows-">QuerySurge – Setting Up Hive Connection with Kerberos</a></p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Understanding Amazon Redshift Data Sharing Features]]></title><description><![CDATA[AWS Redshift is the data-warehousing solution provided by Amazon Web Services. As part of the Datawarehouse offering, Amazon Redshift provides a very…]]></description><link>https://blog.pulkitkapoor.com/understanding-amazon-redshift-data-sharing-features</link><guid isPermaLink="true">https://blog.pulkitkapoor.com/understanding-amazon-redshift-data-sharing-features</guid><category><![CDATA[AWS]]></category><category><![CDATA[Amazon redshift]]></category><category><![CDATA[Data Sharing]]></category><category><![CDATA[Cloud]]></category><category><![CDATA[Data warehouse]]></category><category><![CDATA[data-engineering]]></category><dc:creator><![CDATA[Pulkit]]></dc:creator><pubDate>Mon, 11 Nov 2024 02:44:12 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1731255011654/966cd3a5-ddd3-4065-8d3c-0401f1e5c1e9.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<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="heading-what-is-data-sharing">What is Data Sharing?</h2>
<h3 id="heading-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="heading-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="heading-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="heading-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>
<pre><code class="lang-sql"><span class="hljs-comment">-- As Admin User</span>
<span class="hljs-comment">-- Create datashare</span>
<span class="hljs-keyword">CREATE</span> DATASHARE shareData;
<span class="hljs-keyword">ALTER</span> DATASHARE shareData <span class="hljs-keyword">ADD</span> <span class="hljs-keyword">SCHEMA</span> a_schema;                        <span class="hljs-comment">-- Add target schema</span>
<span class="hljs-keyword">ALTER</span> DATASHARE shareData <span class="hljs-keyword">ADD</span> <span class="hljs-keyword">TABLE</span> a_schema.a_table;                 <span class="hljs-comment">-- Add required tables to share</span>

<span class="hljs-comment">-- Grant permissions to required consumers</span>
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">USAGE</span> <span class="hljs-keyword">ON</span> DATASHARE datashareDeviceLogs <span class="hljs-keyword">TO</span> NAMESPACE <span class="hljs-string">'CONSUMER_NAMESPACE_ID'</span>;     <span class="hljs-comment">-- Share with consumer namespace</span>
DESC DATASHARE shareData;

<span class="hljs-comment">-- Needed if target cluster is set as publicly accessible</span>
<span class="hljs-keyword">ALTER</span> DATASHARE shareData <span class="hljs-keyword">SET</span> PUBLICACCESSIBLE = <span class="hljs-literal">TRUE</span>;                

<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">ALTER</span>, <span class="hljs-keyword">SHARE</span> <span class="hljs-keyword">ON</span> DATASHARE shareData <span class="hljs-keyword">TO</span> <span class="hljs-keyword">GROUP</span> the_group1;        <span class="hljs-comment">-- To allow group to manage this datashare</span>
<span class="hljs-keyword">select</span> * <span class="hljs-keyword">from</span> svv_datashare_privileges;                               <span class="hljs-comment">-- see who is allowed to alter datashares other than admin</span>
</code></pre>
<h3 id="heading-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>
<pre><code class="lang-sql"><span class="hljs-comment">-- As Admin User</span>
<span class="hljs-comment">-- check for incoming datashares</span>
<span class="hljs-keyword">SHOW</span> DATASHARES;
DESC DATASHARE shareData OF NAMESPACE 'PRODUCER_NAMESPACE_ID';

<span class="hljs-comment">-- Create a database to interact with the shared objects</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">DATABASE</span> sharedData <span class="hljs-keyword">WITH</span> PERMISSIONS <span class="hljs-keyword">FROM</span> DATASHARE shareData <span class="hljs-keyword">OF</span> NAMESPACE <span class="hljs-string">'PRODUCER_NAMESPACE_ID'</span>;

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

<span class="hljs-comment">-- Create external schema poining to the datashare's database</span>
<span class="hljs-keyword">CREATE</span> <span class="hljs-keyword">EXTERNAL</span> <span class="hljs-keyword">SCHEMA</span> <span class="hljs-keyword">shared</span> <span class="hljs-keyword">FROM</span> REDSHIFT <span class="hljs-keyword">DATABASE</span> sharedData <span class="hljs-keyword">SCHEMA</span> <span class="hljs-string">'a_schema'</span>;
<span class="hljs-comment">-- Grant permissions</span>
<span class="hljs-comment">-- Usage access for datashare source schema (Note, we are not giving access to datashare itsself)                                </span>
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">USAGE</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">SCHEMA</span> sharedData.a_schema <span class="hljs-keyword">TO</span> <span class="hljs-keyword">GROUP</span> a_group;       
<span class="hljs-comment">-- Access for external schema</span>
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">USAGE</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">SCHEMA</span> shared.a_table <span class="hljs-keyword">TO</span> <span class="hljs-keyword">GROUP</span> a_group;  
<span class="hljs-keyword">GRANT</span> <span class="hljs-keyword">SELECT</span> <span class="hljs-keyword">ON</span> <span class="hljs-keyword">ALL</span> <span class="hljs-keyword">TABLES</span> <span class="hljs-keyword">IN</span> <span class="hljs-keyword">SCHEMA</span> sharedData.a_schema <span class="hljs-keyword">TO</span> <span class="hljs-keyword">TO</span> <span class="hljs-keyword">GROUP</span> a_group;            <span class="hljs-comment">-- [PRIVELEGE] to target datashare table</span>
</code></pre>
<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="heading-limitations-for-data-sharing">Limitations for data sharing</h3>
<p>The following are limitations when working with datashares in Amazon Redshift:</p>
<ul>
<li><p>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.</p>
</li>
<li><p>Amazon Redshift doesn't support adding external schemas, tables, or late-binding views on external tables to datashares.</p>
</li>
<li><p>Consumers can't add datashare objects to another datashare. Additionally, consumers can't add views referencing datashare objects to another datashare.</p>
</li>
<li><p>Amazon Redshift doesn't support sharing stored procedures through datashares.</p>
</li>
</ul>
]]></content:encoded></item></channel></rss>