AWS Training
Modules Listen Certification

← Senior Spark Technical Lead (Scala, Python) — Role Review

Starts this lesson and continues through 4 more to the end of the course.

Datasets, encoders, and closures — the Scala API on Spark

Why this matters

A PySpark engineer who opens a Scala Spark codebase meets three things Python never showed them: a typed Dataset[T], an Encoder that appears from an import, and a job that dies with Task not serializable before a single row is read. These are where a Scala team's Spark gets slow or brittle, and what a lead is asked to rule on in review.

What the posting is really asking. "Lead technical teams in the design and implementation of solutions using Apache Spark, Scala" and "conduct code reviews and performance optimization activities" meet here: you must say when the typed API is allowed, show in a plan what a lambda costs, and diagnose someone else's serialization failure from its stack.

Every plan and error below was produced on Spark 4.3.0, Scala 2.13.18, Java 17, local[2] on 2026-11-22. The docs overview confirms Spark 4.3.0 "runs on Java 17/21/25, Scala 2.13". Plans are trimmed (file location, Batched, REPL $line… class prefixes) and otherwise unaltered. Catalyst itself is module E7 of the sibling db-training repo.

DataFrame is Dataset[Row]

From the SQL programming guide (verified 2026-11-22): "In the Scala API, DataFrame is simply a type alias of Dataset[Row]." And: "The Dataset API is available in Scala and Java. Python does not have the support for the Dataset API. But due to Python's dynamic nature, many of the benefits of the Dataset API are already available (i.e. you can access the field of a row by name naturally row.columnName)."

import org.apache.spark.sql.{DataFrame, Dataset, Row, Encoders}
import spark.implicits._

case class Order(id: Long, customer: String, amount: Double)
val orders = Seq(Order(1, "acme", 120.0), Order(2, "globex", 75.5)).toDS()  // Dataset[Order]
val df: DataFrame = orders.toDF()
val same: Dataset[Row] = df                       // compiles: same type
val typed = spark.read.parquet(path).as[Order]    // DataFrame -> Dataset[Order]

Encoders

An Encoder[T] is "used to convert a JVM object of type T to and from the internal Spark SQL representation", and encoders "are generally created automatically through implicits from a SparkSession, or can be explicitly created by calling static methods on Encoders". That is what import spark.implicits._ is for. Without a usable encoder the code does not compile — observed with a plain (non-case) class:

error: Unable to find encoder for type Plain. An implicit Encoder[Plain] is needed to store Plain
instances in a Dataset. Primitive types (Int, String, etc) and Product types (case classes) are
supported by importing spark.implicits._

The explicit form is Encoders.product[T], "an encoder for Scala's product type (tuples, case classes, etc)". The encoder is a schema:

Encoders.product[Order].schema.simpleString  // struct<id:bigint,customer:string,amount:double>
Encoders.kryo[Order].schema.simpleString     // struct<value:binary>

When the case class and the data disagree

as[U] maps class fields "to columns of the same name". Four cases, all run against a three-column Parquet file:

Case class vs data When it fails What 4.3.0 raised
Extra field region: String At .as[...], before any job ExtendedAnalysisException: [UNRESOLVED_COLUMN.WITH_SUGGESTION] A column, variable, or function parameter with name region cannot be resolved.
id: Int where data is bigint At .as[...] AnalysisException: [CANNOT_UP_CAST_DATATYPE] Cannot up cast id from "BIGINT" to "INT".
Fewer fields than the data Never ds.columns still returned all three — as[] "does not eagerly project away any columns"
amount: Double, data has a NULL At runtime, inside a task SparkRuntimeException: [NOT_NULL_ASSERT_VIOLATION] NULL value appeared in non-nullable field

⚠️ Row 4 is the one that reaches production. Name and type mismatches fail on the driver; a null in a primitive field fails on whichever executor meets it first. The message names the fix: "please try to use scala.Option[_]". With amount: Option[Double] the same data returned NO(1,Some(1.0)) and NO(2,None). Review rule: every primitive case-class field over a nullable column is an Option — and StructField's nullable defaults to true, so most columns from files are nullable.

Typed versus untyped: what the plan shows

The same predicate, written two ways, against the same Parquet file:

typed.filter($"amount" > 498).explain()        // untyped: a Column expression
typed.filter(o => o.amount > 498).explain()    // typed: a Scala lambda

Untyped:

