How PySpark works: Py4J, the JVM & Python workers
Apache Spark · Spark Architecture
Theory
Spark itself is written in Scala and runs on the Java Virtual Machine (JVM). When you start PySpark, your Python process launches a JVM driver and talks to it through Py4J, a bridge that lets Python call Java objects. Your SparkSession and DataFrames in Python are thin wrappers: df.filter(...) just asks the JVM to add a step to the plan, so built-in DataFrame functions run entirely inside the JVM at full speed.
Python code only runs on the cluster when you ship it there: RDD lambdas, Python UDFs and pandas UDFs. For those, each executor starts Python worker processes, sends them rows, and reads the results back. Plain Python UDFs move rows in pickled batches; pandas UDFs, toPandas() and createDataFrame(pandas_df) can use Apache Arrow, a columnar format that both sides read without converting row by row. For example, F.upper('city') never leaves the JVM, while a udf(lambda s: s.upper()) sends every city to Python and back.
Why we use it
This explains the single most important PySpark performance rule: prefer built-in functions over Python UDFs and RDD lambdas. It also explains errors you will meet, such as Py4JJavaError (a JVM exception surfaced in Python) and Python worker crashes caused by memory overhead.
When to use it
Think about it whenever you write a UDF, call toPandas(), or see Py4JJavaError in a stack trace. Use built-in functions first, pandas UDFs when you truly need Python logic, and enable Arrow for pandas conversions. With Spark Connect the client talks gRPC instead of Py4J.
How it works
- Python script calls a DataFrame method
- Py4J forwards the call to the JVM driver
- JVM builds and optimises the plan; an action runs tasks on executors
- Plan has Python code (UDF/lambda)? Yes: Rows go to Python workers (pickle/Arrow). No: Tasks stay in the JVM.
- Results come back to the JVM driver
- Py4J hands the result objects to Python
Syntax
sc._jvm.java.lang.Math.max(3, 7) # call Java via Py4J (internal API)
df._jdf # the JVM Dataset behind a DataFrame
df.explain() # BatchEvalPython = Python UDF, ArrowEvalPython = pandas UDF
spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true")Example
import os
from pyspark.sql import SparkSession, functions as F
from pyspark.sql.functions import udf, pandas_udf
spark = (SparkSession.builder.master("local[2]")
.config("spark.ui.enabled", "false")
.getOrCreate())
sc = spark.sparkContext
orders = spark.createDataFrame(
[(101, "North", 55000.0), (102, "West", 30000.0), (103, "North", 1500.0), (104, "South", 52000.0)],
"order_id INT, region STRING, amount DOUBLE")
# 1) Py4J: the Python SparkSession is a thin proxy over JVM objects
print("Java Math.max(3, 7) via Py4J:", sc._jvm.java.lang.Math.max(3, 7))
print("JVM class behind the DataFrame:", orders._jdf.getClass().getName())
# 2) DataFrame functions run inside the JVM; no Python process touches the rows
plan = orders.withColumn("gst", F.col("amount") * 0.18)._jdf.queryExecution().executedPlan().toString()
print("built-in expression needs Python?", "Python" in plan)
# 3) A Python UDF ships rows to separate Python worker processes (pickled batches)
gst_udf = udf(lambda a: a * 0.18, "double")
plan = orders.withColumn("gst", gst_udf("amount"))._jdf.queryExecution().executedPlan().toString()
print("Python UDF operator:", "BatchEvalPython" in plan)
# 4) A pandas UDF moves the same data with Apache Arrow (columnar batches)
@pandas_udf("double")
def gst_vec(a):
return a * 0.18
plan = orders.withColumn("gst", gst_vec("amount"))._jdf.queryExecution().executedPlan().toString()
print("pandas UDF operator:", "ArrowEvalPython" in plan)
# 5) RDD lambdas also run in Python workers, not in the driver process
worker_pids = set(sc.parallelize(range(4), 2).map(lambda _: os.getpid()).collect())
print("lambdas ran outside the driver process:", os.getpid() not in worker_pids)
# 6) Arrow also speeds up toPandas() / createDataFrame(pandas_df)
spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true")
print(orders.toPandas().groupby("region")["amount"].sum().sort_index().to_dict())
# Output:
# Java Math.max(3, 7) via Py4J: 7
# JVM class behind the DataFrame: org.apache.spark.sql.classic.Dataset
# built-in expression needs Python? False
# Python UDF operator: True
# pandas UDF operator: True
# lambdas ran outside the driver process: True
# {'North': 56500.0, 'South': 52000.0, 'West': 30000.0}
Key points
- Python driver <-> JVM driver via Py4J; executors are JVMs too
- Built-in DataFrame functions run in the JVM: no Python per row
- Python UDFs and RDD lambdas run in separate Python worker processes
- Arrow moves columnar batches between JVM and Python (pandas UDFs, toPandas)
- Py4JJavaError = an exception raised in the JVM; read the Java message inside it
- _jvm and _jdf are internal; fine for learning, avoid in production code