AWS Training
Modules Listen Certification

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

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

Code review, testing, and deployment for Spark

Why this matters

A Spark job that is wrong rarely fails. It writes plausible numbers, and someone outside the team finds out a quarter later. Review, tests and the deploy path are where a team catches that first, and a lead owns all three: by deciding what every reviewer checks, what "tested" means, and what "done" means.

What the posting is really asking. "Ensure adherence to best practices in coding, testing, and deployment processes" and "conduct code reviews" mean: you can hand the team a checklist whose every line names a mechanism, show a Scala and a Python engineer how to test a transformation without a cluster, and say how a jar or script reaches EMR or Glue, and which Spark version is waiting there.

PS0 lesson 5 covers splitting transformations from I/O and a pytest fixture; this lesson adds the reviewer's side, the Scala side, and deploy mechanics. Scala-language review items are in lesson 1; performance triage is lesson 4.

Fetched or executed 2026-11-22. Outputs are from Spark 4.3.0, Scala 2.13.18, Java 17, local mode.

A PR review checklist, ordered by blast radius

A wrong number that ships quietly outranks a job that dies loudly, which outranks a slow one.

# Check The mechanism to cite Source
1 Join key is unique where you assume A duplicate key multiplies rows; nothing errors Executed below
2 NULLs in keys and filters = on NULL is unknown, so NULL keys drop out of an inner join. "NOT IN always returns UNKNOWN when the list contains NULL" Null semantics
3 ANSI behaviour "By default, spark.sql.ansi.enabled is true": invalid input throws "instead of returning null results". On by default "since Spark 4.0" (migration guide) ANSI compliance
4 Non-deterministic expressions UDFs "are considered deterministic by default... duplicate invocations may be eliminated"; monotonically_increasing_id "depends on partition IDs" udf, id
5 Time zone is pinned spark.sql.session.timeZone defaults to "(value of local timezone)" Configuration
6 Write is idempotent Save modes "are not atomic"; partition overwrite defaults to STATIC Next section
7 collect() / toPandas() Only for small results, "as all the data is loaded into the driver's memory" collect, toPandas
8 Window without partitionBy Unordered windows default to an unbounded frame; unpartitioned ones log "Moving all data to a single partition" Window; warning observed
9 withColumn in a loop "can generate big plans which can cause performance issues and even StackOverflowException. To avoid this, use select() with multiple columns at once" withColumn
10 Schema declared, not inferred CSV inferSchema (default false) "requires one extra pass over the data"; Parquet schema merging is "relatively expensive" and off by default CSV, Parquet
11 No deploy config in code See "Config" below Configuration

Rows 1, 2, 3 and 9, executed (setup abbreviated; F is pyspark.sql.functions):

j = orders.join(cust, "cust")              # cust has two rows for c1
# orders: 3 rows, sum 22 | after join: 5 rows, sum 37

a.join(b, "k").count()                     # 1   — the NULL-key row is gone
a.join(b, a.k.eqNullSafe(b.k)).count()     # 2
spark.sql("select * from a where v not in (select 5 union all select null)").count()   # 0

spark.sql("select cast('abc' as int)")     # NumberFormatException: [CAST_INVALID_INPUT] ... Use `try_cast`
spark.sql("select try_cast('abc' as int)") # NULL

for i in range(50): loop = loop.withColumn(f"c{i}", F.col("id") + i)
once = base.withColumns({f"c{i}": F.col("id") + i for i in range(50)})
# Project nodes in analyzed plan -> loop: 50 | withColumns: 1

⚠️ The warning is on the withColumn page only; withColumns takes a dict, carries no such note, and produced one projection here.

⚠️ I expected rand() to differ between two collect() calls on one DataFrame; both returned identical values. I have not verified when values change, so the rule is conservative: no non-deterministic expression in a join key, a dedupe key, or anything a retry must reproduce.

Idempotent writes

From save modes (verified 2026-11-22): the default is error/errorifexists; the others are append, overwrite, ignore. They "do not utilize any locking and are not atomic", and "when performing an Overwrite, the data will be deleted before writing out the new data".

PS0 lesson 5 left the partition-overwrite key unverified. It is spark.sql.sources.partitionOverwriteMode, default STATIC: "In static mode, Spark deletes all the partitions that match the partition specification... In dynamic mode, Spark doesn't delete partitions ahead, and only overwrite those partitions that have data written into it at runtime." A per-write option "takes precedence". Executed:

