Tungsten & whole-stage codegen
Apache Spark · Spark SQL
Theory
Tungsten is Spark's execution engine work focused on CPU and memory efficiency. Instead of storing rows as many small JVM objects, Spark keeps them in a compact binary format (UnsafeRow) in memory it manages itself, on or off the JVM heap. This cuts garbage-collection pauses and memory use, and lets operators such as sort, aggregation and joins work directly on binary data with cache-friendly layouts.
Whole-stage code generation fuses a chain of operators (scan, filter, project, partial aggregate) into one generated Java function per stage, compiled at runtime, so each row flows through tight loops without virtual function calls between operators. In explain() output, operators prefixed with *(1), *(2) belong to code-generated stage 1, 2 and so on; operators without a star, such as Exchange, run outside codegen. For example, a filter, a projection and a partial sum on orders all appear as *(1) and run as one generated loop before the shuffle.
Why we use it
Tungsten and codegen are why DataFrame code with built-in functions runs much faster than RDD lambdas or Python UDFs: Spark controls the data layout and generates specialised code. Knowing this explains the advice to avoid UDFs and to read the *(n) markers in plans.
When to use it
You get Tungsten and codegen automatically with DataFrames and SQL. Help it by using built-in functions instead of Python UDFs, and check explain() for *(n) markers. Very wide or complex queries can exceed codegen limits and fall back to slower interpreted execution, which shows up in logs.
How it works
- Physical plan is ready
- Do the operators support code generation? Yes: Fuse them into one generated function per stage. No: Run those operators interpreted.
- Compile the generated Java code at runtime
- Process rows in tight loops over binary UnsafeRows
- Exchange writes shuffle data and ends the stage
- Next codegen stage continues
Syntax
df.explain() # *(1) ... = whole-stage codegen stage 1
df.explain("codegen") # print the generated Java code
spark.sql.codegen.wholeStage # true by default
spark.memory.offHeap.enabled / spark.memory.offHeap.sizeExample
from pyspark.sql import SparkSession, functions as F
spark = (SparkSession.builder.master("local[1]")
.config("spark.ui.enabled", "false")
.getOrCreate())
orders = spark.createDataFrame([
(101, 1, "North", "Laptop", 1, 55000.0, "2026-01-05"),
(102, 2, "West", "Phone", 2, 30000.0, "2026-01-06"),
(103, 1, "North", "Mouse", 3, 1500.0, "2026-01-06"),
(104, 3, "South", "Laptop", 1, 52000.0, "2026-01-07"),
(105, 4, "West", "Tablet", 1, 25000.0, "2026-01-08"),
(106, 2, "East", "Phone", 1, 15000.0, "2026-01-08"),
(107, 5, "North", "Tablet", 2, 48000.0, "2026-01-09"),
(108, 3, "South", "Mouse", 4, 2000.0, "2026-01-10"),
], "order_id INT, customer_id INT, region STRING, product STRING, "
"qty INT, amount DOUBLE, order_date STRING"
).withColumn("order_date", F.to_date("order_date"))
q = (orders.filter(F.col("amount") > 10000)
.withColumn("gst", F.col("amount") * 0.18)
.groupBy("region").agg(F.sum("gst").alias("gst_total")))
q.collect() # run it so AQE shows the final plan
q.explain() # *(n) prefixes = whole-stage codegen stages
spark.conf.set("spark.sql.codegen.wholeStage", "false")
print("--- with whole-stage codegen turned off: no *(n) markers ---")
orders.filter(F.col("amount") > 10000).select("order_id").explain()
# Output:
# == Physical Plan ==
# AdaptiveSparkPlan isFinalPlan=true
# +- == Final Plan ==
# ResultQueryStage 1
# +- *(2) HashAggregate(keys=[region#2], functions=[sum(gst#8)])
# +- AQEShuffleRead coalesced
# +- ShuffleQueryStage 0
# +- Exchange hashpartitioning(region#2, 200), ENSURE_REQUIREMENTS, [plan_id=32]
# +- *(1) HashAggregate(keys=[region#2], functions=[partial_sum(gst#8)])
# +- *(1) Project [region#2, (amount#5 * 0.18) AS gst#8]
# +- *(1) Filter (isnotnull(amount#5) AND (amount#5 > 10000.0))
# +- *(1) Scan ExistingRDD[order_id#0,customer_id#1,region#2,product#3,qty#4,amount#5,order_date#6]
# +- == Initial Plan ==
# HashAggregate(keys=[region#2], functions=[sum(gst#8)])
# +- Exchange hashpartitioning(region#2, 200), ENSURE_REQUIREMENTS, [plan_id=19]
# +- HashAggregate(keys=[region#2], functions=[partial_sum(gst#8)])
# +- Project [region#2, (amount#5 * 0.18) AS gst#8]
# +- Filter (isnotnull(amount#5) AND (amount#5 > 10000.0))
# +- Scan ExistingRDD[order_id#0,customer_id#1,region#2,product#3,qty#4,amount#5,order_date#6]
#
#
# --- with whole-stage codegen turned off: no *(n) markers ---
# == Physical Plan ==
# Project [order_id#0]
# +- Filter (isnotnull(amount#5) AND (amount#5 > 10000.0))
# +- Scan ExistingRDD[order_id#0,customer_id#1,region#2,product#3,qty#4,amount#5,order_date#6]
Key points
- Tungsten: binary UnsafeRow format and Spark-managed memory, less GC
- Whole-stage codegen fuses operators of a stage into one generated function
- *(n) in explain() = operator inside codegen stage n; Exchange breaks stages
- Python UDFs cannot be fused into generated code; built-in functions can
- Codegen is on by default; turning it off is only for debugging