AWS Training
Modules Listen Certification

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

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

Performance tuning as a lead — an ordered triage, not a bag of configs

Why this matters

A junior brings you a slow job and a diff that sets six configs. Some were already the default, and nobody recorded the runtime before. That is a process problem, not a knowledge problem.

What the posting is really asking. "Conduct ... performance optimization activities", "troubleshoot and debug technical issues" and "performance tuning and optimization techniques" mean you can run an investigation that converges: look at evidence in a fixed order, name the one cause, change one thing, and show the before and after. This lesson is that order and that evidence.

Mechanisms are elsewhere. Shuffle, join selection, AQE and the memory model: module E7 of the sibling db-training repo. The PySpark skew fixes (filter the junk key, broadcast, salt): PS0 lesson 4. Every default below is from the Spark 4.3.0 docs at spark.apache.org/docs/latest (page titles read "Spark 4.3.0 Documentation"), verified 2026-11-22. Every sample was run on 4.3.0 in local mode.

The triage, in order

Tab and column names are the ones the Web UI guide uses (verified 2026-11-22). Each step is cheaper than the next and rules out a class of cause.

# Question Where to look What it means → where it points
1 Slow, or just waiting? Stage detail → Scheduler delay ("the time the task waits to be scheduled"); Jobs tab → Event timeline (executors added, removed) Tasks queueing for slots is a capacity problem. No query tuning fixes it → cluster size, spark.dynamicAllocation.*
2 Which job, stage, tasks? Jobs tab → job detail → stages with duration, Input, Output, Shuffle read, Shuffle write; link to the Associated SQL Query One stage usually owns the time. Everything after is about that stage
3 Are the tasks even? Stage detail → Summary metrics for Duration and Shuffle Read Size / Records: compare max with median Max far above median is skew. More executors will not help → AQE skew settings, then the PS0 fixes
4 Is the shuffle too big for memory? Same table: Shuffle spill (memory), Shuffle spill (disk), Shuffle Write Time, Shuffle Read Fetch Wait Time Spill on every task: partitions too large → more shuffle partitions. Spill on one: back to step 3
5 Is the JVM thrashing? GC time in the same table; Executors tab, with Thread Dump, Heap Histogram and Flame Graph links High GC share of task time → memory per task, caching, object-heavy code
6 Is the plan right? SQL tab → execution detail → plan graph with per-node metrics; "Details" expands the parsed, analyzed, optimized and physical plans Scan: PartitionFilters and PushedFilters. Join: which strategy. Count the Exchange nodes
7 Is the code the problem? SQL tab query listing (one entry per action); Storage tab UDFs, collect, one lineage recomputed by several actions with nothing cached

⚠️ The Web UI guide names the metrics but gives no ratio of GC time or max-to-median that counts as "bad". Any threshold you hear is folklore unless cited. The one documented ratio is AQE's: 5.0 × the median, below.

The evidence tools

explain. SQL syntax is EXPLAIN [ EXTENDED | CODEGEN | COST | FORMATTED ] statement (EXPLAIN); the DataFrame method takes mode= simple, extended, codegen, cost or formatted (PySpark API, verified 2026-11-22). Ask a junior for formatted: an outline, then one block per node. Executed on 4.3.0 against a Parquet table partitioned by dt:

spark.sql("""SELECT c.tier, sum(o.amount) AS total
             FROM orders o JOIN customers c ON o.customer_id = c.customer_id
             WHERE o.dt = '2026-11-03' AND o.amount > 50 GROUP BY c.tier""").explain(mode="formatted")