day("2026-11-22", 3).write.partitionBy("dt").mode("overwrite").parquet(d)
# static rerun : ['dt=2026-11-22']                      <- 11-20 and 11-21 deleted

day("2026-11-22", 3).write.partitionBy("dt").mode("overwrite") \
    .option("partitionOverwriteMode", "dynamic").parquet(d)
# dynamic rerun: ['dt=2026-11-20', 'dt=2026-11-21', 'dt=2026-11-22']
# run again    : 3 rows in dt=2026-11-22                <- idempotent
# mode("append") rerun: 6 rows in dt=2026-11-22         <- a retry doubled it

⚠️ The default deletes every partition you did not write: a daily job with mode("overwrite"), partitionBy and no dynamic setting erases history. The config "doesn't affect Hive serde tables". I did not test table formats (Iceberg, Delta); check their docs.

Config: in code or at submit time

Configuration: "Properties set directly on the SparkConf take the highest precedence, then those through --conf flags or --properties-file passed to spark-submit or spark-shell, then options in the spark-defaults.conf file." Executed with spark.sql.shuffle.partitions set to 3 in code, 7 by --conf, 11 in a properties file:

In code --conf Properties file Effective
3 7 11 3
— 7 11 7
— — 11 11

So a value hard-coded in the builder cannot be overridden by the operator at 2 a.m. And deploy-related properties (spark.driver.memory, spark.executor.instances) "may not be affected when setting programmatically through SparkConf in runtime": in client mode "the driver JVM has already started".

Review rule: resource and deploy settings live in the job definition. Code sets only what the logic depends on, such as the session time zone.

Testing PySpark: pyspark.testing

The 4.3.0 reference lists exactly two functions:

assertDataFrameEqual(actual, expected, checkRowOrder=False, rtol=1e-05, atol=1e-08, ignoreNullable=True,
    ignoreColumnOrder=False, ignoreColumnName=False, ignoreColumnType=False, maxErrors=None,
    showOnlyDiff=False, includeDiffRows=False)
assertSchemaEqual(actual, expected, ignoreNullable=True, ignoreColumnOrder=False, ignoreColumnName=False)

The testing guide calls them "standalone, meaning they can be compatible with any test framework or CI test pipeline". Executed against a latest_per_order transformation (newest row per order_id):

from pyspark.testing import assertDataFrameEqual, assertSchemaEqual
assertDataFrameEqual(latest_per_order(src), expected)    # passes; row order ignored by default
assertDataFrameEqual(latest_per_order(src), wrong)       # raises PySparkAssertionError:
[DIFFERENT_ROWS] Results do not match: ( 50.00000 % )
*** actual ***
! Row(order_id='o1', updated_at='2026-11-03', amount=12)
  Row(order_id='o2', updated_at='2026-11-02', amount=7)

*** expected ***
! Row(order_id='o1', updated_at='2026-11-01', amount=10)
  Row(order_id='o2', updated_at='2026-11-02', amount=7)

assertSchemaEqual with amount expected as LongType failed with [DIFFERENT_SCHEMA] Schemas do not match. and a diff of IntegerType against LongType: the schema-contract test PS0 asks for.

⚠️ ignoreNullable=True is the default on both: a column that became nullable passes unless you set it to False.

⚠️ Trap I hit: with pandas 3.1.1 installed, assertDataFrameEqual died with an ImportError from pyspark.pandas. The install page lists pandas >=2.2.0,<3.0.0; with 2.3.3 it ran. Pin test dependencies.

Testing Scala Spark: ScalaTest

ScalaTest is at 3.2.20 (verified 2026-11-22). In the FunSuite style "tests are function values"; === gives messages like "1 did not equal 2". BeforeAndAfterAll supplies afterAll.

object OrderTransforms {
  def latestPerOrder(df: DataFrame): DataFrame = {
    val w = Window.partitionBy("order_id").orderBy(col("updated_at").desc)
    df.withColumn("rn", row_number().over(w)).where(col("rn") === 1).drop("rn")
  }
}

class OrderTransformsSuite extends AnyFunSuite with BeforeAndAfterAll {
  private lazy val spark: SparkSession = SparkSession.builder().
    master("local[2]").appName("order-transforms-test").
    config("spark.sql.shuffle.partitions", "2").
    config("spark.ui.enabled", "false").
    getOrCreate()

  override def afterAll(): Unit = spark.stop()