*(1) Filter (isnotnull(amount#2) AND (amount#2 > 498.0))
+- *(1) ColumnarToRow
   +- FileScan parquet [id#0L,customer#1,amount#2] DataFilters: [isnotnull(amount#2), (amount#2 > 498.0)],
      PushedFilters: [IsNotNull(amount), GreaterThan(amount,498.0)], ReadSchema: struct<id:bigint,customer:string,amount:double>

Typed:

*(1) Filter invoke($Lambda$4653/0x...apply(newInstance(class Order)))
+- *(1) ColumnarToRow
   +- FileScan parquet [id#0L,customer#1,amount#2] DataFilters: [],
      PushedFilters: [], ReadSchema: struct<id:bigint,customer:string,amount:double>

Both returned 200 rows. Differences:

The map I ran, o => o.amount * 2, uses one field, yet its scan read all three: column pruning follows the class, not what the lambda touches. A one-field case class Slim(id: Long) followed by map did prune to ReadSchema: struct<id:bigint>.

Grouping splits the same way. groupBy($"customer").sum("amount") planned HashAggregate(partial_sum) → Exchange → HashAggregate(sum) over a two-column scan. groupByKey(_.customer).mapGroups(...) planned AppendColumns → Exchange → Sort → MapGroups → SerializeFromObject over all three columns. The API doc says so: mapGroups "does not support partial aggregation, and as a result requires shuffling all the data in the Dataset" — use reduce or an Aggregator for per-key aggregation.

Column expression Lambda on Dataset[T]
Field-name typo (amont) UNRESOLVED_COLUMN when the job runs Compile error: value amont is not a member of Order
Parquet filter pushdown Yes (observed) No (observed)
Column pruning By columns referenced By the fields of T
Per-row object No Yes — newInstance
Aggregation Partial + final mapGroups: full shuffle, sort

⚠️ These are plan differences, not timings; nothing was benchmarked. Measure before quoting a speed-up.

Closures and Task not serializable

The RDD guide (verified 2026-11-22): "Prior to execution, Spark computes the task's closure. The closure is those variables and methods which must be visible for the executor to perform its computations … This closure is serialized and sent to each executor." A lambda that reads a field of its enclosing class captures the whole instance: it "is equivalent to writing rdd.map(x => this.field + x), which references all of this".

Compiled with the Scala 2.13.18 compiler that ships in Spark's jars/ and run with spark-submit:

class RateClient { def rate(ccy: String): Double = if (ccy == "EUR") 1.1 else 1.0 }  // not Serializable

class Pricing(spark: SparkSession, val markup: Double) {
  import spark.implicits._
  def run(ds: Dataset[Double]): Array[Double] = ds.map(x => x * markup).collect()   // reads this.markup
}
org.apache.spark.SparkException: Task not serializable
  Caused by: java.io.NotSerializableException: stl.Pricing
Serialization stack:
	- object not serializable (class: stl.Pricing, value: stl.Pricing@7d776105)
	- element of array (index: 0)

The first line of the serialization stack names the class that could not be serialized; the lines after it give the path to it. Three fixes, all executed (method bodies shown):

// 1. Copy the field to a local val — the lambda captures one Double.   -> 12.0,24.0
def run(ds: Dataset[Double]) = { val m = markup; ds.map(x => x * m).collect() }

// 2. Put the helper in an object — nothing is captured; each JVM builds its own.   -> 11.0,22.0
object Rates { val client = new RateClient; def eur(x: Double) = x * client.rate("EUR") }
def run(ds: Dataset[Double]) = ds.map(x => Rates.eur(x)).collect()

// 3. Serializable class, non-serializable member rebuilt lazily.   -> 13.2,26.4 (float tails trimmed)
class PricingTransient(val markup: Double) extends Serializable {
  @transient lazy val client = new RateClient
  def run(ds: Dataset[Double])(implicit e: Encoder[Double]) = ds.map(x => x * markup * client.rate("EUR")).collect()
}

Fix 1 is the guide's own: "the simplest way is to copy field into a local variable". Fix 2 is its "static methods in a global singleton object". Extending Serializable alone is not a fix — with a plain val client the failure moved one level down: NotSerializableException: stl.RateClient … field (class: stl.PricingHalf, name: client).

⚠️ @transient lazy val is not in the Spark pages listed above; it is verified by execution only.

⚠️ In spark-shell, fix 2 failed with NotSerializableException: PricingObj; the same source compiled into a jar worked. I found no doc page explaining it — reproduce serialization bugs in compiled code.

The other closure trap is mutation. The guide's var counter example, run here on local[2], printed Counter value: 0; the guide calls the behaviour "undefined".

Broadcast variables and accumulators

From the same guide: broadcast variables "keep a read-only variable cached on each machine rather than shipping a copy of it with tasks". Create with sc.broadcast(v), read with .value; release with .unpersist() (re-broadcast on next use) or .destroy() (permanent; a later read raised INTERNAL_ERROR_BROADCAST). Spark already broadcasts the common data tasks need within a stage, so an explicit broadcast "is only useful when tasks across multiple stages need the same data or when caching the data in deserialized form is important".

Accumulators are created with sc.longAccumulator("name") or sc.doubleAccumulator; tasks add, and "only the driver program can read the accumulator's value". The guarantee, verbatim:

For accumulator updates performed inside actions only, Spark guarantees that each task's update to the accumulator will only be applied once, i.e. restarted tasks will not update the value. In transformations, users should be aware of that each task's update may be applied more than once if tasks or job stages are re-executed.

Run here: an accumulator incremented inside map over 100 elements read 0 before any action, 100 after one count(), 200 after a second count() on the same uncached RDD. Accumulators in transformations are debugging counters, never business numbers.

Kryo, Java serialization, and why Datasets use neither

Fact Source (verified 2026-11-22)
spark.serializer default is org.apache.spark.serializer.JavaSerializer configuration; the 4.3.0 shell reported it unset and SparkEnv using JavaSerializer
Kryo is "significantly faster and more compact than Java serialization (often as much as 10x)" but "does not support all Serializable types" tuning guide
The setting covers "shuffling data between worker nodes" and "serializing RDDs to disk"; Kryo is not the default only "because of the custom registration requirement" tuning guide
spark.kryo.registrationRequired defaults to false; spark.kryoserializer.buffer.max to 64m configuration
Datasets: "instead of using Java serialization or Kryo they use a specialized Encoder" getting started

So Kryo matters for RDD-heavy code, not for the rows of a Dataset[Order]. The exception is opting in: Encoders.kryo[T] "maps T into a single byte array (binary) field". Run here, a Kryo-encoded Dataset[Order] had schema struct<value:binary> and filter($"amount" > 0) failed with UNRESOLVED_COLUMN … Did you mean one of the following? [value]. The columns are gone, and with them everything the optimizer could do.

The closure failures above were raised from JavaSerializerInstance.serialize inside SparkClosureCleaner.clean. ⚠️ I found no documented setting for the closure serializer, so do not expect Kryo to cure Task not serializable.

Scala UDFs

udf(f) "defines a Scala closure … as user-defined function (UDF). The data types are automatically inferred based on the Scala closure's signature." Null handling, executed on a column holding 10 and NULL:

UDF argument type Result for the NULL row Why
(x: Int) => x + 1 NULL Spark guards the call: a primitive-argument UDF planned as if (isnull(amount)) null else UDF(knownnotnull(amount))
(x: Option[Int]) => x.map(_ + 1) NULL No guard — an Option-argument UDF planned as plain UDF(amount)
(x: java.lang.Integer) => x == null true Lambda receives the null
(s: String) => s.length Fails [FAILED_EXECUTE_UDF] … java.lang.NullPointerException: Cannot invoke "String.length()" because "s" is null

⚠️ "A null primitive becomes 0" belongs to the untyped overload udf(f: AnyRef, dataType), where "the result is 0 for null input". The migration guide says that overload "is not allowed by default" since Spark 3.0 unless spark.sql.legacy.allowUntypedScalaUDF is set.

A Scala UDF avoids the Python worker (PS0 lesson 3) but is still a black box:

*(1) Filter if (isnull(amount#2)) false else UDF(knownnotnull(amount#2))
+- *(1) ColumnarToRow
   +- FileScan parquet [id#0L,customer#1,amount#2] DataFilters: [if (isnull(amount#2)) false else UDF(knownnotnull(amount#2))],
      PushedFilters: [], ReadSchema: ...

PushedFilters: [] again — same 200 rows, no pushdown. Prefer a built-in from functions.

What a lead does with this

When to allow typed Dataset APIs. Allow .as[T] at module boundaries, where a compile-checked schema documents a contract, and lambdas for row logic with no column expression — after the filters and projections. Reject a lambda filter over a file scan, and groupByKey + mapGroups where groupBy().agg() would do.

The serialization smell list.

The one line for juniors. Columns first; lambdas only for what columns cannot say — and run explain() before you ask for review.

Check yourself

  1. In Scala, what is the relationship between DataFrame and Dataset? What does Python have?
  2. A job reads Parquet with .as[Event], passes every test, and fails in production with NOT_NULL_ASSERT_VIOLATION. What is wrong with Event?
  3. A stack reads Task not serializable … NotSerializableException: com.acme.Pipeline. What happened, and which fix do you reach for first?
  4. An accumulator updated inside map reports twice the row count. Bug in Spark?
  5. A teammate proposes spark.serializer=KryoSerializer to speed up a Dataset[Order] pipeline.
Answers
  1. DataFrame "is simply a type alias of Dataset[Row]". "Python does not have the support for the Dataset API" — it has DataFrames only.
  2. A primitive field (Double, Long, Int) sits over a nullable column. Names and types are checked at .as[...]; nulls are only met at runtime. Make the field an Option.
  3. A lambda used a field or method of Pipeline, so it captured this. First fix: copy the field into a local val before the lambda, as the RDD guide recommends — not extends Serializable.
  4. No. The exactly-once guarantee covers updates "performed inside actions only"; in transformations an update "may be applied more than once". Two actions over an uncached lineage ran the map twice — reproduced here as 100 then 200.
  5. It will not change how the Dataset's rows are serialized: Datasets "instead of using Java serialization or Kryo … use a specialized Encoder". Ask where the time goes first (lesson 4).

Teaching this section

← PreviousScala for Spark engineers — the language you have to read and reviewNext →Scala or Python — choosing per workload and running a mixed team