Python and the JVM

Part of the free LogicWiz Data Engineering course, Module 12: How Spark runs. The SQL and Python run in the app, on real Postgres and real Python in the browser.

It is Monday, 10:40. Your new tax column, written as a Python function, takes 41 minutes to compute. Last month's version, built from F.when and F.col, took 4. And on Friday night the same job lost two executors to exit code 137 with half the heap free. Nora says both have one cause: "Your Python does not run where you think it runs."

You'll learn to

  • Draw where PySpark code runs: Python, the JVM and the workers
  • Explain why a Python UDF is slow, and what Arrow changes
  • Find where Python's memory lives, and size it
  • Say what Spark Connect changes for your code

Learn

Python is the remote control

Start with what runs where. Spark's engine is a Java program: it runs in a JVM, the Java virtual machine. Your PySpark script is a Python program. On the driver the two run side by side, and a small bridge called Py4J passes your calls across.

When you write df.filter(...), no rows move. Python tells the JVM "add a filter to the plan", and the JVM does. Think of a remote control and a TV: the remote sends button presses, the TV does the work.

So a job built only from Spark's own functions (F.when, F.col, SQL) runs entirely in the JVM, as fast as the same job written in Scala. That is last month's 4 minutes.

Where PySpark code runs

The driver machine holds the Python process, the Py4J gateway and the driver JVM; each executor holds its JVM and one Python worker per running Python task, outside the heap.

Read the left box first: that is the driver, where your script runs. The orange box on the right only exists when your code makes the executors run Python.

A Python function sends the rows out

Your tax rule is different. It is a UDF, a user-defined function, written in Python. The JVM cannot run Python, so the rows have to go to Python.

Each executor starts Python workers: separate Python processes, one for each task running at that moment. A 4-core executor runs up to 4.

The task in the JVM packs some rows, sends them to its worker over a local socket, waits, and reads the answers back. That trip, repeated for every batch of rows, is where the extra 37 minutes go.

There is a second cost. Spark's optimiser cannot look inside your function. It cannot merge it into the code it generates, and it cannot use a filter on the function's result to skip data at the scan.

One batch of 100 rows goes to Python and back

A conversation between a task in the executor JVM and its Python worker in four steps: the JVM pickles 100 rows and sends them, Python unpacks them and calls the function 100 times, the results are pickled and sent back, and the same trip repeats for the next 100 rows.

  1. The JVM packs 100 rows. For each row it takes the two columns the function needs and turns them into bytes Python can read. That is called pickling. The batch goes to the Python worker over a local socket.

  2. Python unpacks, then calls your function. It rebuilds 100 tuples, one Python object for every value, then calls tax_udf once for each row: 100 calls.

  3. The results go back. Python pickles the 100 results and sends them. The JVM reads them and puts them into the rows. All this time the task in the JVM waited.

  4. And again. The next 100 rows make the same trip. For 25,000 rows that is 250 round trips, and 25,000 calls of your function.

Read it top to bottom. An arrow that returns to its own line is work done on that side.

Arrow: send columns, not rows

The slow part is not the socket. It is the work per row: an object built for every value, and a function call for every row.

Apache Arrow is a format that lays a table out column by column, as plain blocks of numbers. With it the JVM sends up to 10,000 rows in one Arrow batch, and Python turns each column into a pandas Series without touching the values one by one.

A pandas UDF takes whole Series and returns a Series. Spark calls it once per batch, and inside it NumPy does the arithmetic on a whole column at once. That is what vectorised means.

One Arrow batch's round trip

Five steps: rows in the executor JVM become a columnar Arrow batch, cross a socket to a Python worker as pandas Series, the function runs once, and the result batch returns to the JVM.

Follow the arrows: the same trip as before, but 10,000 rows travel together and your function runs once in the middle.

Count the round trips and the calls

import math, pickle
from array import array

# The UDF's input: (amount, country) for 25,000 order lines
rows = [(10.0 + i % 50, 'GB' if i % 3 else 'JP') for i in range(25_000)]

# Plain Python UDF: pickled batches of 100 rows, one call per row
calls = len(rows)
batches = math.ceil(len(rows) / 100)
pickled = sum(len(pickle.dumps(rows[i:i + 100], protocol=5)) for i in range(0, len(rows), 100))
print(f'pickled: {batches:4} socket round trips, {calls:6} calls, {pickled:7} bytes')

