What is PySpark? Architecture, Py4J and SparkSession

Spark tutorial · PySpark.in

PySpark is the Python API for Apache Spark: you write DataFrame code in Python, and Spark runs it in parallel on the JVM across a cluster, so the same code can process gigabytes or terabytes. Use it when data no longer fits on one machine or pandas becomes too slow. This chapter explains how Python talks to the JVM, how drivers, executors and partitions fit together, and what lazy evaluation means.

MODULE 1 • CHAPTER 2 | PYSPARK.IN ADVANCED CURRICULUM

What is PySpark & Internal Execution Architecture

Py4J JVM Bridge, Cluster Topology, Partition-to-Core Execution, Lazy Evaluation & Catalyst Plans

1. What is PySpark? (And When Should You Use It?)

PySpark is the official Python API for Apache Spark. It combines Python's readable syntax and rich data ecosystem with Spark's distributed, fault-tolerant JVM compute engine—allowing data engineers to process terabytes to petabytes of data across hundreds of machines.

Intuitive Analogy: Delhi -> Agra (Pandas) vs. Delhi -> New York (PySpark)

Think of Pandas like taking a train from Delhi to Agra (200 km): it is fast, cheap, and has zero airport check-in overhead—ideal when your dataset fits comfortably inside a single machine's RAM. PySpark is like flying from Delhi to New York: you cannot drive across an ocean, so you accept the 'airport overhead' (cluster startup, query planning, network serialization) because massive data size demands distributed parallel compute across multiple nodes.

2. Internal Architecture: How Python Communicates with Spark's JVM

A critical detail every Data Engineer must understand is that Apache Spark is written in Scala and runs on the Java Virtual Machine (JVM), whereas Python runs in its own CPython interpreter. When you write PySpark DataFrame code, Spark does not execute your data processing inside Python:

Figure 1: PySpark Master-Worker Architecture showing Py4J Driver communication and Executor task slots.

3. Core Cluster Components & The Partition -> Task -> Core Rule

Component

Role in Spark Cluster

Key Technical Fact

Driver Node

The 'Brain': runs main(), hosts SparkSession, builds Logical/Physical plans, and schedules tasks.

Never call collect() on large DataFrames—all rows get pulled into Driver RAM, causing OutOfMemory (OOM) crashes.

Cluster Manager

Allocates CPU and RAM resources across applications.

Supported managers: Kubernetes, Hadoop YARN, and Spark Standalone (Apache Mesos is deprecated/removed).

Worker Node

Physical or virtual server machine in the cluster.

A single large worker node can host multiple Executor JVM processes.

Executor

A dedicated JVM process launched on a Worker Node that runs tasks and stores cached partitions.

Each Executor has multiple CPU cores (task slots).

Partition & Task

A Partition is a chunk of data; a Task is a unit of work applied to one partition.

Golden Rule: 1 Partition = 1 Task per Stage, and 1 CPU Core runs 1 Task at a time.

Practical Parallelism Math: Suppose your dataset has 100 partitions and your cluster has 10 Executors with 4 CPU cores each (40 total cores). Spark creates 100 tasks, runs 40 tasks simultaneously in Wave 1, 40 tasks in Wave 2, and the remaining 20 tasks in Wave 3.

4. SparkSession: The Unified Entry Point

In older Spark 1.x versions, developers had to manage separate SparkContext, SQLContext, and HiveContext objects. Since Spark 2.0, SparkSession unifies all of them into a single entry point (already pre-initialized as spark in Databricks notebooks).

Snippet 1: Initializing a Production SparkSession

```

from pyspark.sql import SparkSession

spark = (
SparkSession.builder
.appName("PySpark_Architecture_Demo")
.config("spark.sql.shuffle.partitions", "200")
.getOrCreate()
)

print(f"Running Apache Spark Version: {spark.version}")

```

OUTPUT:

Running Apache Spark Version: 3.5.1

5. Lazy Evaluation, Catalyst Plans & explain()

