Sub topic 15
Replacing Python UDFs with built-in functions
This chapter covers why Python user-defined functions (UDFs) slow queries, how they stop Photon from running part of a plan, and how to replace them. It assumes you can read a Spark query plan, know what Photon is, and can write PySpark DataFrame code. Earlier chapters on Photon fallback and on reading plans cover those topics.
Why a Python UDF is slow
A UDF is a function you write yourself and call inside a query. A Python UDF is written in Python, but Spark runs on the JVM and Photon is native C++ code. Neither of them can execute Python. So Spark has to move the data to a separate Python process, run your function there, and move the results back.
For a standard Python UDF, each batch of rows goes through these steps:
- Spark serializes the input rows from its internal format.
- It sends them to a Python worker process.
- The worker calls your function once per row.
- The worker serializes the results and sends them back.
- Spark deserializes the results into its own format.
The cost has three parts. Serialization and deserialization take CPU time. The per-row Python call is much slower than a compiled loop over a column. The function is also opaque to the optimizer. Spark cannot look inside it, so it cannot reorder it, push it down, or combine it with neighboring expressions.
How a UDF affects Photon
Photon only runs operators and expressions it supports. A Python UDF is not supported, so the operator that contains it runs in the standard Spark engine. Photon operators below and above it can still run, but the data must be converted between the formats at each boundary. A single UDF in a projection can therefore make a pipeline slower than the UDF's own cost suggests.
You can see this in the plan. Run explain on the DataFrame and look for a BatchEvalPython or ArrowEvalPython node. That node is the Python UDF. Operators with names that start with Photon run in Photon.
from pyspark.sql import functions as F
from pyspark.sql.types import StringType
df = spark.createDataFrame(
[(" north ",), ("South",), (None,)],
["region"],
)
normalize_udf = F.udf(
lambda s: s.strip().upper() if s is not None else None,
StringType(),
)
df.withColumn("region_norm", normalize_udf("region")).explain()
df.withColumn("region_norm", F.upper(F.trim("region"))).explain()In the first plan, look for the Python evaluation node. In the second plan, the projection contains upper(trim(region)) directly. On a Photon-enabled cluster, that projection can run in Photon if the rest of the plan allows it. The exact node names depend on your Databricks Runtime version, so check your own output.
Replacing a UDF with built-ins
Here is the pair of versions from the topic's example, with the same result:
from pyspark.sql import functions as F
from pyspark.sql.types import StringType
# Slower: a Python UDF runs row by row outside the native engine.
normalize_udf = F.udf(lambda s: s.strip().upper() if s is not None else None, StringType())
slow = df.withColumn("region_norm", normalize_udf("region"))
# Preferred: built-in functions stay inside the optimized engine.
fast = df.withColumn("region_norm", F.upper(F.trim("region")))Both versions return null for a null input. The built-in functions do this on their own, so the explicit is not None check disappears.
Finding the right built-in
Most UDFs reimplement something that already exists. Before you write a UDF, check the list of built-in functions for your language. Common replacements are:
| What the UDF does | Built-in alternative |
|---|---|
| Clean or change case of strings | `trim`, `upper`, `lower`, `regexp_replace`, `substring` |
| Branching logic with `if` / `else` | `when(...).otherwise(...)` or SQL `CASE WHEN` |
| Parse or format dates | `to_date`, `to_timestamp`, `date_format` |
| Work with JSON text | `from_json`, `get_json_object`, `to_json` |
| Work with arrays or maps | `transform`, `filter`, `aggregate`, `explode` |
| Null handling | `coalesce`, `nullif`, `ifnull` |
| Custom row logic with several steps | A chain of the functions above, or `expr("...")` |
Branching logic
A UDF that returns a label from a number is a typical case:
from pyspark.sql import functions as F
orders = spark.createDataFrame(
[(1, 50.0), (2, 500.0), (3, 5000.0)],
["order_id", "amount"],
)
labeled = orders.withColumn(
"size",
F.when(F.col("amount") < 100, "small")
.when(F.col("amount") < 1000, "medium")
.otherwise("large"),
)
labeled.show()This gives the same result as an if chain in Python, and Spark can optimize the expression.
Higher-order functions for arrays
If a UDF loops over an array, a higher-order function usually replaces it. These take a lambda written in SQL or in the PySpark API, and Spark evaluates it itself.
from pyspark.sql import functions as F
data = spark.createDataFrame([([1, 2, 3],), ([4, 5],)], ["values"])
data.select(
F.transform("values", lambda x: x * 10).alias("scaled"),
F.aggregate("values", F.lit(0), lambda acc, x: acc + x).alias("total"),
).show()The lambda here is not a Python UDF. PySpark turns it into a Spark expression, so no Python worker is involved.
When a UDF is still needed
Some logic has no built-in equivalent, such as a call into a specialized Python library. In that case, reduce the cost rather than ignoring it.
- Filter and project first. Run the UDF on as few rows and columns as possible. Put filters and joins before the UDF step.
- Use a pandas UDF. A pandas UDF (also called a vectorized UDF) sends data in Apache Arrow batches and runs your function on a whole batch as a pandas Series. This avoids most of the per-row overhead. It still runs in Python, so it still breaks Photon at that operator.
- Use a SQL UDF. A SQL UDF that you register in Unity Catalog is written as a SQL expression, so Spark can often inline it into the plan. It is limited to what SQL can express.
- Keep it deterministic and simple. A UDF with side effects, such as a network call per row, is slow and hard to retry.
A pandas UDF example:
import pandas as pd
from pyspark.sql import functions as F
@F.pandas_udf("double")
def to_celsius(f: pd.Series) -> pd.Series:
return (f - 32) * 5.0 / 9.0
temps = spark.createDataFrame([(32.0,), (212.0,)], ["fahrenheit"])
temps.select(to_celsius("fahrenheit").alias("celsius")).show()This particular function is only arithmetic, so the better fix is (F.col("fahrenheit") - 32) * 5.0 / 9.0. The pandas UDF is appropriate only when the logic really needs Python.
Common errors
- Assuming Photon covers the whole query. If one expression is a UDF, the operator holding it runs outside Photon. Check the plan or the Query Profile instead of assuming.
- Different null behavior. A UDF that raises on
Nonefails the task, while built-ins usually return null. Test with null inputs when you rewrite. - Different type behavior. A UDF declares its return type. If it returns a value of the wrong type, Spark may produce nulls instead of an error. Built-ins have fixed, documented return types.
- Rewriting without measuring. The gain depends on how many rows reach the UDF and how much else the query does. Compare runs as described in the benchmarking chapter.
- Hiding a UDF in a view. A view or a library function may contain a UDF that your query does not show. Run
explainon the final query.
Checking your result
After a rewrite, confirm three things. First, explain no longer shows a Python evaluation node. Second, the output matches the old version, including nulls and edge cases. You can check this with an exceptAll between the two results. Third, the Query Profile shows the operators in Photon, and the runtime has dropped on a fair comparison.
diff = slow.exceptAll(fast).count() + fast.exceptAll(slow).count()
print("rows that differ:", diff)A result of 0 means both versions returned the same rows, counting duplicates.
Exercise
A query uses a Python UDF in withColumn to return "high" when score >= 80, "mid" when score >= 50, and "low" otherwise. Rewrite it with built-in functions, and name the plan node you would look for to confirm the UDF is gone.
Show answer
Use F.when(F.col("score") >= 80, "high").when(F.col("score") >= 50, "mid").otherwise("low"). In the physical plan, the Python UDF appears as a BatchEvalPython node (or ArrowEvalPython for pandas UDFs). After the rewrite, that node should be absent, and the projection should show a CASE WHEN expression, which Photon can run.
Exercise
Why does a pandas UDF still prevent Photon from running the operator that contains it, even though it is faster than a row-by-row UDF?
Show answer
A pandas UDF is still Python code. It runs in a separate Python worker process, and Photon is a native engine that cannot execute Python. The Arrow batching reduces serialization and per-row call cost, but the operator still runs in the standard Spark engine.