+- BroadcastHashJoin Inner BuildRight (7)
...
(1) Scan parquet
PartitionFilters: [isnotnull(dt#11), (dt#11 = 2026-11-03)]
PushedFilters: [IsNotNull(amount), GreaterThan(amount,50.0), IsNotNull(customer_id)]
ReadSchema: struct<customer_id:bigint,amount:double>

Partition pruned, predicate pushed to Parquet, two columns read. An empty PartitionFilters: [] on a date-partitioned table is a finding by itself.

EXPLAIN COST on the same query printed Statistics(sizeInBytes=3.0 GiB) for a join of an 838.9 KiB relation with a 5.5 KiB one, with no statistics collected. The SQL tuning page names ANALYZE TABLE as what populates catalog statistics.

⚠️ Observed on 4.3.0: with AQE on (the default), EXPLAIN CODEGEN returned Found 0 WholeStageCodegen subtrees. With spark.sql.adaptive.enabled=false the same statement returned Found 2 WholeStageCodegen subtrees. and 479 lines. Likewise explain() before an action prints AdaptiveSparkPlan isFinalPlan=false; after the action the same DataFrame's plan read isFinalPlan=true. The plan you explain before running is not the plan that ran. The final plan is on the SQL tab. ⚠️ The EXPLAIN reference's example output shows no AdaptiveSparkPlan node, so it does not match what 4.3.0 prints.

Event logs and the History Server. The live UI dies with the application. From monitoring and the configuration reference (verified 2026-11-22):

Key 4.3.0 default Note
spark.eventLog.enabled false Nothing is kept unless you set it
spark.eventLog.dir file:///tmp/spark-events Point at shared storage
spark.eventLog.rolling.enabled true My run wrote eventlog_v2_<app-id>/events_1_<app-id>.zstd
spark.history.fs.logDirectory file:/tmp/spark-events Must match the writers' directory
spark.history.ui.port 18080 Started with ./sbin/start-history-server.sh

⚠️ History Server compaction of rolling logs is documented as "LOSSY" and "may not be completely stable". Leave spark.history.fs.eventLog.rolling.maxFilesToRetain at its default.

REST API. The same numbers as JSON, "mounted at /api/v1": port 18080 on the History Server, 4040 on a running driver. The endpoint that answers step 3, used for the skew table below:

/applications/[app-id]/stages/[stage-id]/[stage-attempt-id]/taskSummary?quantiles=0.5,1.0

Also documented: .../taskList?sortBy=-runtime, /applications/[app-id]/sql, and /allexecutors (active and dead). Task metric names include jvmGCTime, diskBytesSpilled and peakExecutionMemory.

Executor metrics. Sent with each heartbeat, exposed at /applications/[app-id]/executors: totalGCTime, JVMHeapMemory, MajorGCTime. The ProcessTree* metrics, including ProcessTreePythonRSSMemory, report 0 unless spark.executor.processTreeMetrics.enabled=true (default false) and a /proc filesystem exists.

The knobs, with 4.3.0 defaults

Copied from the configuration reference and SQL tuning page, verified 2026-11-22.

Key Default Triage step
spark.sql.shuffle.partitions 200 4
spark.sql.adaptive.enabled true ("enabled by default since Apache Spark 3.2.0") 3, 4, 6
spark.sql.adaptive.coalescePartitions.enabled true 4
spark.sql.adaptive.coalescePartitions.parallelismFirst true 4
spark.sql.adaptive.advisoryPartitionSizeInBytes 64 MB 3, 4
spark.sql.adaptive.skewJoin.enabled true 3
spark.sql.adaptive.skewJoin.skewedPartitionFactor 5.0 3
spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes 256MB 3
spark.sql.autoBroadcastJoinThreshold 10485760 (10 MB); -1 disables 6
spark.sql.files.maxPartitionBytes 134217728 (128 MB) 6
spark.executor.memory 1g 5
spark.executor.memoryOverhead executorMemory * spark.executor.memoryOverheadFactor, minimum spark.executor.minMemoryOverhead (384m) failures
spark.executor.memoryOverheadFactor 0.10; 0.40 for Kubernetes non-JVM jobs failures
spark.memory.fraction 0.6 of (heap − 300MB) 5
spark.memory.storageFraction 0.5 5
spark.serializer org.apache.spark.serializer.JavaSerializer 5
spark.dynamicAllocation.enabled false 1
spark.speculation false (multiplier 3, quantile 0.9) 3

In review:

Doc versus runtime. spark.conf.get on 4.3.0 returned 200, true, 67108864b, 5.0, 268435456b, 10485760b and 134217728b for the SQL keys: all agree with the docs. For unset core keys (spark.executor.memory, spark.serializer, spark.speculation) it raised SQL_CONF_NOT_FOUND, so those defaults were not cross-checked. What an application set is on the Environment tab → Spark Properties.

⚠️ The docs disagree. The SQL tuning page says skewJoin.enabled handles "skew in sort-merge join"; the configuration reference says "skew in shuffled join (sort-merge and shuffled hash)". I reproduced only sort-merge.

Hints

From the hints reference (verified 2026-11-22). Join hints: BROADCAST (aliases BROADCASTJOIN, MAPJOIN), MERGE (SHUFFLE_MERGE, MERGEJOIN), SHUFFLE_HASH, SHUFFLE_REPLICATE_NL. When both sides carry different hints, "Spark prioritizes hints in the following order: BROADCAST over MERGE over SHUFFLE_HASH over SHUFFLE_REPLICATE_NL", and Spark "is not guaranteed to use the join strategy suggested by the hint". Executed on 4.3.0: /*+ BROADCAST(c), MERGE(o) */ planned BroadcastHashJoin; /*+ SHUFFLE_HASH(c), MERGE(o) */ planned SortMergeJoin. Both match.

Partitioning hints: COALESCE, REPARTITION, REPARTITION_BY_RANGE, REBALANCE, REBALANCE_BY_SIZE. The first three are "equivalent to coalesce, repartition, and repartitionByRange Dataset APIs"; the REBALANCE pair "can only be used as hints" and are "ignored if AQE is not enabled". The docs call REBALANCE "useful when you need to write the result of this query to a table". /*+ REBALANCE(dt) */ planned Exchange hashpartitioning(dt, 200), REBALANCE_PARTITIONS_BY_COL.

One skew case, reproduced

local[4], Spark 4.3.0. Ninety percent of fact rows share customer_id = 0; broadcast is disabled so the join must shuffle. Abridged from the script that ran:

fact = (spark.range(N)
        .withColumn("customer_id", F.when(F.col("id") % 10 < 9, F.lit(0)).otherwise(F.col("id") % 9999 + 1))
        .withColumn("pad", F.sha2(F.col("id").cast("string"), 256)))
dim = spark.range(10_000).withColumnRenamed("id", "customer_id")   # plus a name column
# spark.sql.autoBroadcastJoinThreshold = -1, spark.eventLog.enabled = true
fact.join(dim, "customer_id").write.format("noop").mode("overwrite").save()

Numbers from taskSummary for the join stage; plan text from the /sql endpoint.

Run Join tasks Shuffle read per task, median / max Task duration, median / max Final plan
AQE off, 3M rows 200 110 KB / 185 MB 9 ms / 1,276 ms SortMergeJoin, plain Exchange
AQE on, 3M, defaults 2 max 185 MB max 838 ms AQEShuffleRead ... coalesced; no skew handling
AQE off, 5M rows 200 182 KB / 308 MB 5 ms / 2,273 ms SortMergeJoin
AQE on, 5M, defaults 6 77 MB / 77 MB 1,230 ms / 1,248 ms SortMergeJoin(skew=true); AQEShuffleRead ... coalesced and skewed

What this shows, honestly:

Failure signatures

Symptom First check Likely cause
Job aborted due to stage failure: Total size of serialized results of 1 tasks (1289.6 KiB) is bigger than spark.driver.maxResultSize (1024.0 KiB) (reproduced with the limit at 1m; default 1g) Which action: collect, toPandas Results pulled to the driver. Raising the limit "may cause out-of-memory errors in driver"
OutOfMemoryError in a task Step 3 and 4 for that stage Tuning guide: "the working set of one of your tasks ... was too large"; its fix is "increase the level of parallelism"
"Memory Overhead Exceeded" (the configuration reference's words, for non-JVM tasks) ProcessTree* metrics; spark.executor.pyspark.memory (default not set) Python outside the heap. The container limit is the sum of memoryOverhead, executor.memory, memory.offHeap.size and pyspark.memory
Fetch failure, then the previous stage reruns Executors tab and event timeline: did an executor disappear? Fetches retry spark.shuffle.io.maxRetries (3) × retryWait (5s), then "the task will fail with fetch failure". The retry exists for "long GC pauses or transient network connectivity issues"
Stage attempts climbing Failure reason on the Stages tab ("Only failed stages show the failure reason") spark.stage.maxConsecutiveAttempts is 4; spark.task.maxFailures is 4

⚠️ Not verified. The exact text of the YARN "container killed ... exceeding memory limits" message and of an "executor lost" log line appears on none of the pages I fetched. Copy them from your own logs (yarn logs -applicationId <app ID>), not from memory. Nor did I find a doc sentence describing a driver OOM from an oversized broadcast.

What a lead does with this

Check yourself

  1. AQE and skewJoin.enabled are both true, yet one task reads 185 MB while the median reads 110 KB. Why was it not split?
  2. You run df.explain() and see a sort-merge join. Why is that not proof of what executed?
  3. Which default means a slow job from last night usually has no UI?
  4. One side is hinted MERGE, the other BROADCAST. What does Spark plan?
  5. Every task in a stage shows disk spill. One task in another stage shows disk spill. Same fix?
Answers
  1. A partition is skewed only if it exceeds 5.0 × the median and skewedPartitionThresholdInBytes, default 256 MB. 185 MB fails the second test. Reproduced above: the plan showed coalesced and no skew=true.
  2. With AQE on it prints AdaptiveSparkPlan isFinalPlan=false. AQE can re-plan at runtime. The final plan is on the SQL tab, or in explain after an action.
  3. spark.eventLog.enabled is false, and the live UI lasts only as long as the application.
  4. A broadcast join. The documented order is BROADCAST over MERGE over SHUFFLE_HASH over SHUFFLE_REPLICATE_NL. Executed: BroadcastHashJoin.
  5. No. Spill everywhere means partitions are uniformly too large: raise the shuffle partition count. Spill on one task is skew: fix the distribution.

Teaching this section

← PreviousScala or Python — choosing per workload and running a mixed teamNext →Code review, testing, and deployment for Spark