Sub topic 18
When to use a UDF, and when not to
A user-defined function (UDF) lets you run your own Python code on each row or batch of a DataFrame. It is the escape hatch for logic that Spark's built-in functions cannot express. It is also slower and harder for Spark to optimize than the built-ins. This chapter assumes you can already use select, withColumn, filter, and the functions in pyspark.sql.functions, and that you know transformations are lazy.
Why UDFs cost more
Built-in functions such as F.round or F.when are expressions that Spark's optimizer (Catalyst) understands. Catalyst can reorder them, push filters down to the data source, and compile them to JVM code.
A regular Python UDF is a black box to Catalyst. For every row, Spark must:
- Serialize the row from the JVM.
- Send it to a separate Python worker process.
- Run your function.
- Serialize the result and send it back.
This round trip happens for each row, so a UDF that does trivial work can still be many times slower than the equivalent built-in. Catalyst also cannot see inside the function, so it cannot use the logic to skip data.
Try the built-in first
Most logic that looks like it needs a UDF does not. Conditionals map to F.when, string work maps to functions such as F.regexp_extract, F.split and F.concat_ws, and collections map to F.transform and F.filter. The SQL function reference lists several hundred.
Here is a labeling rule written both ways. The first block builds the orders DataFrame from earlier chapters so it runs on its own.
from pyspark.sql import functions as F
orders = spark.createDataFrame(
[
(1, "alice", "2024-01-05", 120.0),
(2, "bob", "2024-01-06", 75.5),
(3, "alice", "2024-02-10", 30.0),
(4, "carol", "2024-02-11", None),
],
"order_id INT, customer STRING, order_date STRING, amount DOUBLE",
).withColumn("order_date", F.to_date("order_date"))
# Version 1: a Python UDF
def size_label_py(amount):
if amount is None:
return None
if amount >= 100:
return "large"
if amount >= 50:
return "medium"
return "small"
size_label_udf = F.udf(size_label_py, "string")
with_udf = orders.withColumn("size", size_label_udf("amount"))
# Version 2: the same rule with built-ins
with_builtin = orders.withColumn(
"size",
F.when(F.col("amount") >= 100, "large")
.when(F.col("amount") >= 50, "medium")
.when(F.col("amount").isNotNull(), "small"),
)
display(with_builtin)Both versions give the same result. The built-in version stays visible to the optimizer, needs no Python worker, and is easier to test. A when chain with no matching branch returns null, which is why the last branch checks isNotNull.
When a UDF is justified
Reach for a UDF when all of these hold:
- No combination of built-in functions expresses the logic.
- The logic needs a Python library, such as a parsing, geocoding or scoring package.
- You have confirmed that the rest of the pipeline is not the real bottleneck.
Even then, pick the cheapest kind. The table compares your options.
| Kind | How it runs | Relative cost | Use for |
|---|---|---|---|
| Built-in function | Inside the JVM, optimized | Lowest | Almost everything |
| Pandas UDF | Python worker, data moved in Arrow batches | Moderate | Logic that needs Python or pandas libraries over many rows |
| Regular Python UDF | Python worker, row by row | Highest | Small data, or logic that cannot be vectorized |
Pandas UDFs
A pandas UDF (also called a vectorized UDF) receives a whole batch of values as a pandas.Series. Spark transfers batches using Apache Arrow, a columnar in-memory format, which avoids per-row serialization. Your function must return a Series of the same length as its input.
import pandas as pd
from pyspark.sql import functions as F
@F.pandas_udf("double")
def add_tax(amount: pd.Series) -> pd.Series:
return amount * 1.2
display(orders.withColumn("amount_with_tax", add_tax("amount")))Nulls arrive in the Series as NaN and go back to Spark as null, so carol's row stays null. This example is simple enough that F.col("amount") * 1.2 would be better. It only shows the shape. A realistic use is calling a vectorized function from a Python library on a whole column at once.
Using a function from SQL
To call a Python function from SQL, register it with spark.udf.register. Pass the plain Python function, not the wrapped UDF.
orders.createOrReplaceTempView("orders_v")
spark.udf.register("size_label", size_label_py, "string")
display(spark.sql("SELECT order_id, amount, size_label(amount) AS size FROM orders_v"))Common errors and gotchas
- Silent nulls from wrong return types. If the declared return type is
intbut the function returns a Pythonfloat, Spark gives you null instead of an error. Match the declared type to what the function really returns. - Unhandled nulls. A Python UDF receives
Nonefor null input. Code such asamount >= 100raises aTypeErroronNone, and one bad row fails the whole task. Check forNonefirst, assize_label_pydoes. - Side effects. Spark may run a UDF more than once for the same row, for example when a task is retried. Do not write to files, call paid APIs, or increment counters inside one.
- Non-deterministic logic. Functions that use random numbers or the current time can give different results across retries. Mark them with
.asNondeterministic()so the optimizer does not assume repeatable output. - Heavy setup per call. Loading a model inside the function reloads it for every row, or every batch. Pandas UDFs that take an iterator of batches let you load once per task.
- Access mode limits. On some shared compute configurations, Python UDFs run in a sandbox with restricted libraries and file access. If a UDF works on your personal cluster but fails on shared compute, check the cluster's access mode first.
Checking the cost yourself
Run explain() on both versions of the labeling example. The built-in plan shows the CASE WHEN expression inside a Project step. The UDF plan shows a separate Python evaluation step, such as BatchEvalPython or ArrowEvalPython for pandas UDFs. That extra node marks the boundary where rows cross to Python. To compare speed, time a count() on a large table with each version.
with_builtin.explain()
with_udf.explain()Decision summary
- Can built-in functions do it? Use them.
- If not, can the logic work on whole columns? Use a pandas UDF.
- If not, use a regular Python UDF. Handle
Noneand set the return type explicitly. - Keep the UDF narrow. Filter and select first, so it runs on as few rows as possible.
Exercise
A teammate wrote a Python UDF that returns "weekend" or "weekday" from a date column, using Python's datetime. The job is slow on a table with billions of rows. What would you change, and why?
Show answer
Replace the UDF with built-ins, for example F.when(F.dayofweek("order_date").isin(1, 7), "weekend").otherwise("weekday"). Catalyst can then optimize the expression, and no rows travel to a Python worker. Check the plan with explain() to confirm the Python evaluation step is gone.
Exercise
A UDF declared with return type int computes amount / 2 and returns a Python float. The output column is all nulls and no error appears. Why, and how do you fix it?
Show answer
The declared type does not match the returned value, and Spark converts the mismatch to null instead of raising an error. Declare the return type as double, or return int(amount // 2) if an integer is what you want.