Arrow UDFs in Spark 3.5
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.
from pyspark.sql.functions import udf
@udf("string", useArrow=True)
def normalize_sku(raw):
if raw is None:
return None
head, _, tail = raw.strip().upper().partition("-")
return f"{head}-{tail.zfill(6)}"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.
import pandas as pd
from pyspark.sql.functions import pandas_udf, udf
@pandas_udf("double")
def order_total_pd(items: pd.Series) -> pd.Series:
return items.apply(
lambda arr: float(sum(x["qty"] * x["unit_price"] for x in arr))
)
@udf("double", useArrow=True)
def order_total(items):
return float(sum(x["qty"] * x["unit_price"] for x in items))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
- Do
- 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
- Avoid
- 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?
- Rewrite it as a Series-to-Series pandas UDF whose body calls s.apply(parse) on the batch
- Set spark.serializer to Kryo so the rows sent to the Python worker serialize faster
- Raise spark.sql.execution.arrow.maxRecordsPerBatch so fewer batches cross to Python
- Add useArrow=True to the existing @udf and keep the per-row body exactly as it is
About this lesson
This section is part of the UDFs and Serialization: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.