  test("latestPerOrder keeps the newest row for each order_id") {
    val s = spark
    import s.implicits._
    val src = Seq(("o1", "2026-11-01", 10), ("o1", "2026-11-03", 12), ("o2", "2026-11-02", 7)).
      toDF("order_id", "updated_at", "amount")
    val got = OrderTransforms.latestPerOrder(src).as[(String, String, Int)].collect().toSet
    assert(got === Set(("o1", "2026-11-03", 12), ("o2", "2026-11-02", 7)))
  }
}

How this was run: not through sbt (not installed). With its imports, I ran it in spark-shell with --packages org.scalatest:scalatest_2.13:3.2.20 and org.scalatest.run(new OrderTransformsSuite). It passed; an extra test asserting count() === 2L reported *** FAILED *** 1 did not equal 2.

Community helpers, as their READMEs state today: spark-testing-base shows "4.0.0_2.1.2" for "a project using Spark 4.0.0"; spark-fast-tests gives an install line "for Spark 3" (3.0.1).

⚠️ Neither README states support for Spark 4.3, and I could not verify either on it. The plain ScalaTest suite above has no such dependency.

Packaging and submitting

Submitting applications: "create an assembly jar (or 'uber' jar) containing your code and its dependencies... list Spark and Hadoop as provided dependencies; these need not be bundled since they are provided by the cluster manager at runtime."

Assembled from the quick start, the ScalaTest install page and the sbt-assembly README (latest release tag v2.5.0). Not executed.

// project/plugins.sbt
addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "2.5.0")

// build.sbt
scalaVersion := "2.13.18"
libraryDependencies += "org.apache.spark" %% "spark-sql" % "4.3.0" % "provided"
libraryDependencies += "org.scalatest" %% "scalatest" % "3.2.20" % "test"
assembly / mainClass := Some("com.example.Main")
ThisBuild / assemblyShadeRules := Seq(
  ShadeRule.rename("org.apache.commons.io.**" -> "shadeio.@1").inAll
)

The assembly task writes one jar under target/. When two jars carry the same path, the default MergeStrategy.deduplicate errors unless contents match; the README says to "fix that dependency graph" rather than reach for MergeStrategy.first. ShadeRule.rename renames a library's classes inside your jar and updates references to them.

The spark-submit flags a reviewer must be able to read:

Flag What the docs say
--class "The entry point for your application" (Scala/Java)
--master local[K], yarn, k8s://HOST:PORT, spark://HOST:PORT
--deploy-mode cluster or client, "default: client"
--conf "Arbitrary Spark configuration property in key=value format"
--jars Comma-separated; "included in the driver and executor classpaths"
--packages Maven coordinates; "All transitive dependencies will be handled"
--py-files .py, .zip or .egg "to be distributed with your application"

Client or cluster. In client mode "the driver is launched directly within the spark-submit process". On YARN, in cluster mode "the Spark driver runs inside an application master process which is managed by YARN on the cluster, and the client can go away after initiating the application". Scheduled jobs want cluster mode.

Python dependencies. --py-files ships your own modules, but per Python Package Management it "does not allow to add packages built as Wheels". For those, pack an environment with conda-pack or venv-pack and ship it with --archives.

Deploying on AWS: know what the runtime ships

Verified 2026-11-22 on docs.aws.amazon.com (pages in sources:):

Runtime Label Spark Scala Python
Open source — 4.3.0 2.13 3.11+
AWS runtime for Apache Spark emr-spark-8.2.0 (18 Nov 2026, LTS) 4.1.3-amzn-0 2.13.17 3.11, 3.13
Amazon EMR 7.x emr-7.14.0 3.5.8-amzn-0 2.12.18 3.9, 3.11
AWS Glue 6.0 (default for new jobs) 4.1.1 2.13.17 3.13
AWS Glue 5.1 3.5.6 2.12.18 3.11

The gap: none of these ships Spark 4.3.0. The newest is 4.1.3 on emr-spark-8.2.0; Glue 6.0 is 4.1.1. A feature that arrived in 4.2 or 4.3 cannot be promised on either. And the 7.x line is Scala 2.12, while Spark's docs require "the same version of Scala that Spark was compiled for".

⚠️ The AWS docs disagree with themselves. About Amazon EMR Releases gives the label form as emr-x.x.x and lists 7.14.0 as the latest 7.x release; its text never mentions an 8.x line. The AWS runtime for Apache Spark section of the same guide documents labels "in the form emr-spark-x.y.z", and the EMR Serverless list puts emr-spark-8.2.0 first. Read only the first page and you miss the Spark 4 runtime.

