PySpark and Py4J

How your Python code controls the Spark JVM.

Python process JVM process Socket between them

01What Py4J is

Spark is written in Scala. Scala runs in the Java Virtual Machine (JVM). Python cannot run JVM code directly.

Py4J is a small library. It connects a Python process to a JVM process. It uses a TCP socket on the local machine.

With Py4J, Python can do these tasks:

PySpark uses Py4J for one purpose: to control the Spark driver. Py4J does not move your data. Py4J does not run on the executors.

02Why Python and the JVM must communicate

The Spark engine exists only in the JVM. The SQL parser, the Catalyst optimizer, the scheduler, the cluster managers and the shuffle system are all Scala code. PySpark does not contain a second engine. PySpark is a thin Python layer that sends instructions to the JVM engine.

Your program logic is in Python. The engine is in the JVM. Thus each side must ask the other side for the things that it does not have.

DirectionReasonExampleChannel
Python → JVMBuild the query plan. Python has no plan object.df.filter(...)Py4J
Python → JVMStart the work. Only the JVM can schedule tasks.df.count(), df.writePy4J
Python → JVMGet results, schemas and settings back.df.schema, collect()Py4J + local socket
Python → JVMControl the session.spark.conf.set(...), spark.stop()Py4J
JVM → PythonRun your Python function on the data. The JVM cannot run Python code.UDF, rdd.map(lambda ...)Plain socket on each executor
JVM → PythonCall your Python code when an event occurs.foreachBatchPy4J callback
NOTE

Spark uses one engine for all languages. Scala, Java, Python, R and SQL use the same optimizer and the same execution code. The cost of this design is the boundary between Python and the JVM. Each time data crosses the boundary, Spark must serialize it and send it through a socket. Keep the data in the JVM when possible.

03The processes in a PySpark application

A PySpark application has two kinds of Python process. Each kind uses a different connection to the JVM. The diagram shows both.

DRIVER NODE Python process app.py SparkSession (wrapper) DataFrame (wrapper) Py4J JavaGateway client Driver JVM Py4J GatewayServer SparkSession (real) Catalyst + scheduler Objects kept by ID Py4J TCP · localhost method calls, IDs tasks over Spark RPC (JVM to JVM) EXECUTOR NODE (one of many) Executor JVM Runs tasks Built-in functions run here Python worker pyspark.daemon forks it Runs your UDF code plain socket pickle or Arrow NOT Py4J

Py4J connects only the two processes on the driver. The executors use a different, faster channel.

NOTE

The Python SparkSession and DataFrame objects hold no data. Each one holds an ID that points to a real object in the JVM.

04Executors and the driver

Each executor is a separate JVM process. On YARN and EMR, each executor runs in a YARN container. On Kubernetes, each executor runs in a pod. One node can have more than one executor. Executors do not share a heap.

What one executor JVM contains

PartSettingPurpose
Heapspark.executor.memoryExecution memory (shuffle, join, sort, aggregation), storage memory (cache, broadcast) and user memory.
Overheadspark.executor.memoryOverheadMemory outside the heap: JVM internals, Netty buffers, native libraries and the Python workers.
Task slotsspark.executor.coresThe number of tasks that run at the same time. Each task is a thread, not a process.
BlockManagerspark.blockManager.portKeeps cached partitions, shuffle files and broadcast pieces. Sends them to other executors.
CAUTION

Python workers use overhead memory, not heap memory. If a job with heavy Python UDFs fails because YARN kills the container, increase spark.executor.memoryOverhead. Do not only increase spark.executor.memory.

How the driver talks to executors

The driver JVM and the executor JVMs use Spark RPC. Spark RPC uses Netty over TCP. It does not use Py4J.

Driver JVM DAGScheduler · TaskScheduler DriverEndpoint (receives RPC) MapOutputTracker: where each shuffle block is Cluster manager YARN · Kubernetes 1 2 launches 4 LaunchTask 3 register 5 status · 6 heartbeat 3–6 same RPC Executor JVM 1 own heap, GC and thread pool task task task task BlockManager shuffle files · cache · broadcast Executor JVM 2 own heap, GC and thread pool task task task task BlockManager shuffle files · cache · broadcast data Shuffle blocks go from executor to executor. They do not go through the driver.

