<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Reza Amini on Medium]]></title>
        <description><![CDATA[Stories by Reza Amini on Medium]]></description>
        <link>https://medium.com/@amini.reza1379?source=rss-fe5f66cb0f90------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Lh37pOVKaJB7ZCK_</url>
            <title>Stories by Reza Amini on Medium</title>
            <link>https://medium.com/@amini.reza1379?source=rss-fe5f66cb0f90------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 07:47:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amini.reza1379/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Harnessing the Power of Spark Operator: Orchestrating Data Pipelines with Airflow and Git]]></title>
            <link>https://medium.com/@amini.reza1379/harnessing-the-power-of-spark-operator-orchestrating-data-pipelines-with-airflow-and-git-167fcc2d9260?source=rss-fe5f66cb0f90------2</link>
            <guid isPermaLink="false">https://medium.com/p/167fcc2d9260</guid>
            <category><![CDATA[data-engineering]]></category>
            <category><![CDATA[spark-operator]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[spark]]></category>
            <dc:creator><![CDATA[Reza Amini]]></dc:creator>
            <pubDate>Wed, 25 Sep 2024 07:52:10 GMT</pubDate>
            <atom:updated>2024-09-25T07:52:10.975Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ket6WRdqdKsA7BR-Xv7FQ.png" /><figcaption>Genrated by ChatGPT 4o</figcaption></figure><h3>1. Introduction</h3><p>Suppose you’re working in industries like e-commerce, q-commerce, FMCG, or any other data-intensive field and looking to build scalable data infrastructure. In that case, <strong>Apache Spark</strong> is likely an essential tool. However, one common issue with Spark is that it can consume many resources (CPU, RAM), even when idle. That’s where<a href="https://operatorhub.io/operator/spark-gcp"> <strong>Spark Operator</strong></a> (Spark <a href="https://kubernetes.io/docs/concepts/extend-kubernetes/api-extension/custom-resources/">CRD</a> on Kubernetes) comes in — it allows resources to be allocated dynamically when a pipeline is received, making it much more efficient.</p><p>Creating a flexible workflow for Spark pipelines isn’t easy with Spark Operator, especially for batch processing. In this article, We’ll see how simplifying the process of working with Spark Operator makes a data engineer&#39;s life easier.</p><p>At <a href="https://www.linkedin.com/company/snappshop/mycompany/"><em>SnappShop</em></a>, We developed a robust workflow for managing and developing Spark pipelines in production. This workflow has made it easy for all data engineers on our team to run and manage Spark pipelines efficiently, without needing to worry about the underlying infrastructure.</p><p>For those interested in more details or sample code, you can find a complete example related to this blog in the following <a href="https://github.com/rezaaminimajd/spark-operator-and-airflow"><strong>GitHub</strong></a> project</p><h3>2. A Quick Look at Airflow, Git, and Spark Operator</h3><p>Before we dive into it, let&#39;s have a quick detour of the tools in play.</p><ul><li><a href="https://airflow.apache.org/"><strong>Airflow</strong></a>: Apache Airflow is an open-source platform used to programmatically create, schedule, and monitor workflows. It allows you to define workflows as code (DAGs), ensuring easy automation of tasks, managing dependencies, and tracking progress, all while providing a user-friendly interface for monitoring and management.</li><li><a href="https://git-scm.com/"><strong>Git</strong></a>: Git is a distributed version control system that helps developers track changes in their code over time. It allows multiple people to collaborate on projects by managing versions of code, enabling branching, merging, and maintaining a detailed history of changes, ensuring smooth collaboration and version management in software development.</li><li><strong>Spark Operator</strong>: Now, the star of the show — <strong>Spark Operator</strong>! The Spark Operator is a Kubernetes extension that simplifies the deployment, management, and monitoring of Apache Spark applications on Kubernetes. It uses Kubernetes’ native features, like CRDs (Custom Resource Definitions), to run Spark jobs in a dynamic and scalable way, allocating resources as needed and automating the management of Spark clusters, making it easier to integrate Spark with Kubernetes environments.</li></ul><p><em>We use the GitLab Container Registry to push and pull our base images for Airflow and Spark pipelines. A container registry is a centralized place where container images are stored and managed, making it easy to distribute and deploy images across different environments.</em></p><p>Together, these three tools form a dream team for building, versioning, and orchestrating reliable data pipelines. And the best part? Automating batch jobs becomes way easier when you put them all together.</p><h3>3. Understanding the Core Challenges</h3><p>When working with Spark Operator on Kubernetes, several challenges can complicate the process of managing Spark pipelines efficiently:</p><p><strong>1. Job Submission Complexity:</strong> In Apache Spark, you can typically submit jobs directly to a Spark cluster using the <em>spark-submit</em> command, which makes it easy to run jobs without needing extra configuration files. However, with Spark Operator on Kubernetes, you can’t submit jobs this way. Instead, you need to create a YAML configuration file for each pipeline that defines how the job should run on Kubernetes. This adds complexity to the process compared to the direct submission method.</p><p><strong>2. Dependency on Docker Images</strong>: Each YAML file requires a base Docker image to run the job, and your Spark code must be included in this image. Additionally, whenever you write new code or update existing code, you must also ensure that all dependencies are installed within the Docker image, which can lead to repetitive work every time something changes.</p><p><strong>3. Airflow Integration:</strong> For scheduling, we use Airflow, but this also brings its own set of challenges. All DAG files must be included in the Airflow image, and just like with Spark, the necessary dependencies for the DAGs need to be installed within the Airflow image.</p><h3><strong>4. Three Essential Flows for a Smooth Data Pipeline</strong></h3><p>These flows ensure that my Airflow DAGs are always in sync, dependencies are updated smoothly, and Spark applications are deployed seamlessly via Kubernetes. Let’s break it down:</p><ul><li><strong>Flow 1: Syncing Airflow DAGs, Updating Dependencies, and Managing Images with Git and Container Registry</strong></li></ul><p>In our setup, Airflow is running on Kubernetes, and we use Helm to manage its deployment. To keep our DAGs up to date, we leverage GitSync, which ensures that the latest code is always pulled from our GitLab repository. Any changes made to the DAGs are quickly reflected in Airflow without manual updates.</p><p>Here’s the configuration of GitSync in our Helm values:</p><pre>gitSync:<br>  enabled: true<br>  repo: https://gitlab.com/data/project.git<br>  branch: master<br>  rev: HEAD<br>  depth: 1<br>  maxFailures: 0<br>  subPath: &quot;dags&quot;<br>  credentialsSecret: git-credentials<br>  period: 5s<br>  wait: ~</pre><p>For managing dependencies, we install the necessary dependencies, which are all defined in a <em>requirements.txt</em> file on the Airflow Docker Image. Here’s a quick look at the Docker setup:</p><pre>FROM apache/airflow:2.9.1 <br><br>ENV PIP_NO_PARALLEL=1<br>ENV TZ=&quot;Asia/Tehran&quot;<br><br>RUN pip config --user set global.progress_bar off<br><br>COPY ./docker/airflow/requirements.txt /<br><br>RUN pip install --no-cache-dir &quot;apache-airflow==2.9.1&quot; -r /requirements.txt</pre><p>Once the <em>requirements.txt</em> is updated, the following CI pipeline is triggered:</p><pre>build_airflow_image:<br>  stage: build<br>  tags:<br>    - docker<br>    - build<br>    - production<br>  script:<br>    - echo $CI_JOB_TOKEN<br>    - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN gitlab.com<br>    - docker build --pull -t $CONTAINER_AIRFLOW_IMAGE -f docker/airflow/Dockerfile .<br>    - docker push $CONTAINER_AIRFLOW_IMAGE<br>  only:<br>    changes:<br>      - docker/airflow/requirements.txt<br>    refs:<br>      - master</pre><p>This pipeline builds the Airflow image, pushes it to the GitLab container registry, and ensures that all dependencies are included. Once the image is ready, we deploy it to Kubernetes using Helm on the CD Pipeline:</p><pre>deploy_with_helm:<br>  image: gitlab.com/common-images/helm:3.9.4<br>  stage: deploy<br>  variables:<br>    APP_ENV: &#39;production&#39;<br>  tags:<br>    - kubernetes<br>    - deploy<br>    - production<br>  script:<br>    - helm repo add --username $REPO_USERNAME --password $REPO_TOKEN repo $REPO<br>    - helm repo update<br>    - helm upgrade airflow repo/airflow --install -n namespace -f ./helm/values.yaml --set-string images.airflow.repository=$CI_REGISTRY_IMAGE,images.airflow.tag=$CI_COMMIT_SHA,registry.secretName=registry-secret<br>  only:<br>    changes:<br>      - docker/airflow/requirements.txt<br>    refs:<br>      - master</pre><p>With this, our updated Airflow instance is redeployed, and any changes to the dependencies are automatically applied. This makes managing our Airflow setup much simpler and ensures that everything is up-to-date.</p><ul><li><strong>Flow 2: Syncing Spark Codes, Updating Dependencies, and Managing Images with Git and Container Registry</strong></li></ul><p>We always need the latest image to include the most up-to-date code from the master branch. Whenever there’s a change, we create a new Spark image that incorporates all the updates and push it to the container registry, ensuring that the latest version is always available for deployment:</p><pre>FROM apache/spark:3.5.0<br><br>COPY ./docker/spark/requirements.txt /requirements.txt<br><br>RUN pip install --no-cache-dir -r /requirements.txt<br><br>COPY ./dags/spark_applications /opt/spark/dags/spark_applications<br><br>WORKDIR /opt/spark</pre><pre>build_spark_image:<br>  stage: build<br>  tags:<br>    - docker<br>    - build<br>    - production<br>  script:<br>    - echo $CI_JOB_TOKEN<br>    - docker login -u gitlab-ci-token -p $CI_JOB_TOKEN gitlab.com<br>    - docker build --pull -t $CONTAINER_SPARK_IMAGE -f docker/spark/Dockerfile .<br>    - docker push $CONTAINER_SPARK_IMAGE<br>  only:<br>    changes:<br>      - dags/spark_applications/*<br>      - docker/spark/*<br>    refs:<br>      - master</pre><p>By automating these builds, we ensure that all updates — whether they’re in Airflow or Spark — are deployed efficiently, with minimal manual intervention.</p><ul><li><strong>Flow 3: Implementing the DAG and Running Spark Applications on Kubernetes</strong></li></ul><p>Now that we’ve covered syncing Airflow DAGs and updating dependencies, let’s move on to the next flow:</p><p>Here’s a quick overview of the structure of our codebase:</p><pre>dags/<br>    ├── custom_operators/<br>        ├── image_reader.py<br>        └── yaml_renderer.py<br>    ├── k8s_template/<br>        └── spark-application.j2<br>    ├── spark_applications/<br>        └── example_pyspark_code.py<br>    └── example_dag.py</pre><h4>Custom Operators for Seamless Spark Integration</h4><p>To make this whole process of deploying Spark applications on Kubernetes even smoother, We wrote a couple of custom Airflow operators to handle key tasks. These operators make it easy to keep everything in sync, from fetching the latest Spark image to dynamically generating the YAML configuration for the Spark Operator.</p><ul><li><a href="https://github.com/rezaaminimajd/spark-operator-and-airflow/blob/main/dags/custom_operators/image_reader.py"><strong>ImageReaderOperator</strong></a><strong>: Fetching the Latest Spark Image</strong></li></ul><p>As mentioned earlier, to ensure our applications run with the latest updates, we need to retrieve the most up-to-date image that’s been built and pushed to the container registry.</p><p>We created the ImageReaderOperator. It’s responsible for fetching the latest Spark image from the GitLab registry, which gets updated each time the Spark code is modified. This operator pulls the latest image tag and stores it in Airflow’s XCom (a mechanism that allows tasks to exchange small amounts of data during DAG execution), so other tasks in the DAG can use it.</p><p>Here’s how We use it in my DAG:</p><pre>latest_image = ImageReaderOperator(<br>    task_id=&#39;get-latest-spark-image&#39;<br>)</pre><ul><li><a href="https://github.com/rezaaminimajd/spark-operator-and-airflow/blob/main/dags/custom_operators/yaml_renderer.py"><strong>RenderYamlOperator</strong></a><strong>: Preparing the YAML for Spark Applications</strong></li></ul><p>As mentioned in the core challenges section, one of the issues is needing a separate YAML file for each pipeline. To address this, we use a base YAML file in Jinja format, which is dynamically populated with values passed from each DAG using a custom operator.</p><p>Next up, We created the RenderYamlOperator, which uses a Jinja template to generate the YAML configuration for the Spark Operator. The template, spark-application.j2, contains all the necessary specifications for running a Spark job on Kubernetes, such as the number of executors, memory allocation, environment variables, and more.</p><p>Here’s an example of what the <em>spark-application.j2</em> template looks like:</p><pre>apiVersion: sparkoperator.k8s.io/v1beta2<br>kind: SparkApplication<br>metadata:<br>  name: {{ name }}<br>  namespace: namespace<br>spec:<br>  nodeSelector:<br>    node-role.kubernetes.io/worker: worker<br>  type: Python<br>  image: {{ image }}<br>  mainApplicationFile: {{ mainApplicationFile }}<br>  sparkVersion: {{ sparkVersion }}<br>  driver:<br>    cores: {{ driver_cores }}<br>    memory: {{ driver_memory }}<br>  env:<br>    {% for key, value in env_vars.items() %}<br>    - name: {{ key }}<br>      value: &quot;{{ value }}&quot;<br>    {% endfor %}<br>  executor:<br>    cores: {{ executor_cores }}<br>    memory: {{ executor_memory }}<br>    instances: {{ executor_instance }}<br>  env:<br>    {% for key, value in env_vars.items() %}<br>    - name: {{ key }}<br>      value: &quot;{{ value }}&quot;<br>    {% endfor %}<br>  sparkConf:<br>    &quot;spark.jars.packages&quot;: &quot;{{ spark_jars }}&quot;</pre><p>When We call the RenderYamlOperator, it fills in all the necessary values, such as the Spark version, driver and executor configurations, and environment variables. Here’s how We use it in the DAG:</p><pre>    spark_values = {<br>        &#39;name&#39;: &#39;example-job&#39;,<br>        &#39;image&#39;: &#39;gitlab.com/data/project/spark:{latest_tag}&#39;,<br>        &#39;mainApplicationFile&#39;: &#39;local:///opt/spark/spark_applications/example_pyspark_code.py&#39;,<br>        &#39;sparkVersion&#39;: &#39;3.5.0&#39;,<br>        &#39;spark_jars&#39;: &#39;com.github.housepower:clickhouse-native-jdbc-shaded:2.7.1&#39;,  # and other jars<br>        &#39;driver_cores&#39;: 2,<br>        &#39;driver_memory&#39;: &#39;4g&#39;,<br>        &#39;executor_cores&#39;: 2,<br>        &#39;executor_memory&#39;: &#39;4g&#39;,<br>        &#39;executor_instance&#39;: 2,<br>        &#39;env_vars&#39;: {<br>            &quot;DATABASE_USER&quot;: database_connection.login,<br>            &quot;DATABASE_PASSWORD&quot;: database_connection.password,<br>            &quot;DATABASE_DATABASE&quot;: database_connection.schema,<br>            &quot;DATABASE_HOST&quot;: database_connection.host,<br>            &quot;DATABASE_PORT&quot;: database_connection.port<br>        }<br>    }</pre><pre>render_yaml = RenderYamlOperator(<br>    task_id=&quot;render-yaml-operator&quot;,<br>    values=spark_values,<br>    latest_image_task_id=&#39;get-latest-spark-image&#39;,<br>    template_path=&quot;spark-application.j2&quot;,<br>    xcom_key=&#39;example-pyspark-yaml&#39;<br>)</pre><p>The <em>spark_values</em> dictionary holds all the values that need to be filled into the template. Once rendered, the resulting YAML file is stored in XCom.</p><p>it also uses ‘<em>latest_image_task_id’</em> to pull the latest Spark image tag from XCom of the previous task. The rendered result is then pushed into XCom under the key <em>‘example-pyspark-yaml’</em>.</p><p>For more details, here’s a sample of the PySpark code used in one of our jobs:</p><pre>import os<br><br>from pyspark.sql import SparkSession<br><br>database_user = os.getenv(&quot;DATABASE_USER&quot;)<br>database_password = os.getenv(&quot;DATABASE_PASSWORD&quot;)<br>database_table = os.getenv(&quot;DATABASE_TABLE&quot;)<br>database_host = os.getenv(&quot;DATABASE_HOST&quot;)<br>database_port = os.getenv(&quot;DATABASE_PORT&quot;)<br><br>spark = SparkSession.builder.appName(&quot;ExampleJob&quot;).getOrCreate()<br><br># Your processing logic here...</pre><ul><li><strong>Submitting the Spark Job with </strong><a href="https://airflow.apache.org/docs/apache-airflow-providers-cncf-kubernetes/stable/_api/airflow/providers/cncf/kubernetes/operators/spark_kubernetes/index.html"><strong>SparkKubernetesOperator</strong></a></li></ul><p>Finally, to submit the Spark job, We use the <strong>SparkKubernetesOperator</strong>. This operator takes the rendered YAML and sends it to the Spark Operator on Kubernetes. It pulls the YAML from XCom, ensuring that the right configuration is applied.</p><p>Here’s how the submission works in the DAG:</p><pre>submit = SparkKubernetesOperator(<br>    task_id=&#39;submit-spark-job&#39;,<br>    namespace=&#39;namespace&#39;,<br>    application_file=&quot;{{ task_instance.xcom_pull(task_ids=&#39;render-yaml-operator&#39;, key=&#39;example-pyspark-yaml&#39;) }}&quot;,<br>    kubernetes_conn_id=&#39;kubernetes-connection-id&#39;,<br>    get_logs=True<br>)</pre><p>The <em>application_file</em> parameter fetches the rendered YAML from XCom, and the operator applies it to the Kubernetes. Once the job is applied, Kubernetes runs the Spark job according to the specified configuration</p><h3><strong>Wrapping It Up</strong></h3><p>By building these flows, We’ve been able to automate the entire process of deploying Spark applications on Kubernetes. everything is integrated into a smooth workflow that runs on Airflow.</p><p><strong>TL;DR</strong>: This post explores how to efficiently manage Apache Spark pipelines on Kubernetes using Spark Operator, Airflow, and GitLab. We address challenges like handling YAML configurations for each pipeline, managing Docker images with code and dependencies, and integrating Airflow for scheduling. Using custom operators like ImageReaderOperator and RenderYamlOperator, we automate the pipeline deployment process, keeping DAGs and images up to date while simplifying job submission. These solutions simplify batch processing and make managing Spark applications on Kubernetes more effective.</p><p><strong>Contact Information</strong></p><p>If you’d like to discuss more about Spark pipelines, Airflow, or Kubernetes, feel free to connect with me on <a href="https://www.linkedin.com/in/rezaaminimajd/">LinkedIn</a> or reach out via <a href="/service/mailto:amini.reza1379@gmail.com">Email</a>. I’d be happy to chat or answer any questions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=167fcc2d9260" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>