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

  1. Physical plan is ready
  2. Do the operators support code generation? Yes: Fuse them into one generated function per stage. No: Run those operators interpreted.
  3. Compile the generated Java code at runtime
  4. Process rows in tight loops over binary UnsafeRows
  5. Exchange writes shuffle data and ends the stage
  6. 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.size

Example

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

Apache Spark topics

Spark Fundamentals

Spark Architecture

RDDs

DataFrames

Aggregations & Joins

Spark SQL

Window Functions

Cleaning & Complex Types

UDFs

Performance Tuning

Structured Streaming

MLlib & Ecosystem

Interview Prep

T
Tech Town
Log InSign Up Free
Home SQL Python DSA Power BI Snowflake Databricks Spark Gen AI Practice Problems Contest Blog

Master Apache Spark

PySpark and Spark SQL from the ground up: DataFrames, joins, window functions, partitions and performance tuning, Structured Streaming and more. Click any topic in the sidebar to open it right here.

{{ sectionCount }}
Sections
{{ topicCount }}
Topics
Free
Forever
Hands-on practice Practice PySpark Write real PySpark — DataFrames, joins, window functions and Spark SQL — in a live editor with hidden tests and instant checking. Start practising →
Section {{ sec.num }}

{{ sec.label }}

Spark  /  {{ current.sectionLabel }}  /  {{ current.name }}

{{ current.name }}

Theory

{{ current.def }}

Why we use it

{{ rich.why }}

When to use it

{{ rich.when }}

{{ sec.h }}

{{ sec.body }}

{{ sec.body }}

Diagram

{{ rich.dg.caption }}

{{ tb.title }}
{{ c.v }}
{{ rich.dg.op }}
➜
{{ rich.dg.output.title }}
{{ c.v }}
{{ nd.label }}
{{ nd.sub }}
{{ nd.label }}
{{ nd.sub }}
{{ rich.dg.left.title }}
{{ it }}
{{ rich.dg.right.title }}
{{ it }}
On screen — where to click

{{ rich.ui.title }}

{{ u.text }}
  1. {{ st.n }}{{ st.text }}
{{ rich.ui.title }}
{{ u.text }}
Flowchart — how it works
{{ nd.text }}
{{ nd.text }}
◇ {{ nd.text }}
Yes → {{ nd.yes }}
No → {{ nd.no }}
Syntax
{{ current.syntax }}
Example
{{ current.example }}
Want to run this yourself? Try the same API on Practice PySpark Online right in your browser, or run it locally after pip install pyspark (needs Java 17+), or paste it into a Databricks Free Edition notebook.
Key Points — click to check off as you learn
  • {{ pt.mark }} {{ pt.text }}

Share this topic