UDFs and Serialization: Advanced
A plain @udf runs under BatchEvalPython, and you pay for it value by value. The executor converts each field of an UnsafeRow into a Java object, a pickler on the JVM side turns those objects into bytes, and the Python worker unpickles every value into a fresh Python object before your function sees it. The result makes the same trip in reverse. A function that adds 1 to a number still costs several object allocations per field and 1 interpreted function call per row, and on a table of billions of rows those fixed costs are the job.
A layout both runtimes share
| Buffer | product_name (string) | price (double) |
|---|---|---|
| Validity bitmap | 1 1 1 1 | 1 0 1 1 |
| Offsets | 0, 6, 9, 13, 17 | None, the width is fixed |
| Values | kettlemuglampvase | 19.99, unused, 5.00, 42.50 |
One partition's round trip: the task copies a batch of rows into Arrow columns, streams them over a local socket to the Python worker, the worker hands pandas Series to your function, and the result batch comes back to the next operator in the same stage.
What changes per row
- Every field becomes a Java object, then pickle bytes, then a Python object
- Your function runs once for every row
- A null arrives as None, a number as a boxed Python int or float
- Cost scales with rows times columns, however short the function
- Each column is copied once into Arrow buffers on the JVM side
- Your function runs once per batch, on whole pandas Series
- A numeric column becomes a numpy array in one bulk conversion
- Python call overhead is paid per batch, so cost tracks bytes moved
A setting, spark.sql.execution.arrow.maxRecordsPerBatch, caps the rows in a batch, and a batch never spans 2 partitions, so a partition under the cap crosses as a single batch. Bigger batches spread the per-call overhead across more rows, but the worker holds the whole batch as pandas objects at once. That memory belongs to the Python process, outside the JVM heap, and counts against spark.executor.memoryOverhead, so a wide table with long strings and a raised cap is a direct route to the memoryOverhead OOM.
What the plan and the Spark UI show
In explain(), a vectorized UDF appears as ArrowEvalPython where a plain one showed BatchEvalPython. Both are narrow operators: the round trip to Python happens inside the current stage, with no exchange, so the stage count and the shuffle read and write columns in the Spark UI stay put when you switch. The number that moves is task duration for the stage holding the UDF, and that is the one to record before and after.
A table has 200 partitions of 250,000 rows each, and a Python UDF reads one numeric column. How many times does Python invoke the function body as a plain @udf, and as a Series-to-Series @pandas_udf with the default batch cap?
@pandas_udf takes the Spark return type, and the Python type hints on your function tell Spark which variant you mean. The workhorse takes 1 pd.Series per input column and returns a pd.Series with exactly as many values. Inside, your pandas or numpy code works on the whole Series at once. price * 1.2 multiplies every row of the batch in one vectorized operation, and Spark checks only that the output length matches the input.
import pandas as pd
from pyspark.sql.functions import col, pandas_udf
@pandas_udf("double")
def with_vat(price: pd.Series) -> pd.Series:
return (price * 1.2).round(2)
result = (
spark.table("products")
.where(col("price").isNotNull())
.select(
"product_id",
"product_name",
"price",
with_vat("price").alias("price_with_vat"),
)
)
result.show()The function sees only its batch
Each call gets 1 batch, so anything that summarizes the Series inside a Series-to-Series UDF summarizes the batch. price - price.mean() subtracts the mean of whichever rows shared the batch, and the answer shifts if the table is repartitioned, the batch cap is raised, or a filter upstream drops rows. Spark raises no error, because the output length still matches. A statistic over a whole column or a whole group belongs in a built-in aggregate joined back to the rows, or in one of the grouped variants below.
This UDF runs over a 3-million-row table stored in 12 partitions, with the default batch cap. What does each output row hold?
The variants and what each costs
| Shape | Each call receives | Called from | Shuffle | Plan node |
|---|---|---|---|---|
| `Series` to `Series` | 1 batch per input column | `select`, `withColumn` | None | `ArrowEvalPython` |
| `Iterator[Series]` to `Iterator[Series]` | Every batch of 1 partition, streamed | `select`, `withColumn` | None | `ArrowEvalPython` |
| `Series` to scalar | Every value of 1 group | `groupBy().agg()`, windows | All rows, no partial aggregation | `AggregateInPandas` |
| `applyInPandas` | 1 whole group as a DataFrame | `groupBy()` | All rows, by key | `FlatMapGroupsInPandas` |
| `mapInPandas` | Every batch of 1 partition as DataFrames | The DataFrame itself | None | `MapInPandas` |
Setup once per partition
The iterator variant hands your function every batch of 1 partition through a generator, so the line above the for loop runs once per task. The same load inside a Series-to-Series UDF would repeat for every batch: a 400-partition job with 25 batches per partition would read a 200MB model 10,000 times instead of 400. Python workers are reused across tasks by default, so keeping the loaded model in a module-level variable of a module shipped to the executors can cut the loads further, toward 1 per worker.
Groups bring a shuffle and a whole group in memory
A Series-to-scalar UDF in groupBy().agg() and applyInPandas both need every row of a key inside one Python call, so Spark hash-partitions on the grouping key first. Neither combines rows before the exchange: where F.avg sends 1 partial sum and count per key per map task, a pandas aggregate sends every row. On the reducer, the whole group is materialized as one pandas object, so a hot key with 40 million rows becomes a 40-million-row DataFrame in one worker's memory: skew and an OOM risk at the same time.
import pandas as pddef center(pdf: pd.DataFrame) -> pd.DataFrame:pdf["centered"] = pdf["value"] - pdf["value"].mean()return pdfresult = readings.groupBy("sensor").applyInPandas(center, schema="sensor string, value double, centered double")result.collect()
Some logic has no vectorized form: a parser from an internal library, a chain of string rules with early returns, a walk through a nested record. Written as a pandas UDF, it turns into s.apply(f), a Python loop that still calls f once per row, so the batch buys no speed and the body now reads as pandas wrapped around per-row code. Left as a plain UDF, it keeps its readable signature but pays the pickle transport on every value. Spark 3.5 adds a path for exactly this case: keep the row-at-a-time function and replace only the pickle transport beneath it.
With useArrow=True on the decorator, or spark.sql.execution.pythonUDF.arrow.enabled set to true for the session (it defaults to false in 3.5), the executor ships Arrow batches in place of pickled rows. Inside the 3.5 worker, each batch is still converted to pandas Series, then zipped back into rows: your function is called once per row with Python values that match the declared types, a struct arrives as a Row, and the results are packed back into Arrow. explain() shows ArrowEvalPython in place of BatchEvalPython. Pickling disappears on both sides, while the Arrow-to-pandas conversion and the per-row call both stay, so the gain is largest when the pickle frames dominated the profile and the body was cheap.
| Property | Plain @udf | Arrow-optimized @udf | @pandas_udf |
|---|---|---|---|
| Wire format | Pickle | Arrow | Arrow |
| Calls to your function | 1 per row | 1 per row | 1 per batch |
| A value arrives as | Python object | Python object | Element of a pandas Series |
| A null arrives as | `None` | `None` | `NaN`, `None` or `NaT`, by dtype |
| Pays off when | It is the baseline | The border dominated the profile | The body vectorizes |
Nested data and pandas
pandas has no nested column type, so the conversion improvises. A struct argument arrives in a pandas UDF as a pd.DataFrame with one column per field, and returning a struct means returning a DataFrame. An array arrives as an object-dtype Series holding a numpy array per row, and an array of structs holds numpy arrays of dicts. None of those shapes vectorize: any work on the elements is a Python loop over objects that pandas allocated for you, on top of the conversion that built them.
Neither version vectorizes this order total, so both pay the Arrow-to-pandas conversion inside the worker. The Arrow-optimized one still wins on its own terms: it reads like the plain UDF your team already reviewed, each item arrives as a Row rather than a pandas shape, and, compared with the plain UDF, no value is pickled. Better still, the computation needs no Python: F.aggregate("items", F.lit(0.0), lambda acc, x: acc + x.qty * x.unit_price) is a higher-order built-in that runs in the JVM with no border at all, though like the other higher-order functions it falls back from generated code. When nested data must reach Python and stay columnar, mapInArrow, available since 3.3, hands your function pyarrow RecordBatch objects, which represent nested types natively and come with compute functions that work on them.
Choosing between them
- Use a pandas UDF when the body is pandas or numpy math over whole columns
- Add useArrow=True to an existing per-row UDF when the profile shows the pickle border
- Try a higher-order built-in such as aggregate or transform before any UDF on arrays
- Run old and new UDFs on a sample and diff outputs before enabling the session config
- Wrap per-row logic in s.apply inside a pandas UDF and expect a speedup
- Pass a struct column to a pandas UDF expecting a Series of dicts
- Assume a mismatched return value coerces the same way on both transports
- Reach for useArrow when the slow part is your own Python body
A plain @udf parses each user_agent string with a Python library that has no vectorized API, across 900 million rows. The flame graph shows the JVM spending most of its samples pickling. Which change targets that cost with the least rewriting?
Serialization also happens with no Python anywhere in sight. Spark turns JVM objects into bytes to shuffle an RDD, to keep a cached block in a serialized storage level, to ship a broadcast variable, and to send every task from the driver to an executor. spark.serializer picks the library for the first 3, and its default is org.apache.spark.serializer.JavaSerializer. Task closures always use Java serialization, whatever the setting says.
What each serializer writes
Java serialization writes a class descriptor before the data. The descriptor holds the full class name and a version id, followed by every field's name and type, and then the serializer walks the object graph by reflection. Within one stream a repeated descriptor becomes a back-reference, but Spark resets the stream every spark.serializer.objectStreamReset objects, 100 by default, so descriptors are written again and again. Kryo writes a small integer for each registered class and uses per-class serializers that write field values in order, with no field names. A class you never registered still works, but Kryo then stores its full class name with each object, as the Spark tuning guide warns.
Turning it on
The serializer is fixed when the session starts, so it belongs in the builder or in spark-submit, never in a spark.conf.set call mid-job. registrationRequired makes the first unregistered class fail its task with an error naming the class, which turns a silent size penalty into a list of names to add. buffer.max caps a single serialized object, and a Buffer overflow error means one record or broadcast value outgrew it, often a large lookup map built in JVM code.
Where the setting changes nothing
| Data path | Bytes written by | Does spark.serializer matter? |
|---|---|---|
| DataFrame shuffle | `UnsafeRow` binary, copied as is | No |
| DataFrame `cache()` | Compressed columnar batches | No |
| DataFrame broadcast join | The hash relation's own binary format | Barely |
| Python UDF border | Pickle or Arrow | No |
| Python RDD records | Pickled in Python, byte arrays in the JVM | Barely |
| RDD of JVM objects: shuffle, serialized cache | `spark.serializer` | Yes |
| Broadcast of a JVM object | `spark.serializer` | Yes |
| Task closures | Java serialization, always | Not configurable |
Python has a serializer choice of its own for RDD records: pickle by default, or a marshal-based serializer passed when the SparkContext is created, faster but limited to Python's built-in types. It changes the byte arrays the JVM receives, which the JVM treats as opaque, so spark.serializer plays no part in it.
- ▸Does any stage run on an RDD of JVM objects? RDD jobs have no query behind them in the SQL tab.
- ▸Is a broadcast variable built by JVM code, such as a map from a library? It passes through spark.serializer.
- ▸Does a flame graph show ObjectOutputStream frames inside shuffle writes or cached-block writes? That is the cost Kryo removes.
A job built only from DataFrame operations writes 400GB of shuffle per run. The team sets spark.serializer to Kryo with every custom class registered. What happens to shuffle write in the Spark UI?
A sampling profiler attached to an executor records JVM stacks, so it sees only half of a Python UDF job. In Spark 3.x, each task that talks to Python has 2 JVM threads worth reading: the task thread, which runs the stage and reads results back from the worker, and a writer thread named after the Python executable, such as stdout writer for python3, which pushes input rows to the worker. The Python worker is a separate process, so its CPU time is missing from the graph and shows up indirectly, as the task thread blocked reading a socket.
Frames that mean serialization
| Frame | Thread | What it means |
|---|---|---|
| `net.razorvine.pickle.Pickler.dump` | Writer | Rows pickled for a plain `@udf` |
| `EvaluatePython.toJava` | Writer | Spark values turned into pickle-ready Java objects |
| `Unpickler.load`, `EvaluatePython.makeFromJava` | Task | Results unpickled and turned back into Spark values |
| `ArrowWriter.write` | Writer | Row values copied into Arrow column vectors |
| `socketRead0` or `NioSocketImpl.read` under the Python reader | Task | JVM idle, waiting for the Python worker |
| `ObjectOutputStream.writeObject0` | Shuffle writer, block manager | Java serialization of RDD records or broadcasts |
| `Kryo.writeClassAndObject` | Shuffle writer, block manager | Kryo serialization of those same objects |
| `DefaultClassResolver.writeName` | Under Kryo frames | Full class names written for unregistered classes |
Reading one profile
| Frames | Share of executor samples |
|---|---|
| `Pickler.dump`, `EvaluatePython.toJava` | 31% |
| `Unpickler.load`, `EvaluatePython.makeFromJava` | 14% |
| Socket read, waiting on the Python worker | 38% |
| Parquet scan and the generated stage code | 12% |
| Everything else | 5% |
45% of the samples is the JVM side of the pickle border, and 38% is the JVM waiting while Python unpickles, calls the function per row and pickles the results. Both point the same way. If the body vectorizes, a pandas UDF removes the pickle frames and divides the Python calls by the batch size. If it does not, useArrow=True removes the pickle frames and leaves the socket wait, which is now mostly your function, for a profile on the Python side to explain. With a scan share this small, reading the data was never the problem.
- ▸
Pickler.dumpandEvaluatePythonwide: the pickle border. Move to a pandas UDF if the body vectorizes,useArrow=Trueif it does not. - ▸Socket read wide, border frames thin: the Python body itself is slow. Profile it in Python first, and once you know where the time goes, vectorize the body or replace it.
- ▸
ArrowWriter.writewide: more columns cross than the function needs. Select only the columns it reads before the call. - ▸
ObjectOutputStreamin shuffle or block writes: Java serialization on RDDs or broadcasts. Switch to Kryo. - ▸Kryo frames with
DefaultClassResolver.writeName: unregistered classes. Register them, then setregistrationRequired.
Check every fix the way you found the problem: compare the stage's task time in the Spark UI before and after, then capture a new graph and confirm the frames you targeted shrank. A fix that moves work from one frame family to another, say from Pickler.dump to ArrowWriter.write, should still shrink the total. If the total holds steady, read the new graph again before choosing the next fix: a wide ArrowWriter.write means columns the function never reads are crossing, and a wide socket wait means the Python body itself is now the cost.
After a move to a pandas UDF, a stage's flame graph shows ArrowWriter.write at 40% of executor samples. The UDF is called on F.struct(*df.columns) over a 60-column table, and its body reads 2 fields. What should change?
> A card-payments team scores 600 million transactions each night with a Python fraud model applied through a plain UDF, then averages the score per merchant. The stage holding the UDF runs for 3 hours, and a flame graph of one executor shows most samples in pickling frames and socket waits. The model's arithmetic vectorizes, the merchant average needs no Python, and a lookup table of merchant tiers is broadcast from Python.
Arrow batches for Python UDFs, the right JVM serializer, and how to find serialization cost in a flame graph.
- Category
- Spark
- Difficulty
- advanced
- Duration
- 15 minutes
- Challenges
- 13 hands-on challenges
Topics covered: Arrow at the Border, pandas_udf, Arrow UDFs in Spark 3.5, Kryo vs Java Serialization, Serialization in a Flame Graph
Lesson Sections
- Arrow at the Border
A layout both runtimes share Apache Arrow is a columnar memory format with a published specification. Its Java and Python libraries read and write the same bytes. A record batch stores each column as a few contiguous buffers. Fixed-width values sit back to back in a values buffer, and a validity bitmap marks nulls with 1 bit per row. Strings and other variable-length types add an offsets buffer that records where each value starts. Since the executor and the Python worker agree on that layout, t
- pandas_udf
The cell below adds a price with 20% VAT to every product that has a price. Run it, then add rating as a second argument and return price * rating: every extra input column arrives as another Series, aligned row for row with the first. The function sees only its batch The variants and what each costs Only rows 3 and 4 add an exchange, because a group has to be complete before Python sees any of it. The remaining rows are narrow and run inside the current stage. Setup once per partition Groups br
- Arrow UDFs in Spark 3.5
Nested data and pandas Choosing between them
- Kryo vs Java Serialization
What each serializer writes Turning it on Where the setting changes nothing For a job built from DataFrames and Python, switching to Kryo moves no number in the Spark UI that you could attribute to it. Even for RDDs, Spark has used Kryo internally since 2.0 when it shuffles primitives and strings, and arrays of primitives get the same treatment. The setting matters in JVM code that keeps RDDs of custom classes. Graph and iterative algorithms do this, and so does the ALS recommender in Spark's ML
- Serialization in a Flame Graph
Frames that mean serialization Reading one profile The table below is one illustrative capture from a 40-minute stage that applies a plain Python UDF to a Parquet table, with samples grouped by the frame families above. Real profiles vary, and the proportions are what you read.