When a UDF Is Necessary
The cases that justify a UDF
A UDF is worth its cost when column functions cannot express the logic at any reasonable length. Most of the UDFs worth keeping fall into 3 cases.
- A Python library already does the work: Phone number formatting, user-agent parsing or a pricing rule your team maintains as a Python package. Rewriting it as column expressions creates a second copy that drifts from the first.
- The rule needs real control flow: A checksum computed digit by digit, such as the Luhn check on card numbers, or a parser that walks a string and changes mode as it reads.
- A Python model scores each row: A model trained with a Python machine learning library has to be called from Python, and no built-in can load it.
Before writing one, check in order whether a single built-in does it, whether a combination of built-ins does it in a few lines, and whether an array function does it. F.transform is one such array function, and F.filter and F.aggregate are others. If all 3 answers are no, write the UDF.
Keep it contained
When a UDF stays, shrink what it touches. Every row that reaches the function pays the conversion, every argument column is converted for each of those rows, and a filter on the function's output gets no pushdown. Arrange the query so built-ins do all the work they can before the UDF runs.
from pyspark.sql import functions as F
from referrer_rules import classify
@F.udf(returnType="string")
def referrer_kind(referrer):
if referrer is None:
return None
return classify(referrer)
views = spark.read.parquet("/data/page_views")
kinds = (
views
.where(F.col("viewed_at") >= "2024-03-01")
.where(F.col("dur_ms") > 0)
.select("view_id", "referrer")
.withColumn("referrer_kind", referrer_kind(F.col("referrer")))
)The 2 where calls compare raw columns, so they reach the Parquet reader and drop old and empty views before Spark handles them. The scan reads only the 4 columns the query names. viewed_at and dur_ms feed the filters, and the select needs view_id and referrer. Leaving a filter column out of the select keeps it from flowing downstream, but the reader still has to read it to apply the test. Past the filter, only the 2 kept columns travel on, and the UDF receives 1 argument, so only the referrer value of each surviving row is converted. classify is imported at the top of the file, outside the function body, and the referrer_rules package has to be installed on every executor, because that is where the function runs.
- page_views files (source, Parquet)
- Date and duration filter (transform, built-in, pushed to scan)
- Keep 2 columns (transform, select)
- referrer_kind (transform, Python UDF)
- kinds (storage, DataFrame)
- page_views files -> Date and duration filter
- Date and duration filter -> Keep 2 columns
- Keep 2 columns -> referrer_kind
- referrer_kind -> kinds
- Do
- Filter with built-ins on raw columns before the UDF so fewer rows reach it
- Pass the UDF only the columns it reads
- Import libraries and build lookups outside the function body
- Cache or write the UDF's output when more than 1 action reads it
- Avoid
- Filter on a UDF's output when the same test exists on a raw column
- Pass F.struct("*") to a UDF that reads 2 fields
- Call a network service from inside the function for each row
- Compile a regex or open a file inside the function body
Each action re-runs the plan, UDF included. A job that calls count() on kinds and then writes it pays the conversion twice, so cache kinds first, or write it once and read the result.
A job tags 300 million page views with referrer_kind and keeps only March views longer than 0 ms. Which arrangement keeps the UDF's cost lowest?
- Pass F.struct("*") to the UDF and let the function skip old or empty views itself
- Filter on raw viewed_at and dur_ms first, then pass only referrer to the UDF
- Run the UDF over every view, cache the result, then filter March views from the cache
- Have the UDF call the referrer service over HTTP so all executors share 1 lookup
About this lesson
This section is part of the UDFs and Serialization: Beginner 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.