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:
- Py4J Bridge on the Driver: When you initialize a SparkSession, Python uses a library called Py4J over a local network socket to communicate with a corresponding JVM Driver process.
- Native JVM Execution (Zero Python Overhead): All built-in DataFrame transformations (select, filter, groupBy, join) are translated into Catalyst logical plans and compiled into JVM bytecode. Worker nodes process your data purely inside JVM Executors—which is why native PySpark is just as fast as Scala Spark.
- Python Workers & Apache Arrow (Only for UDFs): Separate Python worker processes are spawned on worker nodes only when you run custom Python UDFs or Pandas UDFs. In those cases, data must be serialized out of the JVM into Python (accelerated via Apache Arrow columnar memory format).

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 ``` |
OUTPUT: Running Apache Spark Version: 3.5.1 |
5. Lazy Evaluation, Catalyst Plans & explain()
PySpark divides all DataFrame operations into two categories:
- Transformations (Lazy): Operations like select(), filter(), withColumn(), groupBy().agg(), join(). Your Python code executes line by line, recording metadata in a Logical Plan, but zero data is read or processed yet.
- Actions (Eager): Operations like show(), count(), collect(), take(), write.parquet(). Calling an Action triggers the Catalyst Optimizer to compile an optimized Physical Plan, split it into Stages at shuffle boundaries, and dispatch Tasks to Executors.
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 ``` |
OUTPUT: == Physical Plan == |
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
- Pandas API on Spark (pyspark.pandas): Introduced in Spark 3.2, it lets data scientists run familiar Pandas syntax (ps.read_csv(), df.groupby().mean()) directly on distributed Spark clusters without rewriting code or pulling data into single-machine memory.
- Spark Connect: Decouples the client application from the Spark Driver using gRPC, allowing lightweight Python IDEs, microservices, and notebooks to connect to remote Spark clusters seamlessly.
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() ``` |
OUTPUT: category |
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
- Apache Spark architecture: driver, executors and DAG
- Transformations vs actions in PySpark, with examples
- RDD vs DataFrame vs Dataset in Spark
- Run PySpark online in the browser
More Spark tutorials
- Spark SQL Tutorial: Run SQL Queries in PySpark
- Spark SQL Queries in PySpark: spark.sql() Examples
- Registering UDFs in SQL
- PySpark Joins
- Broadcast Join and Skew Join in PySpark
- PySpark SQL Functions: col, lit, when (CASE WHEN)
PySpark tutorial: all lessons · All tutorials · Try the free PySpark compiler · Practice challenges · Beginner tutorial: learn PySpark step by step