Warming into it
I've written about Python UDFs a few times now, and every one of those posts has been about speed/performance. In this post I want to take a step back and answer which kind of function you should be writing in the first place. Spark has a lot of them (a @udf, a @pandas_udf, an @arrow_udf, a UDAF, an Aggregator, a @udtf, an @arrow_udtf, SQL functions, SQL table functions, and a Hive GenericUDTF that is somehow still the only table function the JVM has), and the names are, to be honest, not super helpful in telling you what any of them is for.
Two variables will determine what you ultimately end up using: the first is the shape of the job and the second is where your code runs. A SQL function gets folded into the query, so the optimizer can see inside it the same way it sees a built-in. A Scala or Java UDF runs in the executor's own JVM, which is cheap, but the optimizer can't see inside it. A Python UDF runs in a separate Python worker, so Spark has to ship rows out to it in batches and read the results back. So pick the shape first, then the cheapest language that can express it; a good amount of the UDF issues I ran into while writing this came from getting one of those two wrong. Alternatively, stick with your favourite language and use this as a reference for what your options are. Most shapes exist in most of Spark's languages, and the table further down shows the few gaps.
So this guide, again written for idiots by an idiot, sorts them by the one thing that actually decides which one you need. Every snippet below is code run on Spark 4.3.0; the whole thing lives in spark-demos if you'd rather just feed that straight to an agent.
TLDR; Every user-defined function in Spark is defined by its shape (one row to one value, many rows to one value, one row to many rows, or a whole table to a table), and the language you write it in decides where it runs.
What is a UDF, and why does Spark keep telling me not to write one?
Spark already comes with a lot of functions. On 4.3.0, SHOW SYSTEM FUNCTIONS lists 591 of them (lower, regexp_replace, sum, explode, date_add and so on), and most DataFrame code and SQL queries are just those functions plugged into each other. A user-defined function (UDF) is a function you write yourself for the cases none of them cover: you give Spark your function, a name, and the type it returns, and from then on you can call it in a query the same way you'd call lower.
@udf("string")
def first_dish(items):
# "2x Khao Soi; 1x Birria Tacos" -> "Khao Soi"
return items.split(";")[0].split("x", 1)[1].strip()
df.select("order_id", "items", first_dish("items").alias("first_dish"))
spark.udf.register("first_dish", first_dish) # SQL can call it now too
spark.sql("SELECT order_id, first_dish(items) AS first_dish FROM orders")
+--------+----------------------------+------------+
|order_id|items |first_dish |
+--------+----------------------------+------------+
|1001 |2x Khao Soi; 1x Birria Tacos|Khao Soi |
|1002 |1x Pad See Ew |Pad See Ew |
|1003 |3x Birria Tacos; 2x Horchata|Birria Tacos|
+--------+----------------------------+------------+
The @udf("string") decorator turns an ordinary Python function into something Spark can put in a query. The "string" part is the return type, which Spark needs up front because it plans the whole query before it reads any data, and spark.udf.register gives the function a name in the session so SQL can call it as well.
That planning step is where the catch is. Before anything runs, Spark's optimizer (called Catalyst) rewrites your query into a cheaper version of itself: filtering rows earlier, dropping columns nobody uses, merging steps together. It can do that with built-ins because it knows exactly what each one does. It has no idea what your function does, so to Catalyst a UDF is a sealed box with inputs going in and a value coming out, and it plans around it rather than through it. Python UDFs add a second cost on top: Spark runs on the JVM (the Java virtual machine), so Python code can't run inside Spark itself, and every row your Python function sees has to be sent to a separate Python process and back. Those two costs (a box the optimizer can't see into, and a trip to another process) are the reason for all the "use a built-in instead" advice, and how big they are depends on which kind of UDF you write and in which language.
What kinds of UDF are there? (UDFs, UDAFs, UDTFs, and other acronyms that sound like airport codes)
Most of the confusion around UDFs comes from treating "UDF" as one thing with several speeds, when really it's four different contracts about how many rows go in and how many come out per call. Once you know which contract your logic needs, the list of candidates shrinks to two or three.
-
Scalar UDF (usually just called a UDF): Spark calls it with one row's values and it returns one value, so the result has exactly as many rows as the input.
first_dishabove is one. Typical jobs are cleaning, parsing or scoring a single value. -
Aggregate UDF (UDAF): Spark calls it with a whole group of rows (everything a
groupBy("customer")puts together) and it returns one value for the group, the waysumandavgdo. You write one for a statistic Spark doesn't have; the example below is a geometric mean of each customer's order totals. - Table function (UDTF): Spark calls it with one row and it returns zero or more rows, so it's the only kind that can make a table longer. The example turns each order into one row per dish on it.
- UDTF with a TABLE argument: Spark hands it a whole table, split up by a key and sorted, and it returns a table. You get one running instance of your function per key, so it can remember things from one row to the next; the example is a loyalty punch card that tracks stamps per customer.
Which kind should I choose, and when?
Two decisions, in this order: the shape, then where the code runs.
The shape comes straight from your logic. Count how many rows go into one call and how many come out, and the list above tells you which kind of UDF that is; there's usually only one that fits.
Where it runs is the part that decides the cost. A Spark job is split into tasks that run on executors, which are JVM processes on the machines in your cluster, while the driver (the process your script runs in) plans the query and hands out the tasks. Every built-in function, SQL function, Scala UDF and Java UDF runs inside the executor's JVM, on Spark's own rows, with no copying. A Python UDF can't, because the executor can't run Python, so Spark starts a separate Python worker process next to each executor, ships it batches of rows in Arrow (a column-oriented format both sides can read without converting row by row, and the default for this since 4.2), waits, and reads the results back.
There's a second, quieter split inside the JVM. A SQL function is inlined into the plan like a macro, so Catalyst optimizes it exactly as if you'd typed the expression yourself; a Scala or Java UDF runs in-process, but Catalyst can't look inside it, so it can't push a filter through it or fold it into anything. A Python UDF is opaque and out of process, which is why it's the last thing you reach for rather than the first.
Put together, that gives an order to try things in:
Built-ins first, then a SQL function, then a JVM UDF, then Python, and in Python the batch-at-a-time decorators before the row-at-a-time one. The shape doesn't change that order, but it does change what's on offer, because not every language has every shape.
How do they differ between PySpark, SQL, Scala and Java?
| Shape | What it's for | PySpark | SQL | Scala | Java |
|---|---|---|---|---|---|
| Scalar: one row in, one value out | cleaning, parsing, scoring a single value |
@udf, @pandas_udf, @arrow_udf
|
CREATE FUNCTION ... RETURN expr |
functions.udf |
UDF1...UDF22 + spark.udf().register
|
| Aggregate: many rows in, one value out | a statistic Spark doesn't have | grouped @pandas_udf, @arrow_udf
|
none (only scalar and table functions) |
Aggregator + functions.udaf
|
Aggregator + functions.udaf
|
| Table: one row in, many rows out | exploding, splitting, generating |
@udtf, @arrow_udtf
|
CREATE FUNCTION ... RETURNS TABLE |
no API; a UDF returning an array, exploded | a Hive GenericUDTF (needs Hive support) |
| Table in, table out: a partitioned, sorted table in | stateful logic per key |
@udtf with a TABLE argument and PARTITION BY
|
none | none (groupByKey + flatMapGroups on a Dataset) |
none (same) |
The gaps in that table are not a typo. Python UDTFs arrived in Spark 3.5, picked up analyze() and keyword arguments in 4.0, and @arrow_udtf and @arrow_udf in 4.1; SQL functions are documented from the 4.0.1 docs onward.
The JVM languages get the cheapest scalar and aggregate functions, and the thinnest table functions. Scalar UDFs in Scala and Java run in the executor's own process on Spark's own rows, which removes the Python worker entirely, but they're still opaque to Catalyst, so a SQL function is still better when the logic fits in built-ins.
// Scalar: functions.udf wraps a plain Scala function. It runs in the executor JVM.
val slug = udf((s: String) => s.trim.replaceAll("[^A-Za-z]+", "-").toLowerCase)
spark.udf.register("slug_scala", slug)
// Aggregate: an Aggregator with a (sum of logs, count) buffer, wrapped by functions.udaf.
case class LogBuf(logSum: Double, n: Long)
object GeoMean extends Aggregator[Double, LogBuf, Double] {
def zero = LogBuf(0, 0)
def reduce(b: LogBuf, x: Double) = LogBuf(b.logSum + math.log(x), b.n + 1)
def merge(a: LogBuf, b: LogBuf) = LogBuf(a.logSum + b.logSum, a.n + b.n)
def finish(b: LogBuf) = math.exp(b.logSum / b.n)
def bufferEncoder: Encoder[LogBuf] = Encoders.product[LogBuf]
def outputEncoder: Encoder[Double] = Encoders.scalaDouble
}
val geomean = udaf(GeoMean)
// Table: Scala has no UDTF API. A UDF that returns an array of structs, exploded, does the job.
val Item = """\s*(\d+)x\s+(.+?)\s*""".r
val lineItems = udf((items: String) => items.split(";").toSeq.collect {
case Item(qty, dish) => (qty.toInt, dish.split("\\s+").mkString(" "))
})
orders.select(col("order_id"), explode(lineItems(col("items"))).as("li"))
The Aggregator is the important one, because merge is exactly what Python aggregates are missing (more on that under making a UDF faster): Spark runs reduce on each partition, shuffles one small LogBuf per customer, and merges them, the same two-phase shape as the built-in. The table function is a workaround rather than an API; the plan reads Generate explode(UDF(items)), so it's the built-in explode doing the generating and your UDF only building an array, which means every line item for a row is materialized at once before it's exploded.
Java has the same scalar and aggregate APIs (UDF1 through UDF22, and the same Aggregator class), so the Java file mostly reads like the Scala one with more ceremony. For a registered table function on the JVM, the only option is a Hive GenericUDTF, an old Hive interface with ObjectInspectors that Spark still supports for compatibility:
/** One row in, many rows out, on the JVM: Spark has no Java UDTF API of its own, so it's a Hive GenericUDTF. */
public class LineItemsUDTF extends GenericUDTF {
@Override
public StructObjectInspector initialize(ObjectInspector[] args) throws UDFArgumentException {
return ObjectInspectorFactory.getStandardStructObjectInspector(
Arrays.asList("qty", "dish"),
Arrays.asList(PrimitiveObjectInspectorFactory.javaIntObjectInspector,
PrimitiveObjectInspectorFactory.javaStringObjectInspector));
}
@Override
public void process(Object[] args) throws HiveException {
for (String part : args[0].toString().split(";")) {
Matcher m = ITEM.matcher(part);
if (m.matches()) forward(new Object[] {Integer.parseInt(m.group(1)), m.group(2).replaceAll("\\s+", " ")});
}
}
}
CREATE TEMPORARY FUNCTION line_items_java AS 'kitchen.LineItemsUDTF';
SELECT o.order_id, li.qty, li.dish
FROM orders o LATERAL VIEW line_items_java(o.items) li AS qty, dish;
It works, and its plan line is Generate HiveGenericUDTF#kitchen.LineItemsUDTF(items), but only on a session with Hive support. Without it, CREATE TEMPORARY FUNCTION fails with [NO_HANDLER_FOR_UDAF] No handler for UDAF 'kitchen.LineItemsUDTF', which is a pretty confusing way of saying "this is a Hive class and you don't have Hive", and names the wrong kind of function to boot.
And the languages mix, which is the part people tend to forget. A Java UDF in a jar can be registered by name from PySpark and called like any built-in, and because it runs in the JVM, the plan has no Python operator at all:
spark = session(**{"spark.jars": "jars/kitchen-udfs.jar"})
spark.udf.registerJavaFunction("slug_java", "kitchen.Slug", "string")
df.select(F.expr("slug_java(...)")) # plan: Project, Scan
That's a decent option when a team writes PySpark but one hot function needs to be fast and the logic won't fit in SQL. It runs the other way too: anything registered with spark.udf.register or spark.udtf.register is callable from SQL in the same session, which is how the SQL queries in Steps 3 to 5 below reach the Python classes.
How do I write one?
The running example: a ghost kitchen's orders
Every example uses the same small table of orders from a ghost kitchen, chosen because it has one of each problem: a free-text items column that holds several dishes per order, a notes column of key=value pairs, and customers who come back (or don't) over a couple of months.
ORDERS = [
# order_id, customer, ordered_on, items, notes, total
(1001, "ana", dt.date(2026, 11, 2), "2x Khao Soi; 1x Birria Tacos", "spice=hot;allergy=peanut", 46.50),
(1002, "ana", dt.date(2026, 11, 9), "1x Pad See Ew", "spice=mild", 15.00),
(1003, "bo", dt.date(2026, 11, 3), "3x Birria Tacos; 2x Horchata", "allergy=dairy", 54.00),
(1004, "ana", dt.date(2026, 11, 20), "4x Khao Soi", "spice=hot", 66.00),
(1005, "bo", dt.date(2026, 12, 28), "2x Pad See Ew; 1x Horchata", None, 35.50),
(1006, "chidi", dt.date(2026, 11, 5), "1x Birria Tacos ", "spice=medium", 14.00),
(1007, "ana", dt.date(2026, 11, 27), "5x Horchata", None, 25.00),
]
Setup is one script that makes the venv (pyspark==4.3.0 from PyPI, pinned to Python 3.12) and compiles the Java and Scala into one jar against a Spark 4.3.0 tarball; bin/run.sh <file> then runs any example with the right tool for its language.
cd demos/20_udfs_and_udtfs
bin/setup.sh
bin/run.sh 01_scalar_udfs.py
Step 1: One row in, one value out
The scalar UDF is the one everyone knows. Here's the same dish-name cleanup (" Birria Tacos " becomes birria-tacos) written five ways, from no UDF at all to an Arrow UDF.
# 1. Built-in functions: no UDF at all.
builtin = F.lower(F.regexp_replace(F.trim("first_item"), r"[^A-Za-z]+", "-"))
# 2. A SQL UDF: a named expression, inlined into the plan like a macro.
spark.sql("""
CREATE OR REPLACE TEMPORARY FUNCTION slug_sql(s STRING) RETURNS STRING
RETURN lower(regexp_replace(trim(s), '[^A-Za-z]+', '-'))
""")
# 3. A Python UDF: called once per row, in a Python worker.
@udf("string")
def slug_py(s):
return "-".join(w for w in "".join(c if c.isalpha() else " " for c in s).lower().split())
# 4. A pandas UDF: called once per batch, gets a pandas Series.
@pandas_udf("string")
def slug_pandas(s: pd.Series) -> pd.Series:
return s.str.strip().str.replace(r"[^A-Za-z]+", "-", regex=True).str.lower()
# 5. An Arrow UDF (Spark 4.1+): called once per batch, gets a pyarrow Array.
@arrow_udf("string")
def slug_arrow(s: pa.Array) -> pa.Array:
return pc.utf8_lower(pc.replace_substring_regex(pc.utf8_trim_whitespace(s), r"[^A-Za-z]+", "-"))
All five return the same slugs. The three Python versions differ in what your function receives per call: a single string for @udf (Arrow carries the batch, but your code still runs once per row), a pandas.Series for @pandas_udf, and a pyarrow.Array for @arrow_udf, which is the distinction the UDF benchmark spent most of its time on.
Step 2: Many rows in, one value out
Aggregate UDFs (UDAFs, if you enjoy acronyms) take a whole group and return one value. Spark doesn't have a geometric mean, so it makes a decent example, though it's also a good reminder to check for a built-in expression first, because exp(avg(ln(x))) is the same number:
# Built-in: exp(avg(ln(x))) is the same number, no Python involved.
builtin = F.exp(F.avg(F.ln("total")))
# A grouped-aggregate pandas UDF: the whole group's column arrives as one Series.
@pandas_udf("double")
def geomean_pandas(totals: pd.Series) -> float:
return math.exp(totals.map(math.log).mean())
# The Arrow version (Spark 4.1+): the group arrives as one pyarrow Array.
@arrow_udf("double")
def geomean_arrow(totals: pa.Array) -> float:
return math.exp(pc.mean(pc.ln(totals)).as_py())
All three give ana 32.75, bo 43.78, chidi 14.0. They don't cost the same to run, though, because the Python versions can't combine partial results before Spark moves rows between machines; that's the third fix in the next section.
Step 3: One row in, many rows out (the UDTF)
This is the one people miss. A user-defined table function returns a table instead of a value, so a single order can turn into one row per line item. In PySpark it's a class, and eval() runs once per input row and yields as many rows as it likes, including none:
@udtf(returnType="qty int, dish string")
class LineItems:
def eval(self, items: str):
for part in items.split(";"):
m = re.match(r"\s*(\d+)x\s+(.+?)\s*$", part)
if m: # a malformed item yields nothing, rather than a row of nulls
yield int(m.group(1)), " ".join(m.group(2).split())
spark.udtf.register("line_items", LineItems)
spark.sql("""
SELECT o.order_id, li.qty, li.dish
FROM orders o, LATERAL line_items(o.items) li
""")
You call a UDTF in the FROM clause, and LATERAL is what lets it read a column from each row of orders and joins its output back to that row:
+--------+---+------------+
|order_id|qty| dish|
+--------+---+------------+
| 1001| 2| Khao Soi|
| 1001| 1|Birria Tacos|
| 1002| 1| Pad See Ew|
| 1003| 3|Birria Tacos|
| 1003| 2| Horchata|
...
The plan runs it in ArrowEvalPythonUDTF, the table-function twin of ArrowEvalPython. In fairness to SQL, though, this particular parse doesn't need Python, and a SQL table function gets identical rows out of split, explode and two regexes:
CREATE OR REPLACE TEMPORARY FUNCTION line_items_sql(items STRING)
RETURNS TABLE (qty INT, dish STRING)
RETURN SELECT CAST(regexp_extract(part, '(\\d+)x', 1) AS INT),
regexp_replace(trim(regexp_extract(part, '\\d+x(.*)', 1)), ' +', ' ')
FROM (SELECT explode(split(items, ';')) AS part);
The script checks the two against each other (SQL table function agrees: True), and the SQL version's plan is Project, Generate, Project, Scan: the function body inlined, with the explode running in the JVM. The rule from choosing a UDF holds for tables too; a Python UDTF earns its place when the logic needs Python (a library, a parser, a model, a loop with state), and the next step is the case where it really does.
Step 4: A table in, a table out (TABLE arguments and PARTITION BY)
A UDTF can also take a whole table as an argument, and this is the feature that has no equivalent anywhere else in Spark's function zoo. You pass TABLE(...), add PARTITION BY and ORDER BY, and Spark guarantees that all rows with the same partition key are consumed by exactly one instance of your class, in the order you asked for, with terminate() called once after that partition's last row. In other words you get a little stateful program per key, written as ordinary Python.
The example is a loyalty punch card. Every dish earns a stamp, ten stamps earn a free dish (with the remainder carried over), and stamps expire after 30 days without an order. That last rule is what makes it a UDTF problem; without it this is floor(sum(...) / 10) over a window, but once a gap can wipe the balance, each order's outcome depends on the whole history before it, which window functions are pretty bad at expressing.
@udtf(returnType="customer string, on_date date, event string, stamps int")
class PunchCard:
def __init__(self):
# One instance per partition: this state lives for one customer's orders.
self.customer, self.stamps, self.last = None, 0, None
def eval(self, row):
self.customer = row["customer"]
if self.last and (row["ordered_on"] - self.last).days > 30:
yield self.customer, row["ordered_on"], "expired", self.stamps
self.stamps = 0
self.stamps += sum(int(n) for n in re.findall(r"(\d+)x", row["items"]))
self.last = row["ordered_on"]
while self.stamps >= 10:
self.stamps -= 10
yield self.customer, row["ordered_on"], "free dish", 10
def terminate(self):
# Runs once after the partition's last row.
yield self.customer, self.last, "balance", self.stamps
spark.udtf.register("punch_card", PunchCard)
spark.sql("""
SELECT * FROM punch_card(
TABLE(SELECT customer, ordered_on, items FROM orders)
PARTITION BY customer
ORDER BY ordered_on)
""")
+--------+----------+---------+------+
|customer| on_date| event|stamps|
+--------+----------+---------+------+
| ana|2026-11-27|free dish| 10|
| ana|2026-11-27| balance| 3|
| bo|2026-12-28| expired| 5|
| bo|2026-12-28| balance| 3|
| chidi|2026-11-05| balance| 1|
+--------+----------+---------+------+
Ana's four orders add up to 13 stamps, so she gets a free dish on November 27 and keeps 3; Bo's five stamps from November 3 expire when he comes back on December 28, so his balance is only that order's 3. The plan is the diagram above, Exchange then Sort then ArrowEvalPythonUDTF, which is worth knowing because PARTITION BY is a shuffle; you pay for it like any groupBy, and one enormous key still lands on one Python instance. WITH SINGLE PARTITION in place of PARTITION BY sends the whole table through one instance, which is occasionally what you want and usually a mistake.
On the JVM the nearest thing is groupByKey(...).flatMapGroups(...) on a typed Dataset, which can do the same job but can't be called from SQL.
Step 5: A table whose columns depend on the call (analyze)
Last UDTF trick, and the one I find the most fun. If you leave out returnType, you can give the class a static analyze() method that Spark calls while it's planning the query, with the arguments you passed (and their values, when they're constants), and it returns the output schema. So the columns can depend on how the function is called:
@udtf
class NoteFields:
@staticmethod
def analyze(notes: AnalyzeArgument, keys: AnalyzeArgument) -> AnalyzeResult:
schema = StructType()
for key in keys.value.split(","):
schema = schema.add(key, StringType())
return AnalyzeResult(schema=schema)
def eval(self, notes: str, keys: str):
pairs = dict(p.split("=", 1) for p in (notes or "").split(";") if "=" in p)
yield tuple(pairs.get(k) for k in keys.split(","))
note_fields(o.notes, 'spice,allergy') returns spice and allergy columns, and note_fields(o.notes, 'allergy') returns only allergy, so you can WHERE n.allergy IS NOT NULL on it like any other column (orders 1001 and 1003, peanut and dairy). AnalyzeResult can also set partitionBy, orderBy and select for a TABLE argument, so a function like PunchCard can require its own partitioning instead of trusting every caller to write PARTITION BY customer.
Once it's written, how do I make it faster?
Every fix here starts from the plan. The plan is Spark's description of how it will run the query, df.explain() prints it, and each line is an operator, one step of the work. Every example in the demo prints its operators, and the names give away where each function runs: ArrowEvalPython (a Python scalar UDF), ArrowAggregatePython (a Python aggregate), ArrowEvalPythonUDTF (a Python table function), and Generate (a JVM table function, built-in or yours).
Check whether it needs to be a UDF at all
Step 1's script prints two things for each version: the optimized plan's top Project (what Catalyst sees) and the executed plan's operators.
--- built-in
Project [order_id, lower(regexp_replace(trim(regexp_extract(items, ^\d+x([^;]*), 1), None), [^A-Za-z]+, -, 1)) AS slug]
Project
Scan
--- SQL UDF
Project [order_id, lower(regexp_replace(trim(regexp_extract(items, ^\d+x([^;]*), 1), None), [^A-Za-z]+, -, 1)) AS slug]
Project
Scan
--- @udf
Project [order_id, pythonUDF0 AS slug]
Project
ArrowEvalPython
Project
Scan
(@pandas_udf and @arrow_udf print exactly what @udf does.)
The SQL function's plan is character for character the built-in's, which is the whole case for SQL functions: you get a named, reusable function and the optimizer still sees every piece of it, so if your logic fits in Spark's built-ins, a SQL function costs you nothing at all. The Python versions all collapse into pythonUDF0, an opaque column that an ArrowEvalPython operator fills by shipping rows to the Python worker. In the UDF benchmark, at 50 million rows of arithmetic, the built-ins took 0.107 s, the SQL UDF 0.095 s, and the fastest Python UDF 0.725 s.
In Python, hand your function a batch
@udf calls your Python function once per value. @pandas_udf and @arrow_udf call it once per batch (up to 10,000 rows by default, set by spark.sql.execution.arrow.maxRecordsPerBatch), with the whole batch as one pandas Series or Arrow array, so the cost of entering Python is paid once per batch instead of once per row. In the same benchmark, arithmetic on 50 million rows took 5.2 s with a pickled @udf and 2.2 s with an Arrow-fed @udf, against 0.79 s with @pandas_udf and 0.73 s with @arrow_udf. Between those last two the gap is mostly strings, where @arrow_udf was about 1.6x faster, because Arrow keeps strings in one buffer while pandas has traditionally made a Python object per string.
Let aggregates combine partial results
A shuffle is Spark moving rows between executors so that all the rows with the same key end up together, and it's usually the most expensive step in a job because it goes over the network. Step 2's plans show how much each aggregate shuffles:
--- built-in --- @pandas_udf / @arrow_udf
Sort Sort
Exchange Exchange
HashAggregate ArrowAggregatePython
Exchange Sort
HashAggregate Exchange
Project Project
Scan Scan
The built-in aggregates twice, once on each executor before the shuffle (a partial sum and count per customer) and once after it, so only one small row per customer per partition crosses the network. A Python aggregate has no way to merge partial results, so every single row is shuffled, sorted by key, and handed to your function as one complete group, which means a skewed key puts its entire group in one Python call's memory. That's fine for small groups and a real memory risk for large ones. On the JVM, an Aggregator (further down) defines reduce and merge and gets the partial aggregation back.
So for an aggregate, the fix is a built-in expression when one exists (exp(avg(ln(x))) here), or a Scala or Java Aggregator when it doesn't.
Watch out for one enormous key
A Python aggregate gets a whole group in one call, and a UDTF with PARTITION BY gets one instance per key. Both are fine until one key has far more rows than the rest (a skewed key), because that key's rows all land in one call or one instance, on one executor, in one Python worker's memory. If a few keys dominate your data, check that before reaching for either.
Move the hot function to the JVM without leaving PySpark
A Java or Scala UDF in a jar can be registered from PySpark with spark.udf.registerJavaFunction and called like any other function, and its plan has no Python operator at all (the slug_java example in the language section). For a PySpark job where one function is the slow part and the logic won't fit in SQL, that gets it out of the Python worker without rewriting the job.
Don't be an idiot like me
A few of these cost me real time, so here they are with the exact errors.
-
Python versions have to match. My first run picked up Python 3.14 for the driver and 3.12 for the workers, and every UDF died with
[PYTHON_VERSION_MISMATCH] Python in worker has different version: 3.12 than that in driver: 3.14, PySpark cannot run with different minor versions.The demo pins 3.12 and setsspark.pyspark.pythonto the venv's interpreter. -
Aggregators in
spark-shelldidn't work for me. The ScalaAggregatordefined in a script loaded withspark-shell -ifirst failed withNotSerializableException(aColumnheld in a REPLvalgot captured), and after fixing that, withNoClassDefFoundError: Could not initialize class $line14.$read$on the executors. Compiled into a jar, the identical code runs, so the demo compiles it (with the Scala compiler that ships inside Spark's ownjars/folder, which is a fun thing to know exists). - Hive UDTFs need Hive, and say so in terms of UDAFs, as above.
-
Python aggregates and
PARTITION BYboth shuffle every row, which isn't an error but is the thing most likely to turn into one at scale.
In a Nutshell
- What a UDF is: your own function, registered so a query can call it like a built-in. The optimizer can't see inside it, and a Python one also has to run in a separate process.
-
The kinds: one row to one value is a scalar UDF, a group to one value is an aggregate, one row to many is a table function, and a partitioned table to a table is a UDTF with a
TABLEargument. - Choosing: pick the shape from how many rows go in and come out, then the cheapest place that can run it: built-ins, then a SQL function (inlined, fully optimized), then a Scala or Java UDF (in the JVM, opaque), then Python (in a separate worker, opaque).
-
The languages: SQL has scalar and table functions; Scala and Java have scalar UDFs and
Aggregators but no table function API of their own (explode an array in Scala, or use a HiveGenericUDTFon a Hive-enabled session); PySpark has every shape, including the onlyTABLEargument form. A function registered in one language can be called from another in the same session. -
Writing one: in Python the decorator decides what your function receives (one value for
@udf, a pandas Series for@pandas_udf, an Arrow array for@arrow_udf). UDTFs are classes whoseevalyields rows, called inFROMwithLATERAL; withTABLE(...) PARTITION BY ... ORDER BYyou get one instance per key andterminate()at the end, andanalyze()lets a UDTF choose its columns at planning time. -
Making it faster: read the plan; replace the UDF with built-ins or a SQL function if you can; in Python, use the batch decorators; for aggregates, prefer a built-in expression or a JVM
Aggregatorthat merges partial results; watch for skewed keys; and move one hot function to Java or Scala withregisterJavaFunction.
Nearly all of it comes back to the shape and the place: once you know how many rows your logic takes and returns, and which process it has to run in, the right function is usually the only one left.
Further reading
-
Python user-defined table functions, the PySpark guide to UDTFs,
TABLEarguments andanalyze(). - CREATE FUNCTION (SQL), the reference for SQL scalar and table functions.
- Scalar user-defined functions and user-defined aggregate functions, the Scala and Java APIs.
- Stop Blaming Serialization for Slow Python UDFs, my benchmark of the Python scalar UDFs.
- From Pickle to Arrow: A Decade of Moving Data Between Spark's JVM and Python, on everywhere Spark hands data to Python.
- spark-demos/demos/20_udfs_and_udtfs, every example here, runnable.





















Top comments (0)