How your Python code controls the Spark JVM.
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.
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.
| Direction | Reason | Example | Channel |
|---|---|---|---|
| Python → JVM | Build the query plan. Python has no plan object. | df.filter(...) | Py4J |
| Python → JVM | Start the work. Only the JVM can schedule tasks. | df.count(), df.write | Py4J |
| Python → JVM | Get results, schemas and settings back. | df.schema, collect() | Py4J + local socket |
| Python → JVM | Control the session. | spark.conf.set(...), spark.stop() | Py4J |
| JVM → Python | Run your Python function on the data. The JVM cannot run Python code. | UDF, rdd.map(lambda ...) | Plain socket on each executor |
| JVM → Python | Call your Python code when an event occurs. | foreachBatch | Py4J callback |
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.
A PySpark application has two kinds of Python process. Each kind uses a different connection to the JVM. The diagram shows both.
Py4J connects only the two processes on the driver. The executors use a different, faster channel.
The Python SparkSession and DataFrame objects hold no data. Each one holds an ID that points to a real object in the JVM.
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.
| Part | Setting | Purpose |
|---|---|---|
| Heap | spark.executor.memory | Execution memory (shuffle, join, sort, aggregation), storage memory (cache, broadcast) and user memory. |
| Overhead | spark.executor.memoryOverhead | Memory outside the heap: JVM internals, Netty buffers, native libraries and the Python workers. |
| Task slots | spark.executor.cores | The number of tasks that run at the same time. Each task is a thread, not a process. |
| BlockManager | spark.blockManager.port | Keeps cached partitions, shuffle files and broadcast pieces. Sends them to other executors. |
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.
The driver JVM and the executor JVMs use Spark RPC. Spark RPC uses Netty over TCP. It does not use Py4J.
The numbers match the steps below. The driver controls the work. The executors move the data. Four task slots means spark.executor.cores = 4.
DriverEndpoint and sends RegisterExecutor. The driver records its ID, host and cores.LaunchTask message. The code of the stage goes to the executors one time, as a broadcast.StatusUpdate messages. A small result goes in the message. A large result stays in the BlockManager, and the driver gets it from there.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.MapOutputTracker where the blocks are. Then they get the blocks directly from the other executors, or from the external shuffle service.TorrentBroadcast), not only from the driver.collect(), take(), toPandas().| Channel | Between | Carries |
|---|---|---|
| Py4J | Python driver ↔ driver JVM (same machine) | Method calls, object IDs, small values, callbacks |
| Spark RPC | Driver JVM ↔ executor JVMs, and executor ↔ executor | Tasks, status, heartbeats, shuffle and broadcast data |
| Plain socket | Executor JVM ↔ its Python workers (same machine) | Rows for Python UDFs, as pickle or Arrow |
The start sequence has two forms. The form depends on which process starts first.
spark-submit app.pyspark-submit starts the class org.apache.spark.deploy.PythonRunner.PYSPARK_GATEWAY_PORT and PYSPARK_GATEWAY_SECRET.JavaGateway client.SparkContext asks the gateway to make a JVM JavaSparkContext. Python keeps the ID of that object.python app.py or a notebooklaunch_gateway() runs spark-submit pyspark-shell as a child process.# 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
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.
Most PySpark API methods do one thing only. They send one Py4J call to the JVM. This example follows df.filter("age > 30").
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())
| Python value | Sent as | JVM value |
|---|---|---|
int, float, bool, str, None | Value in the command text | Integer/Long, Double, Boolean, String, null |
list, dict | Converted copy (PySpark enables auto_convert) | ArrayList, HashMap |
Python wrapper (JavaObject) | ID only, for example o42 | The original JVM object |
| Other Python objects | Not supported | Error |
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.
PySpark gives you access to the gateway. Use it to call JVM classes that PySpark does not wrap.
| Attribute | Points to |
|---|---|
spark._jvm | The root of all JVM packages. Example: spark._jvm.java.lang.System |
spark._jsparkSession | The JVM SparkSession |
sc._jsc | The JVM JavaSparkContext |
df._jdf | The JVM Dataset<Row> |
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())
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.
print(spark._jvm.java.lang.System.getProperty("java.version"))
print(spark._jsparkSession.version()) # Spark version from the JVM
Py4J sends only small values and IDs. Large data uses other paths. Know these paths. They control the speed of your job.
collect() and toPandas()spark.conf.set("spark.sql.execution.arrow.pyspark.enabled", "true")
pdf = df.toPandas() # Arrow batches over a local socket, not Py4J
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.
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()
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.
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.
| Operation | Python worker |
|---|---|
DataFrame and SQL with built-in functions: filter, groupBy, join, F.upper, spark.sql(...) | No |
Python UDF: @udf, @pandas_udf | Yes |
mapInPandas, applyInPandas, mapInArrow | Yes |
All RDD operations from Python: rdd.map, rdd.filter, df.rdd... | Yes |
df.foreach, df.foreachPartition | Yes |
Most PySpark jobs use at least one of these operations. Thus, install Python on all executor nodes.
spark.pyspark.python or PYSPARK_PYTHON. The minor version must be the same as the driver's version.spark-submit sends pyspark.zip and the Py4J zip to the executors. It adds them to PYTHONPATH.# 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'
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.
# 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.
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.
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.
Do not stop the Python driver while a streaming query runs. The JVM cannot call the callback. The query fails.
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
Read the Java stack trace below the Python trace. The first Caused by: line usually shows the real cause.
A Java or Scala Spark application does not use Python.
main() method calls the Spark API directly. There is no Python process and no Py4J gateway.spark-submit \
--class com.example.MyJob \
--master yarn \
my-job.jar
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.
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.
| Rule | Reason | |
|---|---|---|
| DO | Use built-in functions before UDFs. | The data stays in the JVM. |
| DO | Use pandas UDFs when you need Python code. | Arrow batches cost less than one call per row. |
| DO | Enable Arrow for toPandas(). | The transfer is faster. |
| DO | Use the same Python minor version on the driver and the executors. | PySpark stops the task if the versions are different. |
| DO | Install UDF libraries on all executors, or send them with --archives. | The UDF runs on the executors, not on the driver. |
| DO | Increase spark.executor.memoryOverhead for heavy Python UDFs. | Python workers use memory outside the JVM heap. |
| DO NOT | Call JVM methods in a large Python loop. | Each call is one socket round trip. |
| DO NOT | Use the SparkSession in a UDF. | Executors have no Py4J gateway. |
| DO NOT | Use _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.