The numbers match the steps below. The driver controls the work. The executors move the data. Four task slots means spark.executor.cores = 4.

  1. The driver asks for executors. It sends a request to the cluster manager (YARN ResourceManager, Kubernetes API or Standalone master).
  2. The cluster manager starts the executor JVMs. Each executor gets the address of the driver on its command line.
  3. Each executor registers. It connects to the DriverEndpoint and sends RegisterExecutor. The driver records its ID, host and cores.
  4. The driver sends tasks. The DAGScheduler divides a job into stages. The TaskScheduler puts each task in a free slot and sends a LaunchTask message. The code of the stage goes to the executors one time, as a broadcast.
  5. The executors report. They send StatusUpdate messages. A small result goes in the message. A large result stays in the BlockManager, and the driver gets it from there.
  6. The executors send heartbeats. The interval is 10 seconds (spark.executor.heartbeatInterval). If the driver gets no heartbeat for spark.network.timeout (120 seconds), it marks the executor as lost. It then runs the tasks again on other executors.

The driver does not move the data

The three channels in a PySpark application

ChannelBetweenCarries
Py4JPython driver ↔ driver JVM (same machine)Method calls, object IDs, small values, callbacks
Spark RPCDriver JVM ↔ executor JVMs, and executor ↔ executorTasks, status, heartbeats, shuffle and broadcast data
Plain socketExecutor JVM ↔ its Python workers (same machine)Rows for Python UDFs, as pickle or Arrow

05How the connection starts

The start sequence has two forms. The form depends on which process starts first.

Form A: you run spark-submit app.py

  1. The JVM starts first. spark-submit starts the class org.apache.spark.deploy.PythonRunner.
  2. The JVM opens a Py4J GatewayServer. The server listens on a free local port. It also makes a secret token.
  3. The JVM starts Python. It puts the port and the token into the environment variables PYSPARK_GATEWAY_PORT and PYSPARK_GATEWAY_SECRET.
  4. Python connects. PySpark reads the two variables and makes a JavaGateway client.
  5. Python makes the context. SparkContext asks the gateway to make a JVM JavaSparkContext. Python keeps the ID of that object.

Form B: you run python app.py or a notebook

  1. Python starts first. It has no JVM.
  2. Python starts the JVM. The function launch_gateway() runs spark-submit pyspark-shell as a child process.
  3. The JVM writes its address to a file. It writes the port and the secret to a temporary file. Python reads that file.
  4. Python connects. Steps 4 and 5 of Form A then occur.
# You can see the gateway in a live session
from pyspark.sql import SparkSession

spark = SparkSession.builder.appName("py4j-demo").getOrCreate()
sc = spark.sparkContext

print(sc._gateway)              # py4j.java_gateway.JavaGateway
print(sc._gateway.gateway_parameters.port)   # local port, e.g. 41753
print(type(sc._jsc))            # JavaObject -> JavaSparkContext
CAUTION

Do not share the gateway port with other users. The secret token protects it. Any process with the token can run code in your JVM.

06One method call, step by step

Most PySpark API methods do one thing only. They send one Py4J call to the JVM. This example follows df.filter("age > 30").

Python Driver JVM df.filter("age > 30") df._jdf holds ID o42 1 · send command text c call o42 target object filter method name sage > 30 s = string arg e end 2 · find object o42 in the ID map 3 · reflection: Dataset.filter(String) builds a new logical plan; reads no data 4 · store new Dataset as o43 5 · reply !yro43 6 · wrap o43 in a new Python DataFrame

The wire text is simplified. In the reply, ! marks a return, y means success, and r means "reference to a JVM object".

The call takes one socket round trip. It reads no rows. Spark reads rows only when you call an action, for example count() or write.

df = spark.createDataFrame([("ann", 34), ("bob", 28)], ["name", "age"])
adults = df.filter("age > 30")       # one Py4J call, no data moves

print(df._jdf)                         # JavaObject id=o42
print(adults._jdf)                     # JavaObject id=o43
print(adults._jdf.queryExecution().optimizedPlan().toString())

Types that Py4J converts

Python valueSent asJVM value
int, float, bool, str, NoneValue in the command textInteger/Long, Double, Boolean, String, null
list, dictConverted copy (PySpark enables auto_convert)ArrayList, HashMap
Python wrapper (JavaObject)ID only, for example o42The original JVM object
Other Python objectsNot supportedError