PySpark divides all DataFrame operations into two categories:

Notice in the example below how explain() prints the optimized execution plan without triggering a Spark job, while show() executes the pipeline and returns results to the Driver (whereas write() writes directly from Executors to cloud storage):

Snippet 2: Demonstrating Lazy Evaluation & Physical Plan with explain()

```

from pyspark.sql import functions as F

sales_data = [
("TXN01", "Female", 34, "Beauty", 1500),
("TXN02", "Male", 24, "Clothing", 800),
("TXN03", "Female", 41, "Electronics", 3200),
("TXN04", "Male", 38, "Beauty", 2100),
("TXN05", "Female", 29, "Electronics", 1900)
]
columns = ["txn_id", "gender", "age", "category", "amount"]

df = spark.createDataFrame(sales_data, schema=columns)

# 1. Transformations: Only builds the Logical Plan (No Spark Job runs!)
filtered_df = df.filter(F.col("age") > 30)
summary_df = (
filtered_df
.groupBy("category")
.agg(F.sum("amount").alias("total_sales"))
)

# 2. Inspect Physical Plan before running any job
summary_df.explain()

# 3. Action: Triggers actual distributed execution across Executors
summary_df.show()

```

OUTPUT:

== Physical Plan ==
AdaptiveSparkPlan isFinalPlan=false
+- HashAggregate(keys=[category#3], functions=[sum(amount#4L)])
+- Exchange hashpartitioning(category#3, 200), ENSURE_REQUIREMENTS
+- HashAggregate(keys=[category#3], functions=[partial_sum(amount#4L)])
+- Project [category#3, amount#4L]
+- Filter (isnotnull(age#2L) AND (age#2L > 30))
+- Scan ExistingRDD[txn_id#0,gender#1,age#2L,category#3,amount#4L]

+-----------+-----------+
| category|total_sales|
+-----------+-----------+
| Beauty| 3600|
|Electronics| 3200|
+-----------+-----------+

Look closely at the Physical Plan above: Catalyst automatically inserted a Project [category, amount] step (Column Pruning) to drop txn_id and gender before grouping, and added isnotnull(age) automatically!

6. Modern PySpark: Pandas API on Spark & Spark Connect

Snippet 3: Distributed Pandas Syntax via pyspark.pandas

```

#pip install pyarrow

#"Requires PyArrow installed locally/in Databricks

import pyspark.pandas as ps

ps_df = df.pandas_api()
print(ps_df.groupby("category")["amount"].sum())

```

OUTPUT:

category
Beauty 3600
Clothing 800
Electronics 5100
Name: amount, dtype: int64

7. MNC Interview Questions (Chapter 2)

Q1. Python is an interpreted and dynamically typed language. How does PySpark achieve speeds comparable to compiled Scala?

Answer: PySpark's DataFrame API is only a thin wrapper over Spark's JVM engine. Through Py4J, Python passes transformation instructions to the JVM Driver, where the Catalyst Optimizer and Project Tungsten generate native JVM bytecode. Python execution overhead occurs only when custom Python UDFs are invoked.

Q2. What is the difference between an Action like show()/collect() and write.parquet() in terms of data flow?

Answer: collect() and show() transfer processed records from Executors back to the Driver node's memory (which can crash the Driver if the result is huge). In contrast, write.parquet() writes partitions directly from each Executor to distributed storage (S3/ADLS/HDFS) in parallel without routing data through the Driver.

Q3. Why does spark.read.csv(..., inferSchema=True) trigger a Spark job even though reading data is a transformation?

Answer: Because Spark must know column data types at compile time to build a valid Logical Plan. Setting inferSchema=True forces Spark to run an immediate background scan over the CSV file to sample and infer types before any downstream transformations can be validated.

Keep learning

More Spark tutorials

PySpark tutorial: all lessons · All tutorials · Try the free PySpark compiler · Practice challenges · Beginner tutorial: learn PySpark step by step