Apache Spark Architecture & Execution: Complete Internal Guide
A practical deep dive into Spark distributed execution system - deconstructing Spark runtime mechanics, partitioning, and task scheduling

Machine Learning · fine-tuning · GraphRAG · causal ML
Table of Contents
IntroductionWhy Apache Spark - Parallel Data ProcessingCore Apache Spark ArchitectureIntroduction
As datasets grow, processing them efficiently on a single machine can become challenging due to limitations in CPU capacity, memory, and storage throughput.
Apache Spark addresses these challenges by providing a distributed data processing engine that can divide workloads into partitions and execute tasks in parallel across CPU cores and multiple machines.
However, Spark is not simply about adding more machines.
Understanding how its components work together—Drivers, Executors, RDDs, DataFrames, Partitions, Jobs, Stages, and Tasks—is essential to designing efficient and reliable data pipelines.
In this article, I'll walk through Spark's architecture, execution mechanics, and key performance considerations using a practical e-commerce sales aggregation example.
Why Apache Spark - Parallel Data Processing
Apache Spark is a distributed computing engine designed for large-scale data processing and data engineering.
Spark processes big data leveraging parallel data processing:

Figure A. High-level Apache Spark distributed cluster architecture (cluster, driver, and worker nodes), comparing a single node execution (Created by Kuriko IWAI)
Compared with a single node processing (right, Figure A), Spark divides work into tasks using multiple nodes, executing them across resources, when available, across machines.
Here, distributed does not mean multiple machines are mandatory. Spark can run in local mode on a single machine. Even there, data can be partitioned and processed in parallel.
Core Apache Spark Architecture
Spark consists of several key components:
Spark driver (driver): The central coordination process of Spark application.
Cluster manager: An external service responsible for allocating hardware resources like CPU cores and memory.
Worker nodes (worker): A physical / virtual machine or compute node in the cluster.
Executors: Distributed worker processes launched on worker nodes.
Java Virtual Machine (JVM): The runtime environment required to execute Spark’s bytecode (since Spark is written in Scala/Java).
First, the driver coordinates a Spark application and transform it into a directed acyclic graph (DAG) of physical execution tasks, and schedules them across the executors.
Then, cluster manager allocates resources under the deployment's resource-management system.
Worker nodes supply compute resources to executors, which execute tasks and hold data during the task execution.
Some managed environments like Databricks use one executor per worker, but this is not a universal Spark rule. A worker can host multiple executors depending on cluster configuration.
◼ E-commerce Use Case - Input Data Structure
Let us imagine a boutique e-commerce company.
It has 10,000 sales records, each with a stock keeping unit (SKU) and quantity sold. Assume three possible SKUs: A, B, and C.
Table 1. E-Commerce sales record breakdown & expected aggregations example.
Our goal is to calculate total valid units sold per SKU:
Filter out records whose qty <= 0, then
Aggregate samples by SKU.
In the illustrative full dataset, suppose 9,800 of the 10,000 records remain after filtering. The final totals expected from Spark are:
1[("A", 8000), ("B", 10500), ("C", 9200)]
2◼ Spark Cluster
I'll define a simplified cluster for our use case.
▫ Worker Nodes (Workers)
I'll set 3 worker nodes, each of which has an instance type of 8 vCPU with 32 GiB RAM:

Figure B. Resource allocation across Worker Nodes (Created by Kuriko IWAI)
In total, 24 vCPU are available in the system.
▫ Spark Executors and CPU/Memory Allocation
Let's say, I'll secure:
7 executors.
2 vCPU cores for each executor.
3GiB JVM heap memory for each executor.
Spark application requests the cluster manager to allocate resources to these 7 executors.
Then, the cluster manager decides CPUs and memory allocations based on the resource usage of each worker.
For instance, it decides to create 14 tasks slots - 2 vCPU core per executor x 7 executors:

Figure C-1. vCPU cores, memory, and Executor allocation across Workers with resource imbalance in Worker A (Created by Kuriko IWAI)
Note that the 3 GiB memory allocated to Executor is not its total memory because it has to secure memory overhead for Workers and other executions.
Assuming that a single task requires 1 vCPU (spark.task.cpus = 1), each worker allocates its vCPU:

Figure C-2. Parallel vCPU allocation across Workers (Created by Kuriko IWAI)
This shows two key points:
Each worker has its unique CPU usage rate (In Figure C-2, Worker A's usage is 75%, while Workers B and C remain 50%).
Even though the system has 24 vCPU cores (8 vCPU/worker x 3 Workers), it can only use 14 vCPU cores; the rest 10 remain unused for these tasks.
Developer Note: Optimal Resource Allocation
In our example, Worker A might create memory, disk I/O, or network bottleneck because of its heavier CPU usage and task loads than Workers B and C.
In practice, we need to consider if this imbalanced resource allocation is optimal for the system especially when all workers have the same instance type.
◼ Java Virtual Machine (JVM) Behind Spark
Apache Spark is built on the Java Virtual Machine (JVM).
JVM is a runtime environment required to execute Spark’s bytecode.
Since Spark is written in Scala/Java:
When using Scala or Java in application: The code runs natively inside the JVM.
When using PySpark (Python): A Python process runs the code, but it communicates with a JVM-based driver via a bridge such as Py4J. The Spark executors on the worker nodes still run inside a JVM, which then manages Python workers to execute Python code and User-Defined Functions (UDFs).
In either case, the JVM manages execution threads, memory allocation, and garbage collection for both the driver and executors.
▫ Driver & Executor JVMs in PySpark Application
In a PySpark application, the Python driver communicates with the Spark driver running in the JVM;
Python driver: Where application-level PySpark code is written and executed.
Driver JVM: Coordinates Spark execution and scheduling.
Executor JVM: Runs Spark tasks and manages execution resources. Python worker processes are involved when tasks require Python execution.
Client JVM (client process or submission machine): JVM running on the local machine or an edge/gateway node.
As shown in the figure, the client JVM first connects to the driver JVM, which subsequently coordinates with the executor JVMs:

Figure D. Overall relation of client, driver, and executor JVMs
From here, the driver JVM hosts the Spark Driver to manage the application, while the executor JVMs host the individual executors responsible for executing those tasks.
Each JVM driver has JVM heap to handle data processing, caching, and user objects efficiently.
◼ Resilient Distributed Datasets (RDDs) Deep Dive
A Resilient Distributed Dataset (RDD) is an immutable, partitioned collection of elements that Spark can process in parallel.
RDDs track dependencies between transformations, allowing Spark to recompute lost partitions in many failure scenarios.
The name captures three properties:
Resilient: Spark records lineage—which RDD depends on which previous RDD—and can often reconstruct missing partitions instead of maintaining replicas of every intermediate result.
Distributed: The dataset is represented as partitions that Spark may process on different executors. Multiple physical machines are not required; local mode also supports RDDs.
Dataset: An RDD can contain key-value pairs, integers, strings, tuples, and other supported elements—not only relational rows. RDD APIs include operations such as map, filter, reduceByKey, join, and aggregateByKey.
An RDD is a logical collection and computation abstraction, not a declaration that particular partitions are permanently assigned to particular workers.
▫ Partitions
A partition is a logical chunk of data and normally corresponds to one task within a stage.
Let's say we create 100 partitions (These 100 initial partitions are an explicit teaching choice).
With 10,000 source elements, it gives approximately 100 elements per partition if the input is distributed roughly evenly:

Figure E. Parallel partition allocation across 100 initial data splits (Created by Kuriko IWAI)
Note that equal distribution is not a general guarantee, particularly after filtering or shuffling.
Apache Spark in Action - The Seven Steps
To achieve the goal of computing the aggregate number of goods sold by SKU, we follow the seven steps:
Step 1. Create a SparkSession.
Step 2. Define raw sales RDD with 100 partitions.
Step 3. Define the filtered RDD.
Step 4. Define the SKU aggregation RDD with four output partitions.
Step 5. Trigger an action; Spark determines jobs, stages, and tasks.
Step 6. Executors execute tasks, subject to 14 available task slots.
Step 7. Return the small aggregated result to the Driver.
We use the RDD API in this walkthrough because it makes Spark's partitions, dependencies, shuffle boundaries, and task execution easier to observe.
For most modern structured data pipelines, the DataFrame API is generally the preferred starting point, as we will explore later.
◼ Step 1. Create a SparkSession
First, SparkApplication creates a SparkSession:
1from pyspark.sql import SparkSession
2
3# step 1 - create sparksession
4spark = SparkSession.builder.appName("app1").getOrCreate()
5sc = spark.sparkContext
6As we saw in the previous section, this process includes ClusterManager to decide CPU/Memory allocation to each Worker:

Figure F. Cluster manager to allocate tasks to Workers (Created by Kuriko IWAI)
Here, SparkSession is the normal entry point for DataFrame and SQL operations.
SparkContext is the entry point for the core RDD API. The exact creation and resource-allocation lifecycle depends on deployment mode and cluster configuration.
◼ Step 2. Define RDD 1: Raw Sales
Assume records is an existing Python collection of 10,000 (sku, qty) tuples; the complete contents are intentionally omitted from this note.
1raw_rdd = sc.parallelize(records, 100)
2sc.parallelize() is convenient for small teaching examples, because the data begins in the Driver's Python process. It is usually not the preferred ingestion method for a huge production dataset. For large datasets, read from distributed storage with Spark readers instead.
Figure C shows that each partition (P0, P1, ...P99) has 100 rows (samples) in total.
For instance, P0 (Partition 0) in RDD 1 looks like:
Table 2. Sample raw data partition layout. Row-level view of the partition P0 (Created by Kuriko IWAI)
◼ Step 3. Define RDD 2: Filter Invalid Quantities
Next, RDD 2 has created to filter invalid records:
1filtered_rdd = raw_rdd.filter(lambda row: row[1] > 0)
2filter is a narrow transformation: the output of an individual partition depends only on the corresponding input partition.
The number of partitions remains 100, although the number of records per partition may change.
Suppose this filter removes 200 invalid records. Then 9,800 remain, equivalent to 98 records per partition on average, not 98 in every partition:

Figure G. From RDD 1 to RDD 2. Row filtering flow across 100 partitions (Created by Kuriko IWAI)
◼ Step 4. Define RDD 3: Aggregate Sales by SKU
The last RDD is to group the data by SKU, creating 4 output partition:
1result_rdd = filtered_rdd.reduceByKey(
2 lambda a, b: a + b,
3 numPartitions=4 # human to define the num of output partitions
4)
5This combines quantities with the same SKU key. reduceByKey performs map-side combining before shuffling partial results to the four reduce partitions.
Important: reduceByKey demonstrates why the statement “RDDs only support row-wise transformations” is incorrect. RDDs can perform aggregations and many other distributed operations.
So, after RDD2, RDD 3 would look like the following:

Figure H. From RDD 2 to RDD 3. Data redistribution during reduceByKey Aggregation across 4 reduce partitions (Created by Kuriko IWAI)
In practice, Hash partitioner allocates SKUs to partitions.
This hash-based partitioning strategy is common, but the actual distribution of the three SKUs over four reduced partitions depends on hashing and configuration. Some partitions may have zero resulting keys.
So, to summarize Steps 2 to 4:
Table 3. Summary of RDD lineage transformations and partition count evolution (Created by Kuriko IWAI)
◼ Lazy Evaluation and Lineage
The filter and reduceByKey calls establish a dependency graph; they do not immediately compute the full aggregation.
Spark records how to produce filtered_rdd from raw_rdd and result_rdd from filtered_rdd.
It is important to note that no Worker has been assigned to the RDDs yet, hence, no computation happens at this stage.
This is called lazy evaluation where Spark only defines how to transform data with RDDs, while postponing the execution of such transformation in a later phase.
The RDD lineage view looks like a graph of what depends on what:
raw_rdd: 100 partitions
→ filtered_rdd: 100 partitions
→ result_rdd: 4 partitions
→ Driver-side Python list
◼ Step 5. Trigger an Action
After defining RDDs, Driver decides Shuffle Boundary, where RDDs are divided into separate Stages, and schedules these Stages.
1result = result_rdd.collect()
2collect() is an action. It starts computation required to produce the RDD and returns all output elements to the Driver.
Here only three SKU aggregates are expected, so collect() is reasonable. But collecting millions of records to a Driver can exhaust Driver memory.
Spark uses the RDD dependencies to build an execution plan, breaking the work into stages and tasks. For our simplified example, expect a shuffle map stage before the reduceByKey shuffle and a result stage after it.
◼ Jobs, Stages, Tasks—Their Relationship to RDD Lineage
A job refers to the scheduler work associated with computing an action's result.
A stage refers to a set of tasks separated from other stages by scheduling dependencies such as shuffle.
A task is work for one partition within a stage.
In our case, Driver decides to set Shuffle Boundary between RDDs 2 and 3, creating Stage 1 with RDDs 1 and 2, and Stage 2 with RDD 3 in Job 1:

Figure I. Complete RDD lineage graph and dependency flow (Created by Kuriko IWAI)
In Stage 1, each partition runs computation defined in RDDs 1 and 2 sequentially:
RDD 1: P0 → RDD 2: P0 → local result P0
RDD 1: P1 → RDD 2: P1 → local result P1
…
RDD 1: P99 → RDD 2: P99 → local result P99
Then, Spark runs shuffle by SKU because the final aggregation by SKU needs to collect SKU data scattered across all the partitions.
In Stage 2, the 4 partitions aggregate the final results.
During this step, executors executes 104 tasks in total:
Stage 1: 100 tasks in total.
Stage 2: 4 tasks in total.
Note that the total number of Tasks executed in Stage 1 is not 200 (100 partitions x 2 RDDs) because a partition handles Narrow Transformation as a single Task.
Subtle but important: “One action always equals exactly one job” is not a universal rule. Some APIs, adaptive execution features, and supporting operations can trigger additional work. The stage boundaries are ultimately verified in the Spark UI.
◼ Step 6. Execute with 14 Task Slots
Our seven 2-core executors provide 14 concurrent one-CPU task slots under the simplified assumptions of 1 CPU allocation per task (Figure C-1).
The table below demonstrates an example of Task allocation to Workers:
Table 4. Worker, Executor, Task, and partition mapping matrix (Created by Kuriko IWAI)
Now, take a look at Task T0 in Stage 1. It follows executions defined in RDD 1 and 2:

Figure J. Detailed execution mechanics of Task T0 within Stage 1 (Created by Kuriko IWAI)
Other Tasks follow the exact same order in its own partition.
In our case, Stage 1 has 100 tasks and all slots are available, its execution can be visualized as:
Table 5. Execution scheduling wave breakdown across 14 concurrent task slots (Created by Kuriko IWAI)
Table 5 shows that the system runs 8 waves (100 Tasks / 14 slots).
But note that this is an example of scheduling; it does not indicate that Spark always allocate Tasks in order of the partition number or in synchronized waves.
Actual scheduling is asynchronous, task durations differ, and locality and resource constraints affect placement. So, if let's say T8 takes longer than the rest in Wave 1, Executor 8 which handles T8 must wait to complete the task, while the rest Executors start to address allocated tasks in Wave 2.
Next, Stage 2 only has 4 Tasks; so the system only uses 4 task slots concurrently, while the rest 10 slots remain unused:

Figure K. Task execution bottleneck during Stage 2 reduce phase (slot underutilization) (Created by Kuriko IWAI)
More executor cores do not automatically make a four-partition stage use 14 CPU cores simultaneously.
◼ Step 7. Returns Computation Results to Driver
Finally, a successful collect() could return the results to the Driver:
1[
2 ("A", 8000),
3 ("B", 10500),
4 ("C", 9200),
5]
6If Executor fails, Spark can retry failed tasks and, where necessary, recompute missing RDD partitions using lineage.
Recovery behavior depends on the failure and the execution state; a failed task may have new attempts, and stage retries or shuffle-data loss may require additional re-computation.
In a simple example, when Executor 4 in Worker B failed during Task T6 in Stage 1, the Driver assigned another Executor T6.
Shipping AI Systems?
I help teams design and deploy scalable ML / RAG / LLM pipelines and MLOps infrastructure.
Or explore:
- Dive deeper 👉 Research Archive
- Learn by building 👉 AI Engineering Masterclass
- Try it live 👉 Playground
RDD API vs DataFrame API: Internal Catalyst Optimization
The original RDD example helps understand lineage, partitions, and shuffle.
In typical structured ETL, however, the DataFrame API is the preferred starting point because it provides columns, schema information, SQL-like expressions, and optimizer-visible operations.
Below diagram illustrates the relationship:

Figure L. How Spark's Graph concepts relate; RDD linage, DataFrame, and Spark Execution DAG (Created by Kuriko IWAI)
Just like RDD has RDD lineage to define the transformation, DataFrame query plan represents its structured query.
Spark constructs execution work from dependencies and physical operators.
DataFrame execution may use RDD-based mechanisms internally, but that does not mean users need to manually build RDD lineage when writing DataFrame code.
◼ DataFrame Query Plan
A DataFrame query plan is the sequence of logical and physical steps an execution engine generates (purple box in Figure L).
A DataFrame query moves through several representations:
Logical plan: A description of the requested operations (scan, filter, group, aggregate).
Analyzed and optimized logical plan: Spark resolves references and applies applicable logical optimizations, such as column pruning or predicate pushdown.
Physical plan: Spark chooses executable operators, e.g. scans, partial/final aggregates, exchanges, joins, and sorts.
Execution: The physical plan is run using Spark's execution mechanisms, ultimately involving tasks on executors.
In our use case, the physical plan can include the following steps:
Partial hash aggregation,
Exchange by SKU, and
Final hash aggregation.
◼ Comparing Actions: RDD API vs DataFrame API
Let us compare RDD API and DataFrame API, taking the SKU aggregation for an example.
▫ RDD API
The elements are (sku, qty) pairs. Our Python aggregation logic is explicit, and Spark follows RDD dependencies:
1result_rdd = (
2 raw_rdd
3 .filter(lambda row: row[1] > 0)
4 .reduceByKey(lambda a, b: a + b, numPartitions=4)
5)
6
7rdd_results = result_rdd.collect()
8
9# Example:
10# [('A', 8000), ('B', 10500), ('C', 9200)]
11▫ DataFrame API
Assume sales_df has columns sku (string) and qty (numeric):
1from pyspark.sql import functions as F
2
3result_df = (
4 sales_df
5 .filter(F.col("qty") > 0)
6 .groupBy("sku")
7 .agg(F.sum("qty").alias("total_qty"))
8)
9
10df_results = result_df.collect()
11
12# Example:
13# [Row(sku='A', total_qty=8000),
14# Row(sku='B', total_qty=10500),
15# Row(sku='C', total_qty=9200)]
16Here, both examples solve the same business problem:
Filtering invalid sales records and aggregating valid quantities by SKU.
And in both cases, collect() triggers Spark execution and returns all resulting records to the Driver.
The key difference here is in the result representation:
RDD API: Returns Python elements, such as (sku, total_qty) tuples.
DataFrame API: Returns structured Row objects with named fields, such as sku and total_qty.
Here's an overall comparison of RDD and DataFrame APIs:
Table 6. RDD API vs. DataFrame API - feature & abstraction comparison:(Created by Kuriko IWAI)
Developer Note
Use collect() carefully with large datasets because all returned records must fit in the Driver's memory.
If we only want to inspect a few rows without collecting the complete dataset, the DataFrame API provides show().
For instance the below code displays up to ten rows rather than returning the entire DataFrame to the application.
1result_df.show(10, truncate=False)
2Note that neither collect() nor show() should be confused with a transformation: both are actions that trigger computation.
Wrapping Up
The goal of Spark tuning is not to maximize partition count or CPU usage independently.
It is to reduce end-to-end execution cost and latency without introducing instability.
In this article, we learn the core relationships in its system:
Resources: Workers host executors; executors run tasks; configured CPU and memory limit concurrency.
RDD programming: Transformations produce immutable RDD definitions and lineage; actions trigger computation.
DataFrame programming: Transformations produce logical query operations; optimization chooses executable physical operators; actions trigger computation.
Execution: Spark organizes work into jobs, stages, and tasks, and tasks process partitions on executors. Shuffles and other dependencies create coordination boundaries among stages.
Understanding how Spark executes distributed workloads is only the foundation.
In the next article, I'll explore how to prevent out-of-memory errors while tuning the performance.
◼ Appendix - Apache Spark Glossary
Table 6. Apache Spark glossary (Created by Kuriko IWAI)
Written by Kuriko Iwai · Kernel Labs. All images, unless otherwise noted, are by the author. All experimentations on this blog utilize synthetic or licensed data.
FAQ
1) What is the difference between a Spark Driver and a Spark Executor?
👉 The Spark Driver is the master process that converts user code into an execution plan (DAG), schedules stages/tasks, and coordinates with the Cluster Manager. Spark Executors are distributed worker processes running on worker nodes that execute assigned physical tasks, hold cached data in JVM memory, and store intermediate shuffle output to disk.
2) How does Spark's Lazy Evaluation improve query performance?
👉 Lazy evaluation delays data computation until an action (e.g., collect(), count(), save()) is explicitly triggered. This allows Spark's Catalyst Optimizer and DAG Scheduler to analyze the complete lineage graph, combine operations, prune unneeded columns, push down predicates, and eliminate redundant shuffles before running physical tasks.
3) What is the difference between Narrow and Wide Dependencies in Spark?
👉 A Narrow Dependency occurs when each partition of the parent RDD is used by at most one partition of the child RDD (e.g., map(), filter()), allowing inline execution without network transfers. A Wide Dependency occurs when multiple child partitions depend on data from a single parent partition (e.g., reduceByKey(), groupBy()), requiring a network shuffle stage boundary.
4) Why is the DataFrame API preferred over the low-level RDD API in modern PySpark?
👉 The DataFrame API exposes full relational semantics and schema structures to Spark, enabling the Catalyst Optimizer to perform logical optimization (e.g., rule-based and cost-based optimizations) and Whole-Stage Java Code Generation. RDD transformations use black-box Python/Java lambdas that cannot be optimized under the hood.
5) How does PySpark communicate between Python and the underlying JVM?
👉 In PySpark, the Python process communicates with the Driver JVM through Py4J socket connections. When executing PySpark code or custom Python UDFs, Executor JVMs spawn separate Python worker processes, serialization/deserialization occurs over IPC pipes, which introduces performance overhead compared to native Scala/Java execution.
6) What causes slot underutilization during Stage 2 reduce operations in Spark?
👉 Slot underutilization occurs when the number of partitions in a stage is lower than the available executor CPU slots (cores). For example, if a cluster has 14 available CPU slots but a reduceByKey or groupBy stage only outputs 4 partitions, Spark can only execute 4 concurrent tasks, leaving 10 CPU slots completely idle.
Shipping AI Systems?
I help teams design and deploy scalable ML / RAG / LLM pipelines and MLOps infrastructure.
Or explore:
- Dive deeper 👉 Research Archive
- Learn by building 👉 AI Engineering Masterclass
- Try it live 👉 Playground
Share What You Learned
Kuriko Iwai, "Apache Spark Architecture & Execution: Complete Internal Guide" in Kernel Labs
https://kuriko-iwai.com/apache-spark-architecture-execution-mechanics-guide
Continue Your Learning
If you enjoyed this blog, these related entries will complete the picture:
PySpark Memory Management Explained: Architecture, Out-of-Memory (OOM) Causes & Troubleshooting
Demystifying Apache Spark - Internals Explained
Advanced Cross-Validation for Sequential Data: A Guide to Avoiding Data Leakage
Data Augmentation Techniques for Tabular Data: From Noise Injection to SMOTE
A Guide to Synthetic Data Generation: Statistical and Probabilistic Approaches
Maximum A Posteriori (MAP) Estimation: Balancing Data and Expert Knowledge
Beyond Simple Imputation: Understanding MICE for Robust Data Science
Maximizing Predictive Power: Best Practices in Feature Engineering for Tabular Data
Related Books for Further Understanding
These books cover the wide range of theories and practices; from fundamentals to PhD level.

Linear Algebra Done Right

Foundations of Machine Learning, second edition (Adaptive Computation and Machine Learning series)

Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems

Machine Learning Design Patterns: Solutions to Common Challenges in Data Preparation, Model Building, and MLOps







