Measuring the UDF Tax

A benchmark answers a single question: how much slower is this job because of the border crossing? Both versions must read the same input on the same cluster, do the same work and differ in exactly one expression. That design breaks under 3 habits, and each skews the answer.

Trap 1: an action that skips the UDF

tagged = events.withColumn("kind", classify_udf("event_type"))
tagged.count()

Catalyst prunes columns that nothing downstream reads. count() reads no columns, so the kind projection is removed, and because a UDF is deterministic unless you mark it otherwise, Catalyst is free to drop it. The timer measures a scan, the 2 versions tie, and the conclusion is wrong. Time an action that needs every column instead. The noop write format, built into Spark since 3.0, runs the whole plan and discards the rows.

tagged.write.format("noop").mode("overwrite").save()

Trap 2: timing the first run

The first run in a session pays one-off costs. Spark forks the Python workers and ships the function for them to load, and the JVM loads its classes for the first time. Later runs reuse the workers. Time each version several times and keep the median, so a cold start or a noisy neighbour on the cluster cannot decide the result.

Trap 3: timing the read too

When each run reads files from storage, read variance lands in both numbers. Cache only the input column, materialize the cache once with an action, then time each variant over the cached data. The difference between the 2 medians is then the expression and nothing else.

import time
from pyspark.sql import functions as F

base = spark.read.parquet("/data/events").select("event_type").cache()
base.count()


def timed(label, frame, repeats=5):
    seconds = []
    for _ in range(repeats):
        start = time.perf_counter()
        frame.write.format("noop").mode("overwrite").save()
        seconds.append(time.perf_counter() - start)
    seconds.sort()
    print(label, "median seconds:", round(seconds[len(seconds) // 2], 2))


commerce = ("purchase", "add_to_cart")
classify_udf = F.udf(lambda t: "commerce" if t in commerce else "other", "string")
builtin_kind = F.when(F.col("event_type").isin(*commerce), "commerce").otherwise("other")

timed("python udf", base.withColumn("kind", classify_udf("event_type")))
timed("built-in", base.withColumn("kind", builtin_kind))

The 2 variants also agree on nulls, which you should confirm before trusting any timing: None in commerce is false in Python, and isin on a null returns null, which when treats as false, so both return "other". A faster version that returns different rows has measured nothing.

From seconds to a per-row price

Suppose the timing code prints 6.2 seconds for the built-in and 38.0 seconds for the UDF, over 40 million cached rows on 8 cores. The UDF adds 31.8 seconds of wall time. Multiply by the 8 busy cores and divide by the rows: (31.8 x 8) / 40,000,000 is about 6.4 microseconds of core time per row. A per-row price scales to any volume, so a table that receives 2 billion rows a day, the volume of the playback job in the intro, pays the figure below.

The difference in the Spark UI

Where to lookBuilt-in runUDF run
SQL tab plan graphScan, then ProjectA `BatchEvalPython` box between them
Stages per run11: the UDF adds no stage
Shuffle read and writeNoneNone
SpillNoneNone at this width
Median task durationShort: tasks of the 6.2 s runAbout 6 times longer, as 38.0 s is to 6.2 s
GC timeLowCan rise with the objects the conversions create

Long tasks that show moderate GC and neither shuffle nor spill usually point to a Python UDF: the checks you already run come back clean while the time goes to a process the stage page does not describe. The BatchEvalPython box in the SQL tab names the cause, and from Spark 3.4 that box also reports how much data was sent to and returned from the Python workers.

A teammate times a UDF against its built-in rewrite with the code below. Both versions take 4.1 seconds, and the teammate concludes the UDF is free. What is the most likely explanation?

start = time.perf_counter()
users.withColumn("domain", domain_udf("email")).count()
print(time.perf_counter() - start)

An aggregate can stand in for the noop write, provided it reads the measured column. Catalyst prunes a column only when nothing downstream reads it. Put F.countDistinct("kind") or F.max("kind") in the final agg and the expression stays in the plan, but F.count("*") lets Catalyst drop it. Don't trust the number until explain() shows the expression still sitting above the scan.

About this lesson

This section is part of the UDFs and Serialization: Intermediate 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.