Zero Labs
Industry News / AI

Part XVI — Whole-Stage Codegen: The Tungsten Trick Behind 2x Speedups

Source · Towards AI By chakshu_salgotra

From the publisher’s feed, collected in the ZeroLabs newsroom.

Your Spark job is not slow because of your data. It is slow because Spark is interpreting your query one virtual function call at a time — unless Tungsten’s code generator compiled the whole stage into a single tight loop. Here is how that compilation works, what silently disables it, and how to get the 2x back.Part I | Part II | Part III | Part IV | Part V | Part VI | Part VII | Part VIII | Part IX | Part X | Part XI | Part XII | Part XIII | Part XIV | Part XV | Part XVIThe Query That Got 3x Slower After We “Optimized” ItIt was a Tuesday, which is worse than a 3 AM page because nobody expects a Tuesday. Our nightly clickstream ETL — 9.2TB of raw JSON events, parsed, normalized, and written to Delta — had been running in 41 minutes for months. We migrated it to a new cluster, bumped Spark from 3.3 to 3.5, and swapped our hand-rolled timestamp parser for a “cleaner” Scala UDF that handled three legacy date formats in one place. The next morning the job had taken 2 hours and 7 minutes. Nothing else changed. Same data volume, same cluster shape, same partitions.The Spark UI told a story I have now seen a dozen times. The heavy stage — the one that parsed JSON, filtered bots, and projected 40 columns down to 12 — showed task deserialization fine, GC fine, no skew, no spill. Just CPU time that had tripled. The executors were burning cycles doing… nothing visible. No shuffle wait. No I/O wait. Pure, unexplained CPU burn on a stage that was supposed to be embarrassingly parallel and embarrassingly simple.I pulled the plan with EXPLAIN. And there it was, in the most boring diff imaginable: the stage that used to read *(4) Project [ ... ] — note the asterisk — now read plain Project [ ... ]. No asterisk. No WholeStageCodegen. The stage had lost its compilation, and the culprit was our shiny new Scala UDF sitting inside the projection. One expression, unsupported by the code generator, had poisoned the entire stage back into the interpreted iterator loop. The "cleaner" code was costing us 86 minutes a night — roughly $4,100 a month in wasted compute at our cluster rates — because of a single asterisk in a query plan nobody checks.So: what does that asterisk actually mean, what machine is doing the compiling, and what are all the quiet ways your pipeline can lose it?The Mechanic Underneath: Your Query Is a Tree, and Trees Can Be CompiledEvery Spark SQL query you write becomes an expression tree. filter($"status" === "click") is not a function call — it is a tree node EqualTo with two children, sitting inside a Filter operator node, sitting inside a Project operator node. In the classic Volcano iterator model that Spark inherited, each operator is an object with a next() method, and executing the query means calling next() down the tree, one row at a time, one operator at a time. A filter on top of a scan on top of a project means three virtual method dispatches per row. On 9.2TB — roughly 40 billion rows — that is hundreds of billions of virtual calls, each one defeating branch prediction and keeping your data bouncing between CPU caches instead of living in registers.Whole-stage codegen deletes that overhead in one move. Instead of interpreting the operator tree at runtime, Spark walks the tree once and generates a single Java method that does the whole pipeline: read a row, apply the filter, apply the projection, write the output — in one tight loop, no virtual dispatch, data staying in registers. That generated source is compiled in-memory by Janino, a lightweight Java compiler embedded in Spark, and the resulting bytecode is what your executors actually run. The * in the plan marks stages that got this treatment. This is the Tungsten project (Spark 2.0+) doing what it promised: treating your query like a compiler treats a program, not like an interpreter treats a script.The key insight: codegen operates on pipelines of operators, not individual operators. Catalyst finds maximal subtrees of the physical plan that can be fused — typically everything between two shuffle boundaries — and generates one function per subtree. Your 40-column projection, your filter, your expression evaluation: all of it becomes straight-line code inside a single while (input.hasNext()) loop. That is where the 2x comes from. Not from better algorithms. From deleting the interpreter.The Volcano Model Is Elegant, and It Costs You a Virtual Call per RowThe iterator model is beautiful computer science. Each operator implements next(): the scan's next() reads a row, the filter's next() loops until a row passes, the project's next() transforms it. Composition is trivial, and every database textbook teaches it. But elegance is not free. A virtual call per operator per row means the CPU cannot inline across operator boundaries, cannot keep the row in registers across the pipeline, and pays branch-misprediction penalties on every dispatch. For a pipeline of five operators over a billion rows, you are paying five billion virtual dispatches before you have done a single useful comparison. Tungsten's bet — correct, as it turned out — was that this dispatch tax, not your logic, dominates CPU-bound stages. When your stage is filter-and-project heavy with no shuffle, the interpreter is the bottleneck.Codegen Collapses the Pipeline Into a Single FunctionHere is what actually happens when Catalyst plans your query. After analysis and optimization, the physical planner looks for pipelining opportunities: chains of operators like Filter → Project → Filter that process rows one at a time without materializing intermediate results. It wraps each maximal chain in a WholeStageCodegenExec node — that is the * you see in EXPLAIN output, e.g. *(4) Project [...]. Then the code generator walks the expression trees inside and emits Java source: the filter predicate becomes an if statement, the projection becomes direct field assignments, null checks become explicit branches. Janino compiles it, the JVM JIT-compiles it again into native code, and your 40-billion-row stage runs as machine code with the row living in registers the whole way through. Two compilation layers, zero virtual calls. The measurable result on CPU-bound stages is routinely 1.5–2.5x — which is why losing the asterisk tripled our stage time: we did not just lose an optimization, we fell off a cliff back into the interpreter.One Bad Expression Poisons the Entire StageThis is the part that burns people. Codegen is all-or-nothing per stage. The generator supports a fixed set of expressions; if any single expression in the pipeline cannot be generated, the entire stage falls back to interpreted mode. The usual suspects:Python UDFs (BatchEvalPython) — never codegen'd. The data crosses a process boundary to Python per batch; there is nothing to compile.Scala/Java UDFs (ScalaUDF) — the generator cannot see inside your arbitrary function, so the whole stage falls back.A handful of exotic expressions and complex UDT handling in older versions.Extremely wide projections can hit generator limits (more on that below).How do you spot it? EXPLAIN (or the SQL tab in the UI): codegen'd stages carry the * prefix — *(2) Filter, *(4) Project. A stage that fell back shows the operators bare, sometimes with an explicit CODEGEN_FALLBACK marker in newer versions, and the plan will show an InputAdapter where the whole-stage node would have been. The config spark.sql.codegen.wholeStage (default true) is the master switch, and spark.sql.codegen.fallback (default true) controls whether Spark silently falls back to interpreted mode instead of failing. Silent fallback is the default — which is exactly why our Tuesday was a surprise. The job did not error. It just got slow, politely.The JVM Has a 64KB Opinion About Your Generated CodeEven when every expression is supported, the generated method can hit hard JVM limits. A Java method cannot exceed 64KB of bytecode, and a 200-column projection with complex expressions can generate a method that blows past it. Spark handles this with method splitting, governed by two configs you should know exist: spark.sql.codegen.hugeMethodLimit (default 65535, the bytecode-size threshold that triggers splitting) and spark.sql.codegen.maxFields (default 100, which caps generated fields per class before splitting into multiple classes). When you see a stage that should be codegen'd but is not, and there is no UDF in sight, check the driver logs for codegen compilation warnings — oversized generated code is the usual second culprit after UDFs. The fix is the same shape as everything in this series: narrower projections (Part I's Parquet lesson rhymes here — read fewer columns, generate smaller methods).The Fix, and What It CostThe naive code was our “cleaner” timestamp parser — a Scala UDF registered once and used in the projection:# Naive: a Scala UDF for legacy timestamp formats. One unsupported expression# poisons the ENTIRE stage back to the Volcano iterator loop - no more *(n).# spark.udf.register("parse_ts", lambda s: ...) # ScalaUDF: codegen fallback# Optimized: built-in expressions only. Every expression here is codegen-safe,# so the whole Filter -> Project pipeline compiles into ONE generated function.parsed = ( raw .filter(F.col("event_type") == "click") # codegen: *(n) Filter .withColumn( "event_ts", F.coalesce( # codegen-safe branch F.to_timestamp("ts_raw", "yyyy-MM-dd HH:mm:ss"), F.to_timestamp("ts_raw", "MM/dd/yyyy HH:mm"), F.to_timestamp("ts_raw", "yyyyMMddHHmmss"), ), ) .select("user_id", "event_ts", "url", "session_id") # narrow: small method)spark.conf.set("spark.sql.codegen.wholeStage", "true") # default true; verify, don't assume# EXPLAIN should show: *(4) Project [...], *(2) Filter [...] (asterisks = compiled)Same semantics, three built-in format attempts instead of one opaque UDF. The plan regained its asterisks on every stage. The measured result on the next nightly run: stage time 2h07m → 38 minutes, total job 2h07m → 41 minutes — the full 86 minutes recovered, plus 3 from the narrower projection. CPU time on the stage dropped 68%. Monthly compute cost for the pipeline went from ~$6,200 back to ~$2,100. The UDF version was not wrong — it was uncompilable, and in Spark those are very different things.The Catch: Codegen Fixes the Interpreter, Not Your JobThree honest limits. First, codegen only accelerates CPU-bound, pipelined stages. If your stage is shuffle-bound (Part II) or skew-bound (Part VII), compiling the filter loop buys you almost nothing — the bottleneck is data movement, and no generated bytecode fixes a straggler partition. Second, codegen has a compile-time cost: on enormous plans with thousands of expressions, Janino compilation itself can take minutes and bloat driver memory. If your job has a suspiciously long planning phase, spark.sql.codegen.wholeStage=false is a legitimate diagnostic, not heresy. Third, generated code is harder to debug — stack traces point at GeneratedClass$...$ line numbers that map to nothing you wrote. When a codegen'd stage throws, the first step is often disabling codegen to get a readable stack trace, fixing the logic, and re-enabling. The asterisk is a performance feature with a debuggability tax. Pay it knowingly.TakeawaysThe * is the plan telling you it compiled: *(4) Project means one generated function; a bare Project means the Volcano interpreter loop. Read your EXPLAIN output like a compiler engineer.Fallback is per-stage and all-or-nothing: one unsupported expression — a Scala UDF, a Python UDF — poisons the entire pipeline back to interpreted mode.Silent fallback is the default: spark.sql.codegen.fallback=true means the job gets slow instead of failing. slowness without errors is the signature symptom.Built-ins are a performance feature: coalesce + to_timestamp with multiple formats does what your UDF did, and the generator can see through it.Generated methods hit JVM limits: 64KB per method; spark.sql.codegen.hugeMethodLimit and maxFields govern the splitting. Narrow projections help twice.Codegen is for CPU-bound stages: it will not save a shuffle-bound or skew-bound job. Fix the bottleneck you actually have (Parts II and VII).Codegen does not make your logic faster. It deletes the interpreter standing between your logic and the CPU — and one invisible expression can put the interpreter right back.If this saved you a 3 AM pager incident, follow me on Medium for Twice a week for the next 3 Months of Advanced Data Engineering & AI. Let’s connect on LinkedIn and X.Part XVI — Whole-Stage Codegen: The Tungsten Trick Behind 2x Speedups was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.