Memory cleanup

The JVM keeps each object in an ID map. The object stays alive while Python holds its wrapper. When Python deletes the wrapper, Py4J sends a "delete o43" command. The JVM then removes the object from the map. The JVM garbage collector can then free it.

07Use the gateway directly

PySpark gives you access to the gateway. Use it to call JVM classes that PySpark does not wrap.

AttributePoints to
spark._jvmThe root of all JVM packages. Example: spark._jvm.java.lang.System
spark._jsparkSessionThe JVM SparkSession
sc._jscThe JVM JavaSparkContext
df._jdfThe JVM Dataset<Row>

Example: list files with the Hadoop FileSystem API

sc = spark.sparkContext
jvm = sc._jvm

conf = sc._jsc.hadoopConfiguration()
path = jvm.org.apache.hadoop.fs.Path("s3://YOUR-BUCKET/logs/")
fs = path.getFileSystem(conf)

for status in fs.listStatus(path):
    print(status.getPath().getName(), status.getLen())
CAUTION

Each JVM method call is one socket round trip. In the loop above, each file causes three calls. For 100,000 files, this is slow. Do large loops in the JVM, or use a Spark API that returns a DataFrame.

Example: read a JVM setting

print(spark._jvm.java.lang.System.getProperty("java.version"))
print(spark._jsparkSession.version())       # Spark version from the JVM

08Where the data goes

Py4J sends only small values and IDs. Large data uses other paths. Know these paths. They control the speed of your job.

Driver: collect() and toPandas()

  1. Python sends one Py4J call. The call asks the JVM to collect the rows.
  2. The JVM opens a separate local socket server. It returns only the port and a token through Py4J.
  3. Python connects to that socket. It reads the rows as pickled batches or as Arrow batches.
spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true")
pdf = df.toPandas()     # Arrow batches over a local socket, not Py4J

Executors: user-defined functions (UDFs)

A built-in function runs in the executor JVM. A Python UDF needs a Python process. The executor sends rows to a Python worker and reads the results back.

BUILT-IN F.upper("name") Executor JVM generated code No Python process. Fastest path. PYTHON UDF @udf Executor JVM serializes rows Python worker one call per row pickle PANDAS UDF @pandas_udf Executor JVM column batches Python worker one call per batch Arrow

None of these three paths uses Py4J. The executor JVM and the Python worker talk over a plain socket.

from pyspark.sql import functions as F
import pandas as pd

# 1. Built-in: stays in the JVM
df.select(F.upper("name")).show()

# 2. Python UDF: Python calls the function one time for each row
@F.udf("string")
def up_row(s):
    return s.upper()
df.select(up_row("name")).show()

# 3. Pandas UDF: Python calls the function one time for each Arrow batch
@F.pandas_udf("string")
def up_batch(s: pd.Series) -> pd.Series:
    return s.str.upper()
df.select(up_batch("name")).show()
NOTE

When you define a UDF, Python pickles the function with cloudpickle. Py4J sends those bytes to the driver JVM one time. Spark then sends the bytes to the executors with the tasks.

09Python on the executors

A UDF does not run on one executor only. It runs on each executor that processes a partition of that stage. Each task applies the UDF to its part of the data.

What occurs on each executor

  1. The function arrives. The pickled bytes of your function come to the executor with the task.
  2. The executor JVM starts a Python worker. It starts the worker on the same machine, or it uses a worker that already runs.
  3. The JVM sends the rows. It sends them through a local socket, as pickle or as Arrow batches.
  4. The worker runs your code. It makes the function again from the bytes. It imports the libraries that the function uses. It calculates the results and sends them back.
  5. The JVM continues the task. It puts the results into the row stream.

When an executor starts Python

OperationPython worker
DataFrame and SQL with built-in functions: filter, groupBy, join, F.upper, spark.sql(...)No
Python UDF: @udf, @pandas_udfYes
mapInPandas, applyInPandas, mapInArrowYes
All RDD operations from Python: rdd.map, rdd.filter, df.rdd...Yes
df.foreach, df.foreachPartitionYes

Most PySpark jobs use at least one of these operations. Thus, install Python on all executor nodes.

What each executor node must have

