Apache Spark Provider Integration with Airflow
Architecture Diagram
Formal Definitions
Detailed Explanation
Spark Integration Overview
The Spark provider enables Airflow to submit and monitor Spark jobs across YARN, Kubernetes, and standalone clusters. It wraps the spark-submit CLI command.
â ī¸Cluster mode survives the worker, client mode does not
In client mode the Spark driver runs inside the Airflow worker process, so a worker restart, a preemption or a pool timeout halfway through the job kills the application with it. Cluster mode launches the driver on the cluster and returns, which is what makes long jobs safe to schedule.
Operator Selection Guide
| Operator | Use Case | Best For |
|---|---|---|
| SparkSubmitOperator | Submit any Spark app | PySpark, Scala, Java |
| SparkJDBCOperator | JDBC read/write | Database transfers |
| SparkSQLOperator | Execute SQL queries | Hive/Spark SQL |
| SparkBatchOperator | Batch processing | Structured Streaming |
Deploy Mode Comparison
| Mode | Driver Location | Worker Dependency | Best For |
|---|---|---|---|
| Client | Airflow worker | High | Development, debugging |
| Cluster | Spark cluster | Low | Production, long jobs |
Connection Setup
# Airflow connection for Spark
# Connection ID: spark_default
# Connection Type: Spark
# Host: yarn (or k8s://https://\<api\>:6443 or spark://<host>:7077)
# Extra: {
# "deploy-mode": "cluster",
# "spark-home": "/opt/spark",
# "spark-binary": "spark-submit",
# "namespace": "spark-jobs",
# "job-template": {
# "apiVersion": "spark.apache.org/v1beta2",
# "kind": "SparkApplication",
# "spec": {"...": "..."}
# }
# }
Basic SparkSubmitOperator
from datetime import datetime, timedelta
from airflow import DAG
from airflow.providers.apache.spark.operators.spark_submit import SparkSubmitOperator
with DAG(
dag_id='spark_etl_pipeline',
start_date=datetime(2024, 1, 1),
schedule_interval='@daily',
catchup=False,
tags=['spark', 'etl'],
) as dag:
submit_extract = SparkSubmitOperator(
task_id='spark_extract',
conn_id='spark_default',
application='/opt/spark/jobs/extract.py',
name='extract_job_{{ ds }}',
application_args=[
'--date', '{{ ds }}',
'--source', 's3://data-lake/raw/',
'--target', 's3://data-lake/staging/',
],
conf={
'spark.sql.shuffle.partitions': '200',
'spark.sql.adaptive.enabled': 'true',
'spark.dynamicAllocation.enabled': 'true',
'spark.dynamicAllocation.minExecutors': '2',
'spark.dynamicAllocation.maxExecutors': '20',
},
packages='org.apache.hadoop:hadoop-aws:3.3.4',
py_files='/opt/spark/lib/utils.py',
driver_memory='4g',
executor_memory='8g',
executor_cores=4,
num_executors=10,
verbose=False,
trigger_rule='all_success',
on_failure_callback=None,
timeout=3600,
)
submit_transform = SparkSubmitOperator(
task_id='spark_transform',
conn_id='spark_default',
application='/opt/spark/jobs/transform.py',
name='transform_job_{{ ds }}',
application_args=[
'--date', '{{ ds }}',
'--input', 's3://data-lake/staging/',
'--output', 's3://data-lake/processed/',
],
conf={
'spark.sql.shuffle.partitions': '200',
'spark.sql.adaptive.enabled': 'true',
},
driver_memory='4g',
executor_memory='8g',
num_executors=10,
)
submit_extract >> submit_transform
SparkJDBCOperator
from airflow.providers.apache.spark.operators.spark_jdbc import SparkJDBCOperator
jdbc_extract = SparkJDBCOperator(
task_id='jdbc_extract',
conn_id='spark_default',
jdbc_table='orders',
jdbc_url='jdbc:postgresql://db-host:5432/warehouse',
jdbc_driver='org.postgresql.Driver',
connection_properties={
'user': '{{ conn.jdbc.username }}',
'password': '{{ conn.jdbc.password }}',
},
target_dir='s3://data-lake/staging/orders/',
fetchsize=10000,
batchsize=5000,
num_partitions=20,
partition_column='order_id',
lower_bound=1,
upper_bound=1000000,
driver_memory='4g',
executor_memory='8g',
num_executors=5,
)
PySpark Job File
# /opt/spark/jobs/transform.py
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, sum, count, max
import argparse
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--date', required=True)
parser.add_argument('--input', required=True)
parser.add_argument('--output', required=True)
return parser.parse_args()
def main():
args = parse_args()
spark = SparkSession.builder \
.appName(f'transform_{args.date}') \
.getOrCreate()
# Read raw data
orders = spark.read.parquet(f'{args.input}/orders/{args.date}')
# Transform
aggregated = orders.groupBy('customer_id').agg(
sum('amount').alias('total_amount'),
count('*').alias('order_count'),
max('order_date').alias('last_order_date'),
)
# Write processed data
aggregated.write.mode('overwrite').parquet(f'{args.output}/fct_orders/{args.date}')
spark.stop()
if __name__ == '__main__':
main()
Deferrable Spark Job Monitoring
from airflow.providers.apache.spark.operators.spark_submit import SparkSubmitOperator
from airflow.providers.apache.spark.triggers.spark_submit import (
SparkSubmitTrigger,
)
from airflow.operators.python import PythonOperator
from typing import Any, Dict
class DeferredSparkSubmitOperator(SparkSubmitOperator):
"""
SparkSubmitOperator that defers after submitting the job.
The worker slot is released while monitoring.
"""
def execute(self, context: Dict[str, Any]) -> None:
self._hook = self._get_hook()
self._conn = self._hook.get_connection(self._conn_id)
application_id = self._submit_job(
context['run_id'],
self._application,
)
self.defer(
timeout=self._total_timeout_seconds,
trigger=SparkSubmitTrigger(
application_id=application_id,
poll_interval=self._poll_interval,
conn_id=self._conn_id,
),
method_name='execute_complete',
)
def execute_complete(self, context: Dict[str, Any], event: Dict[str, Any]) -> None:
if event['status'] == 'error':
raise RuntimeError(f'Spark job failed: {event.get("message")}')
self.log.info(f'Spark job completed: {event.get("application_id")}')
When spark-submit Succeeds but the Job Fails
SparkSubmitOperator builds a spark-submit command and runs it through SparkHook, so the worker executing the task must be able to run that binary. It has to sit on PATH, it should match the cluster's Spark version, and in client mode it needs the same spark-defaults.conf and Hadoop configuration the cluster uses. An image without Spark fails with a command-not-found exit code that reads like a broken application rather than a broken image.
Exit codes also behave differently per deploy mode. In client mode the CLI exits with the application's status, so an exception inside the PySpark job fails the Airflow task on the first attempt. In cluster mode the command returns as soon as the driver is launched; a driver that dies three minutes later cannot change that exit code, so the task reports success while no output was ever written. Poll the application id afterwards, using the deferrable trigger shown above or a resource-manager status check, before treating the task as complete.
Dependency resolution is the third trap. packages downloads Maven artifacts while the task submits, so a worker that has lost its route to the repository fails on the day a cache is cleared; mirror the artifacts internally or ship them with py_files and files.
| Symptom | Likely cause | Correction |
|---|---|---|
| Exit code 127, command not found | Spark is absent from the worker image | install it on workers or move to cluster mode |
| Task succeeds, output table still empty | cluster-mode driver died after submission | poll the application id with a trigger |
| Submit hangs, then a dependency error | no route to the Maven repository at submit time | vendor the jars and pass them with files |
| Application never starts | queue has no free executors | request fewer executors or move queues |
Sizing Executors and JDBC Partitions
num_executors is only a starting request once spark.dynamicAllocation.enabled is true. Spark grows and shrinks the pool against the shuffle backlog, so a task that asks for 10 executors may run with two on a quiet morning and twenty after lunch; capacity reviews should read the Spark UI rather than the operator arguments.
JDBC reads deserve the same scrutiny. num_partitions splits the table with a range predicate per partition, so partition_column should carry an index â otherwise each partition scans the same rows in parallel and the source database works harder than it would for one sequential read. fetchsize and batchsize keep the stream bounded, while the executor heap is set by executor_memory plus YARN's overhead, which is roughly a tenth of executor memory with a floor of 384 MB. Quote that overhead when you ask a queue for capacity, because a request for eight executors of 8 GB does not fit in a queue that only looks like it has 64 GB free.
From Operator Argument to Command Line
The hook translates operator arguments into spark-submit flags, which is worth knowing when a job behaves differently from the script that runs outside Airflow.
| Operator argument | Flag it produces | Note |
|---|---|---|
application | positional first argument | path to a jar, Python or R file |
application_args | --args | passed to the script in order, after templating |
conf | --conf key=value | one flag per entry, so a typo becomes an unknown-property warning rather than an error |
packages | --packages | Maven coordinates resolved during submission |
py_files | --py-files | archives added to the driver and executor PYTHONPATH |
driver_memory | --driver-memory | sized separately from executors in cluster mode |
Configuration Reference
| Parameter | Description | YARN | Kubernetes |
|---|---|---|---|
conn_id | Spark connection | yarn | k8s://https://<api>:6443 |
deploy_mode | client or cluster | cluster | cluster |
num_executors | Executor count | Fixed or dynamic | Pod replicas |
executor_memory | RAM per executor | 4-16g | Configured via resources |
executor_cores | CPU per executor | 2-8 | Configured via resources |
driver_memory | Driver RAM | 2-8g | 2-8g |
packages | Maven coordinates | Downloaded on submit | Downloaded on submit |
py_files | Python dependencies | Local or HDFS | Mounted volumes |
Best Practices
Job Configuration
- Use cluster deploy mode for production â client mode ties the driver to Airflow's worker.
- Enable dynamic allocation to optimize resource usage:
spark.dynamicAllocation.enabled=true. - Set
num_partitionsappropriately for JDBC reads to avoid OOM or under-parallelization. - Use
packagesfor dependency management instead of pre-installing on cluster.
Monitoring and Performance
- Monitor Spark UI for job performance â check stages, shuffle, and spill metrics.
- Use deferrable operators for long-running Spark jobs to free worker slots.
Operational Guidelines
- Set
timeouton SparkSubmitOperator to prevent indefinite hangs. - Tag Spark applications with Airflow run IDs for traceability.
Spark Configuration Reference
| Configuration | Description | Recommended Value |
|---|---|---|
spark.sql.shuffle.partitions | Number of shuffle partitions | 200 (default) |
spark.sql.adaptive.enabled | Adaptive query execution | true |
spark.dynamicAllocation.enabled | Dynamic executor allocation | true |
spark.dynamicAllocation.minExecutors | Minimum executors | 2 |
spark.dynamicAllocation.maxExecutors | Maximum executors | 20 |
See Also
- Databricks Provider â Databricks-managed Spark clusters
- BigQuery Provider â Google BigQuery integration
- Snowflake Provider â Snowflake data warehouse integration
- Operators and Hooks â Operator lifecycle and hook architecture