EMR Serverless. jobDriver takes sparkSubmit, used "to run Scala, Java, PySpark, and any other supported jobs". Copied from the docs, not executed:

aws emr-serverless start-job-run \
    --application-id application-id \
    --execution-role-arn job-role-arn \
    --job-driver '{
        "sparkSubmit": {
            "entryPoint": "s3://us-east-1.elasticmapreduce/emr-containers/samples/wordcount/scripts/wordcount.py",
            "entryPointArguments": ["s3://amzn-s3-demo-destination-bucket/wordcount_output"],
            "sparkSubmitParameters": "--conf spark.executor.cores=1 --conf spark.executor.memory=4g --conf spark.driver.cores=1 --conf spark.driver.memory=4g --conf spark.executor.instances=1"
        }
    }'

# the jar example differs only inside sparkSubmit:
#   "entryPoint": "/usr/lib/spark/examples/jars/spark-examples.jar",
#   "entryPointArguments": ["1"],
#   "sparkSubmitParameters": "--class org.apache.spark.examples.SparkPi --conf spark.executor.cores=4 ..."

For a jar, "specify the main entry class in the SparkSubmitParameters using the --class argument". EMR Serverless ranks "configuration that EMR Serverless provides when it creates SparkSession" above your --conf.

Glue. A job script "can be coded in Python or Scala"; "AWS Glue supports an extension of the PySpark Scala dialect". Parameters: --job-language ("either scala or python", default python), --class, --extra-jars, --extra-py-files. Tell a Scala engineer: Glue "compiles your Scala program on the server", and "you will not have good visibility into any problems that happen there".

CI shape

A generic shape, from what each tool documents.

Stage Scala Python
On PR — format sbt scalafmtCheckAll (scalafmt 3.11.5) ruff format --check exits 1 if a file would be reformatted (Ruff 0.17.6)
On PR — lint, compile sbt compile ruff check
On PR — unit tests sbt test (ScalaTest with sbt) on local[2] pytest on local[2]
On merge — build sbt assembly zip of modules, packed environment
On merge — deploy Versioned artifact to S3, then point the job definition at it Same

DE4 lesson 5 uses the same PR/merge split and covers the job definition and OIDC credentials.

What a lead does with this

Review feedback that teaches. "Don't use collect here" teaches obedience. "This collect loads every row into driver memory, and the API doc says small results only; use take(20) or write it out" teaches the mechanism. Name the mechanism, link the page, say what to do instead.

A definition of done for a Spark job, to adopt as a team rule:

  1. Tested: transformations have unit tests on a local session, including a schema assertion.
  2. Plan reviewed: someone other than the author read the explain output (module E7 of the sibling db-training repo).
  3. Idempotent re-run demonstrated: the job ran twice against the same input and the output matched.
  4. Alarmed: failure pages someone (DE4 lesson 4).
  5. Runtime version recorded: spark.version on the target, in the PR.

Check yourself

  1. A daily job writes mode("overwrite").partitionBy("dt") with default config. What happens to yesterday's partition, and what is the one-line fix?
  2. An operator passes --conf spark.sql.shuffle.partitions=400 and the job still uses 8. Why?
  3. A test passes with assertDataFrameEqual, yet production breaks because a column became nullable. What did the test miss?
  4. A teammate wants a DataFrame function added in Spark 4.3 for a Glue job. What do you tell them?
  5. A PR adds 40 columns with withColumn in a for loop. What do you write in the review?
Answers
  1. It is deleted: spark.sql.sources.partitionOverwriteMode defaults to STATIC. Set .option("partitionOverwriteMode", "dynamic") on the write, or the session config.
  2. The code sets it on the builder, and SparkConf properties "take the highest precedence", above --conf. Remove it from code.
  3. ignoreNullable defaults to True. Assert the schema with ignoreNullable=False.
  4. Not yet: the newest Glue version, 6.0, ships Spark 4.1.1. And Glue 5.1 is Scala 2.12, so check the runtime before promising a feature or shipping a jar.
  5. Cite the API note: each call "introduces a projection internally" and looping "can generate big plans". Ask for one select or one withColumns with a dict, and link the page.

Teaching this section

← PreviousPerformance tuning as a lead — an ordered triage, not a bag of configsNext →Staying current — the Spark 4 line and what to migrate