User-defined function (Spark)
| Also known as | UDF, Spark UDF, PySpark UDF |
|---|---|
| Field | Distributed data processing |
| Introduced | Python UDFs since Spark 1.3.0 (pyspark.sql.functions.udf)
|
| Key parts | Function body, return type, evaluation type (JVM, pickled Python, Arrow-optimized Python, pandas, Arrow) |
| Open source implementations | Apache Spark |
| Related | Pandas UDF, Arrow-optimized Python UDF, Python UDTF, Apache Arrow, Spark Connect |
In Apache Spark, a user-defined function (UDF) is a function written by the user in Scala, Java, Python or SQL and registered with Spark so that it can be called on columns of a DataFrame or in a Spark SQL query, like a built-in function.[1] A scalar UDF acts on one row and returns one value.[1] PySpark offers several kinds of Python UDF that differ in how data moves between the Java virtual machine (JVM) and the Python worker: pickled Python UDFs, Arrow-optimized Python UDFs, pandas UDFs and Arrow UDFs. The choice decides how much serialization overhead each call pays.[2]
What kinds of UDF does Spark support?
The PySpark user guide for Spark 4.3.0 names three main categories of Python UDF: scalar Python UDFs, pandas UDFs and Arrow UDFs.[2]
- Scalar Python UDFs take and return Python objects one row at a time. The objects are serialized with pickle (through cloudpickle) or with Apache Arrow.[2]
- Pandas UDFs, also called vectorized UDFs, take and return pandas
SeriesorDataFrameobjects and work on a batch of rows at a time; Arrow carries the data.[2] - Arrow UDFs take and return
pyarrow.Arrayobjects (or iterators of them) directly, without converting to pandas.[2][3]
JVM UDFs are written in Scala or Java with udf(...) and spark.udf.register, and the class UserDefinedFunction provides asNonNullable, asNondeterministic and withName.[1] Spark SQL also has SQL UDFs, created with CREATE FUNCTION ... RETURN, whose body is a SQL expression or query and which can return a scalar or a table.[4] Functions that return a table from Python are Python user-defined table functions.
Spark UDF types compared
| JVM UDF (Scala/Java) | Pickled Python UDF | Arrow-optimized Python UDF | Pandas UDF | Arrow UDF | |
|---|---|---|---|---|---|
| How it is defined | udf(...), spark.udf.register[1]
|
@udf(..., useArrow=False) or with spark.sql.execution.pythonUDF.arrow.enabled=false[5]
|
@udf (default since Spark 4.2) or useArrow=True[5]
|
@pandas_udf with pandas type hints[6]
|
@arrow_udf, or @udf with pyarrow.Array type hints[3]
|
| Where the code runs | Inside the executor JVM | Python worker process | Python worker process | Python worker process | Python worker process |
| Unit of work for the function | One row | One row[2] | One row; data moves in Arrow batches[6] | A batch, as pandas Series or DataFrame[2]
|
A batch, as pyarrow.Array[3]
|
| JVM to Python serialization | None | Pickle (cloudpickle)[2] | Arrow[2] | Arrow[2] | Arrow, with no pandas conversion[3] |
| Available since | Spark 1.3.0 (functions.udf in Scala)[7]
|
Spark 1.3.0[8] | Spark 3.5.0 (SPARK-40307); default in 4.2.0[9][10] | Spark 2.3.0[11] | Spark 4.1.0 (SPARK-52214)[12] |
Which UDF type is fastest?
The performance tiers follow from how much work each call spends moving data between the JVM and Python. A JVM UDF runs in the executor JVM and needs no transfer to Python. Every Python UDF runs in a separate Python worker process, so its input and output must cross from the JVM to Python and back; PySpark uses Arrow to make that transfer efficient.[6]
Among Python UDFs, pickled UDFs pay the most serialization overhead. The PySpark user guide says they rely on cloudpickle and meet performance bottlenecks with large inputs and outputs.[2] When Databricks engineers introduced pandas UDFs for Spark 2.3 in 2017, they wrote that row-at-a-time Python UDFs "suffer from high serialization and invocation overhead", which led many pipelines to write UDFs in Java or Scala and call them from Python; their benchmark found pandas UDFs 3 to over 100 times faster than row-at-a-time UDFs.[13]
Arrow-optimized Python UDFs keep the row-at-a-time function but replace pickle with Arrow for the transfer. In a Databricks benchmark for Spark 3.5, an Arrow-optimized Python UDF ran about 1.6 times faster than a pickled UDF on one transformation, and about 1.9 times faster when UDFs were chained, on a 32 GB dataset.[14] These are measured results for one cluster and dataset, not general guarantees.
Pandas UDFs and Arrow UDFs are vectorized: the function receives a whole batch, so library code (pandas or PyArrow compute functions) can process many rows per call. Arrow UDFs keep the columnar layout end to end and avoid the extra copies of a pandas conversion.[3] The batch size for Arrow transfers is spark.sql.execution.arrow.maxRecordsPerBatch, default 10,000 rows.[6]
A Python UDF is opaque to the Spark optimizer. Spark 4.3.0 adds an experimental option, spark.sql.experimental.optimizer.transpilePyUDFs (default false), that tries to rewrite simple Python UDFs as Catalyst expressions; it requires ANSI mode and does not yet work with Spark Connect.[15][16]
How to write a UDF in PySpark
The following PySpark example defines the same string function three ways. It runs on Spark 4.3.0 with PyArrow installed.
import pandas as pd
import pyarrow as pa
import pyarrow.compute as pc
from pyspark.sql.functions import udf, pandas_udf, arrow_udf
# Scalar Python UDF: one row per call (Arrow-optimized by default since Spark 4.2)
@udf(returnType="int")
def slen(s: str) -> int:
return len(s)
# Pandas UDF: one pandas Series per batch
@pandas_udf("string")
def upper_pd(s: pd.Series) -> pd.Series:
return s.str.upper()
# Arrow UDF: one pyarrow.Array per batch
@arrow_udf("string")
def upper_pa(s: pa.Array) -> pa.Array:
return pc.ascii_upper(s)
df = spark.createDataFrame([("John Doe",)], ["name"])
df.select(slen("name"), upper_pd("name"), upper_pa("name")).show()
A Python UDF can be registered for SQL with spark.udf.register("slen", slen) and then called as SELECT slen(name) FROM t.[8]
What changed in Spark 4.x?
- Spark 4.0.0 added keyword arguments for Python UDFs.[8]
- Spark 4.1.0 added Arrow UDFs (
arrow_udf, SPARK-52214) and Arrow UDTFs (arrow_udtf, SPARK-52979). From 4.1.0,udfalso creates a vectorized UDF when the type hints match a pandas UDF or Arrow UDF pattern anduseArrowis not set.[12][8] - Spark 4.2.0 made regular Python UDFs Arrow-optimized by default:
spark.sql.execution.pythonUDF.arrow.enablednow defaults totrue(SPARK-54555). Setting it tofalserestores pickled UDFs.[5][10]
The pandas UDF API dates from Spark 2.3.0.[11] Arrow-optimized Python UDFs were introduced in Spark 3.5.0.[9]
Limitations
SQL boolean expressions do not short-circuit around a UDF: in WHERE cond AND udf(x) the UDF may be called on every row regardless of cond, so a UDF that can fail on some inputs must handle them itself.[3]
See also
- Pandas UDF
- Arrow-optimized Python UDF
- Python UDTF
- Python data source API (Spark)
- Apache Arrow
- Spark Connect
- Encoder (Spark)
References
- ↑ 1.0 1.1 1.2 1.3 Scalar User Defined Functions (UDFs) (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ 2.00 2.01 2.02 2.03 2.04 2.05 2.06 2.07 2.08 2.09 2.10 Chapter 5: Unleashing UDFs & UDTFs (PySpark 4.3.0 user guide). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ 3.0 3.1 3.2 3.3 3.4 3.5 Arrow Python UDFs (PySpark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ CREATE FUNCTION (SQL) (Spark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ 5.0 5.1 5.2 Upgrading PySpark (PySpark 4.3.0 migration guide). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ 6.0 6.1 6.2 6.3 Apache Arrow in PySpark (PySpark 4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ sql/api/src/main/scala/org/apache/spark/sql/functions.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ 8.0 8.1 8.2 8.3 python/pyspark/sql/functions/builtin.py (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ 9.0 9.1 Spark Release 3.5.0. Apache Software Foundation.Retrieved 2026-11-23.
- ↑ 10.0 10.1 Spark Release 4.2.0. Apache Software Foundation.Retrieved 2026-11-23.
- ↑ 11.0 11.1 python/pyspark/sql/pandas/functions.py (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ 12.0 12.1 Spark Release 4.1.0. Apache Software Foundation.Retrieved 2026-11-23.
- ↑ Introducing Pandas UDF for PySpark. Databricks, 2017-10-30.Retrieved 2026-11-23.
- ↑ Arrow-optimized Python UDFs in Apache Spark 3.5. Databricks, 2023-11-06.Retrieved 2026-11-23.
- ↑ SQLConf.scala (v4.3.0). Apache Software Foundation.Retrieved 2026-11-23.
- ↑ Spark Release 4.3.0. Apache Software Foundation.Retrieved 2026-11-23.