Pickle at the Border
Pickle is Python's standard format for turning objects into bytes and back, and the JVM side of Spark speaks it too, which is how the 2 processes exchange values. Whatever crosses the socket is pickled by the sender and unpickled by the receiver, so each argument changes form several times before your function sees it.
A value's round trip
Take the product_name value " Wireless Mouse " and a UDF that returns s.strip().lower(). These are the forms that value takes on its way to Python and back.
| # | Where | Form of the value |
|---|---|---|
| 1 | JVM | UTF-8 bytes inside Spark's internal row, as the scan produced them |
| 2 | JVM | A Java `String` object, allocated so the pickler can read it |
| 3 | JVM | Pickle bytes: an opcode, a length and the text, appended to a batch of 100 |
| 4 | Socket | The batch copied through the operating system to the worker |
| 5 | Python | A Python `str`, allocated by the unpickler |
| 6 | Python | Your function runs and returns a new `str`, `"wireless mouse"` |
| 7 | Python | Pickle bytes again, appended to the result batch |
| 8 | Socket | The result batch copied back through the operating system |
| 9 | JVM | Unpickled into a Java `String`, then converted to Spark's internal string |
Only step 6 is code you wrote. The other 8 are format changes and copies, and each one costs a memory allocation or copy per value. strip() and lower() run as C code inside the interpreter and finish quickly on a short string, while the steps around them run for every row whatever the function does. For a typical UDF those steps are the larger part of the bill, so making the function body twice as fast barely moves the job's runtime. Step 9 also enforces the declared return type: a Python float returned from a UDF declared "int" cannot be converted and arrives as null.
What sets the size of the bill
Serialization cost grows with
- Rows reaching the UDF: Every row is converted and copied in both directions, so 10 times the rows means 10 times the border work.
- Bytes in the arguments: A 4-byte integer and a 2KB JSON string cost the same Python call but very different pickling and copying.
- Bytes in the result: Returning a long string or a large array pays the trip a second time on the way back.
- Shape of the values: A struct arrives as a Row object and an array as a list, while maps become dicts. Every nested value inside them is its own Python object.
Width deserves arithmetic. Suppose 50 million events where payload is a JSON string averaging 1,800 bytes and event_type averages 12 bytes. A UDF that reads payload to pull out a single field ships far more to Python than a UDF that reads event_type, before any pickle framing is added.
| UDF argument | Average bytes | Rows | Bytes sent to Python |
|---|---|---|---|
| `payload` | 1,800 | 50,000,000 | 90 GB |
| `event_type` | 12 | 50,000,000 | 600 MB |
So shrink what crosses. Extract the field with a built-in such as F.get_json_object("payload", "$.device") first and hand only that short string to the UDF, if a UDF is still needed. The same reasoning rules out my_udf(F.struct("*")), which pickles every column of every row to use 2 of them.
The border holds memory as well as time. While a batch is in Python, the JVM keeps the original rows in a queue so it can attach each result to the right row, and that queue spills to disk when it outgrows memory. On the Python side, every unpickled value is an object the interpreter allocates and later frees. A wide argument costs CPU in the conversions and memory on both sides of the socket.
This UDF runs over 80 million webhook rows, where body averages 3KB, and takes 40 minutes. Which change removes the most border work?
status_udf = F.udf(lambda b: json.loads(b)["status"] if b else None, "string")
out = hooks.withColumn("status", status_udf("body"))- Replace the UDF with F.get_json_object("body", "$.status"), so the 3KB string never leaves the JVM
- Swap json.loads for a faster JSON parser inside the UDF, because parsing is the slow step
- Pass F.struct("*") so the UDF reads body and every other column in a single call
- Raise spark.sql.shuffle.partitions so the UDF's rows are spread over more tasks
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.