Tech challenge · PySpark

A Python UDF makes the job ten times slower

MediumPySpark

A job cleans phone numbers with a Python UDF that strips spaces and dashes and adds a country code. It is the slowest stage by far. Why are Python UDFs slow, and what would you do instead?

Think it through or sketch an answer first, then open the hint or the solution.

Show a hint

Where does the Python code run, and how does each row get there?

Show the solution

A plain Python UDF runs in a separate Python worker: every row is serialised out of the JVM, processed one at a time in Python and sent back, and the optimiser cannot see inside it. First choice: rewrite it with built-in functions such as regexp_replace and concat, which run in the JVM and are optimised. If you really need Python, use a vectorised pandas UDF, which moves data in Arrow batches.

Example (Python)

from pyspark.sql import functions as F

clean = F.regexp_replace('phone', r'[\s-]', '')
df = df.withColumn('phone', F.when(clean.startswith('+'), clean)
                             .otherwise(F.concat(F.lit('+91'), clean)))

Common mistakes

  • Caching the input to speed up the UDF: the cost is per-row serialisation, not reading.
  • Assuming a pandas UDF is always fine: it still leaves the JVM, so built-ins come first.

Learn more

More PySpark challenges

Today's challenge and the full archive