# Error when the versions are different
Python in worker has different version 3.9 than that in driver 3.11

# Error when a library is only on the driver
ModuleNotFoundError: No module named 'pandas'
WARNING

Do not install a library only on the driver, for example with pip install in a notebook. The driver can import it, but the UDF fails on the executors.

Send one Python environment to all executors

# Pack a virtual environment
python -m venv env && source env/bin/activate
pip install pandas pyarrow venv-pack
venv-pack -o env.tar.gz

# Each executor unpacks the archive into its container directory
spark-submit \
  --archives env.tar.gz#env \
  --conf spark.pyspark.python=./env/bin/python \
  app.py

Other methods: on EMR, use a bootstrap action to install packages on each node. On Kubernetes or EMR on EKS, put the Python environment in the container image.

10Calls from the JVM to Python

Py4J also works in the opposite direction. PySpark starts a Py4J callback server in the Python driver process. The JVM can then call a Python object.

Driver JVM Streaming engine "batch 7 is ready" holds a proxy of your function Python driver Py4J callback server save_batch(df, 7) your code runs here call 2nd Py4J socket
def save_batch(batch_df, batch_id):
    # batch_df is a Python wrapper around a JVM Dataset
    batch_df.write.mode("append").parquet("/tmp/out")

query = (spark.readStream.format("rate").load()
         .writeStream.foreachBatch(save_batch)
         .start())

Other features that use callbacks: StreamingQueryListener in Python, and the old DStream API.

WARNING

Do not stop the Python driver while a streaming query runs. The JVM cannot call the callback. The query fails.

11Errors from the JVM

When a JVM method throws an exception, Py4J sends the error back. Python raises py4j.protocol.Py4JJavaError. PySpark converts many common Spark errors to Python classes, for example AnalysisException.

from py4j.protocol import Py4JJavaError
from pyspark.errors import AnalysisException

# PySpark converts this one
try:
    spark.sql("SELECT * FROM missing_table")
except AnalysisException as e:
    print("Spark error:", e)

# A raw JVM call keeps the Py4J error
try:
    spark._jvm.java.lang.Integer.parseInt("abc")
except Py4JJavaError as e:
    print(e.java_exception.getClass().getName())
    # java.lang.NumberFormatException
NOTE

Read the Java stack trace below the Python trace. The first Caused by: line usually shows the real cause.

12Java and Scala applications: no Python

A Java or Scala Spark application does not use Python.

spark-submit \
  --class com.example.MyJob \
  --master yarn \
  my-job.jar
NOTE

Python is necessary only if you start it yourself. For example, rdd.pipe("python3 script.py") runs an external program on each partition. Then each executor node must have Python.

For DataFrame and SQL code with built-in functions, PySpark and Scala have almost the same speed. Both send the same plan to the same JVM engine. The difference occurs with UDFs. A Scala UDF runs in the executor JVM. A Python UDF must send the data to a Python worker.

13Spark Connect: no Py4J

Spark 3.4 and later have Spark Connect. In this mode, the Python client does not start a JVM. It sends query plans to a remote server with gRPC.

spark = SparkSession.builder.remote("sc://spark-host:15002").getOrCreate()
spark.range(5).show()     # works
spark._jvm                # fails: no JVM gateway in Connect mode

Code that uses _jvm, _jsc or _jdf does not work with Spark Connect. Use only the public API if your code must run in both modes.

14Rules

RuleReason
DOUse built-in functions before UDFs.The data stays in the JVM.
DOUse pandas UDFs when you need Python code.Arrow batches cost less than one call per row.
DOEnable Arrow for toPandas().The transfer is faster.
DOUse the same Python minor version on the driver and the executors.PySpark stops the task if the versions are different.
DOInstall UDF libraries on all executors, or send them with --archives.The UDF runs on the executors, not on the driver.
DOIncrease spark.executor.memoryOverhead for heavy Python UDFs.Python workers use memory outside the JVM heap.
DO NOTCall JVM methods in a large Python loop.Each call is one socket round trip.
DO NOTUse the SparkSession in a UDF.Executors have no Py4J gateway.
DO NOTUse _jvm in code for Spark Connect.Connect has no local JVM.

Names and internals refer to PySpark 3.x and 4.x with Py4J 0.10.9.x. The wire format in section 06 is simplified to show the structure.