# pandas UDF: Arrow batches of up to 10,000 rows, one call per batch, a column is one buffer
batches = math.ceil(len(rows) / 10_000)
amounts = array('d', (r[0] for r in rows))                 # 8 bytes per value, like an Arrow float64 column
chars = ''.join(r[1] for r in rows).encode()               # an Arrow string column: the characters ...
arrow = len(amounts.tobytes()) + len(chars) + 4 * (len(rows) + 1)   # ... plus one 4-byte offset per row
print(f'arrow:   {batches:4} socket round trips, {batches:6} calls, {arrow:7} bytes')

The bytes are about the same. The work is not. Unpickling builds a tuple and a float object for every row before your function runs, and your function runs 25,000 times. Arrow hands pandas whole columns, three times. Spark's exact byte counts differ (its pickler and Arrow's headers), but the shape is the same.

Which one do you have? Read the plan

Runs on Databricks:

# @udf (a plain Python UDF)
*(2) Project [order_id#12L, amount#15, pythonUDF0#40 AS tax#30]
+- BatchEvalPython [tax_udf(amount#15, country#18)#29], [pythonUDF0#40]
   +- *(1) ColumnarToRow
      +- FileScan parquet [order_id#12L,amount#15,country#18] Batched: true, Format: Parquet, ...

# @pandas_udf (Series to Series)
*(2) Project [order_id#12L, amount#15, pythonUDF0#41 AS tax#31]
+- ArrowEvalPython [tax_pudf(amount#15, country#18)#30], [pythonUDF0#41], 200
   +- *(1) ColumnarToRow
      +- FileScan parquet [order_id#12L,amount#15,country#18] Batched: true, Format: Parquet, ...

Trimmed explain() output from Spark 3.5. Look at the second line of each plan. BatchEvalPython is the pickled trip: rows, 100 at a time. ArrowEvalPython is the Arrow trip. The 200 after it is the eval type of a scalar pandas UDF. Everything under the Python step, and the Project above it, runs in the JVM.

The kinds of Python function, side by side

KindDeclared asHow rows travelYour function runsStep in the plan
Python UDF@udfPickled, 100 rows per batch (Arrow by default from Spark 4.2)once per rowBatchEvalPython
Arrow Python UDF (3.5+)@udf(useArrow=True)Arrow batchesonce per rowArrowEvalPython
pandas UDF@pandasudf with Series type hintsArrow batches of up to 10,000 rowsonce per batchArrowEvalPython
Iterator pandas UDFIterator[pd.Series] type hintsArrow batchesonce per partition, looping over batchesArrowEvalPython
Grouped mapgroupBy().applyInPandas()Arrow, one whole group at a timeonce per groupFlatMapGroupsInPandas
MapmapInPandas()Arrow batchesonce per partition, looping over DataFramesMapInPandas

Watch the grouped map. It ignores the 10,000-row limit: every row of a group sits in one Python worker at once, so one hot key can fill it.

Friday: four workers on the balcony

Now Friday's kill. A Python worker is a separate process, so its memory is not in the JVM heap. It sits on the balcony from Lesson 12.8: the overhead, 819 MB on an 8 GB executor.

Unless you say otherwise, nothing limits a worker. It shares the overhead with the JVM's own needs, and grows until the whole container passes its limit. Then the cluster kills the executor: exit code 137, heap half empty.

You can give Python its own allowance instead: spark.executor.pyspark.memory. Spark adds it to the container and divides it between the workers. A worker that passes its share gets a Python MemoryError: one task fails with a readable traceback, and the executor lives.

Step through Friday night

An 8 GB, 4-core executor runs a pandas UDF: four Python workers of 600 MB each overflow the 819 MB overhead and the container is killed, while the heap still has room.

Step to the kill. Then raise spark.executor.memoryOverheadFactor, or set spark.executor.pyspark.memory, and step again: the kill turns into a fit, or into a Python MemoryError.

Three fixes, best first

Each worker held 600 MB: one batch of 10,000 wide rows, plus the copies pandas made of it. Four workers need 2,400 MB, and the JVM needs about 300 MB of its own outside the heap. That is 2,700 MB on a balcony of 819 MB.

  • Hold less per worker. Send smaller batches (a lower spark.sql.execution.arrow.maxRecordsPerBatch), pass only the columns the function needs, make fewer copies.
  • Give Python its own allowance. spark.executor.pyspark.memory=4g is 1 GB per worker. The container becomes 9,011 + 4,096 = 13,107 MB.
  • Or raise the overhead to about 3 GB.

What does not help: a bigger heap. spark.executor.memory=16g adds only 819 MB of overhead.

What fits outside the heap

Bars comparing the 2,700 MB the Python workers and the JVM need outside the heap with the overhead of an 8 GB heap, the overhead of a 16 GB heap, and an overhead raised to 3 GB.

Compare every bar with the red one: only the last is longer than what Python and the JVM need.

Remember: Python runs outside the JVM. Its speed problem is the trip and the call per row. Its memory problem is the balcony.

Bringing rows home: toPandas

There is one more place where rows meet Python: the driver. df.toPandas() brings every row to the driver and builds a pandas DataFrame there.

Without Arrow the rows are pickled, turned into Row objects, then into pandas: slow, and for a while the data exists several times over. With Arrow turned on (spark.sql.execution.arrow.pyspark.enabled=true) the executors send Arrow batches and pandas builds its columns from them. Much faster. But the data still sits in the driver's JVM, in Arrow and in pandas at once.

createDataFrame(pandas_df) is the same road in the other direction. Before either call, work out the size: rows × bytes per row, against spark.driver.memory.

How big would toPandas be?

import pandas as pd

orders = pd.read_csv('data/orders.csv')
per_row = orders.memory_usage(deep=True).sum() / len(orders)
print(len(orders), 'orders,', round(per_row), 'bytes per row in pandas')
for rows in (1_000_000, 50_000_000):
    print(f'{rows:>11,} rows: {rows * per_row / 1024 ** 3:6.2f} GB in pandas alone')

Text columns cost the most: pandas keeps each string as a Python object. Against a 1 GB driver even the first line is a problem once the JVM's and Arrow's copies are added.

Spark Connect: the remote moves out

Until now the remote control and the TV shared a machine. Since Spark 3.4 they can live apart. This is Spark Connect.

Your Python program becomes a thin client. It builds the plan, sends it over the network to a Spark Connect server, where the driver runs, and gets the results back as Arrow batches.

What changes for you:

  • No JVM on your side.
  • No RDDs: df.rdd and sc.parallelize fail, because there is no SparkContext to talk to. Databricks serverless runs through Spark Connect, so code there must avoid both.
  • A mistyped column name fails when the plan runs, at the action, not at the select.
  • Python UDFs still run in Python workers on the cluster, so the cluster needs their libraries.

Spark Connect: who talks to whom

A Python client builds an unresolved plan and sends it over gRPC to the Spark Connect server, which plans and runs it on the executors and streams Arrow batches back to the client.

Read it top to bottom. Your program is the left line: it never holds a JVM, only a plan going out and Arrow batches coming back.

Pick the cheapest tool that works

In order of preference:

  1. Spark's own functions (F.when, F.regexp_extract, SQL). No Python on the executors at all.
  2. A pandas UDF, when nothing built in fits: a tokenizer, a geocoder, a model. Inside it, work on whole columns (amounts * rate, Series.map): a Python loop over the rows throws the gain away. To load a model once, not once per batch, use the iterator form or mapInPandas: they get all of a partition's batches in one call.
  3. A plain Python UDF. A pickle and a call per row. Fine for small data, slow for large.

Two habits on top. Pass a UDF only the columns it needs: every input column makes the trip. And never collect() or toPandas() big data to do in Python what Spark could do in place.

A Python UDF for something Spark already does (upper-casing, parsing a date, a CASE expression) is the most common PySpark slowdown found in code review. And a container killed while Python runs is not fixed by a bigger spark.executor.memory: Python lives outside the heap.

Numbers to remember

SettingDefaultWhat it is
Pickled batch100 rowsHow many rows a plain Python UDF sends per trip. A setting since Spark 4.0: spark.sql.execution.python.udf.maxRecordsPerBatch.
spark.sql.execution.arrow.maxRecordsPerBatch10,000 rowsThe largest Arrow batch sent to a pandas UDF. applyInPandas ignores it.
@udf(useArrow=True)added in Spark 3.5An Arrow-optimised Python UDF: still one call per row, but the rows travel as Arrow. From Spark 4.2 plain Python UDFs use Arrow by default (spark.sql.execution.pythonUDF.arrow.enabled).
spark.python.worker.reusetrueA Python worker serves task after task. Workers are forked from one pyspark.daemon process.
spark.executor.pyspark.memorynot setPython's own allowance: added to the container, divided by the executor's task slots. It is enforced through Python's resource module: Windows cannot enforce it, and macOS does not.
Overhead factor on Kubernetes0.40 for non-JVM jobsInstead of 0.10: PySpark pods get more room outside the heap, because Python lives there.
spark.sql.execution.arrow.pyspark.enabledfalse in open-source Spark 3.5 and 4.0Arrow for toPandas() and createDataFrame(pandasdf).
spark.sql.execution.arrow.pyspark.selfDestruct.enabledSpark 3.2+, experimentalFrees the Arrow copy as pandas takes it over, so toPandas() peaks lower.
Spark ConnectPython client since Spark 3.4, Scala since 3.5The client sends unresolved logical plans as protocol buffers over gRPC to a server on port 15002. Since Spark 4.0 a pure-Python package of about 1.5 MB, pyspark-client, is all your side needs.

Teams keep Python UDFs for logic with no built-in. Model scoring is usually an iterator pandas UDF or mapInPandas that loads the model once per worker and scores batch by batch.

What changed at SwiftKart

You rewrote the tax rule with F.when. No Python worker starts at all, and the column is back to 4 minutes.

The fraud score has no built-in, so it stays in Python: an iterator pandas UDF that loads its model once per partition. It now has its own allowance, spark.executor.pyspark.memory=4g, and Friday's kills have stopped.

Nora adds a line to the review checklist: a Python function for something Spark already does is a bug.

You now know the engine's parts: plans, shuffles, memory, Python. The last lesson of this module puts them to work on evidence: five slow jobs, five case files. That is Lesson 12.12, Tuning from evidence.

In one line

PySpark is a Python remote control for a JVM: Spark's own functions never touch Python, a Python UDF ships rows to Python workers on the executors (a call per row when pickled, a call per batch with Arrow and pandas), those workers' memory sits outside the heap, and Spark Connect moves the remote to another machine and drops the RDD API.

Interview corner

Why is a Python UDF slower than a built-in function?

A built-in function is compiled into the stage's generated JVM code and works on Spark's binary rows. A Python UDF makes the executor serialize the input columns, send them over a local socket to a separate Python worker, call the function once per row, and send results back the same way: 100-row pickled batches, with an object built per value. Catalyst also cannot see inside the UDF, so it cannot push filters on its output into the scan or fuse it into code generation.

Compare a Python UDF, an Arrow-optimised Python UDF and a pandas UDF.

A plain Python UDF pickles rows in batches of 100 and calls the function once per row (BatchEvalPython). An Arrow-optimised Python UDF, useArrow=True since Spark 3.5 and the default for plain UDFs from Spark 4.2, still calls the function per row but moves data as Arrow batches with clearer type handling. A pandas UDF receives Arrow batches of up to 10,000 rows as pandas Series and is called once per batch, so vectorised NumPy code inside it is fast. The iterator form and mapInPandas let you load a model once per partition.

An executor running a pandas UDF is killed with exit code 137 while its heap is half empty. Why, and what do you change?

Python workers are separate processes, one per running task, and their memory sits outside the JVM heap, in the container's overhead, which defaults to 10% of the heap. Four workers holding a few hundred MB each easily pass an 819 MB overhead, so the container is killed. I would shrink what each worker holds (lower maxRecordsPerBatch, fewer columns, no giant groups in applyInPandas), then give Python room with spark.executor.pyspark.memory or more overhead. A bigger heap barely moves the overhead.

What is Spark Connect, and what breaks when you move to it?

Since Spark 3.4 the client can be separate from the driver: it builds unresolved logical plans, sends them as protocol buffers over gRPC to a Spark Connect server, and receives results as Arrow batches. The client needs no JVM; in Spark 4.0 a small pyspark-client package is enough. What breaks is anything that needs the driver JVM: the RDD API, sparkContext, and private _jdf tricks, and errors from bad column names appear only when an action runs. Databricks serverless supports only Spark Connect APIs for this reason.