AWS Training
Modules Listen Certification

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

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

Scala or Python — choosing per workload and running a mixed team

Why this matters

A team with both languages asks its lead the same question every quarter: "should this be Scala?" The wrong answers are "always, it's faster" and "never, nobody knows it". The right answer names the workload and the mechanism.

What the posting is really asking. "Lead technical teams in the design and implementation of solutions using Apache Spark, Scala, and Python" does not mean "be fluent in both". It means you decide which language a pipeline is written in, say why in one sentence, and keep a two-language codebase from becoming two teams. "Stay updated with the latest trends" applies too: the facts under this decision moved in Spark 4.2 and 4.3, and an answer learned on Spark 3 is partly wrong.

Everything below is from the Spark 4.3.0 docs (overview, verified 2026-11-22: "Spark runs on Java 17/21/25, Scala 2.13, Python 3.11+") and run on 4.3.0.

What is identical: the plan

The SQL guide (verified 2026-11-22) says it outright: "the same execution engine is used, independent of which API/language you are using to express the computation." Two minutes shows it.

# PySpark
df = (spark.range(1_000_000)
        .withColumn("k", F.col("id") % 10)
        .where(F.col("id") > 100)
        .groupBy("k")
        .agg(F.sum("id").alias("total"), F.avg("id").alias("mean")))
df.explain()

The Scala version is the same chain in spark-shell (col, sum, avg from org.apache.spark.sql.functions). Both printed this, and diff on the two outputs returned nothing:

AdaptiveSparkPlan isFinalPlan=false
+- HashAggregate(keys=[k#1L], functions=[sum(id#0L), avg(id#0L)])
   +- Exchange hashpartitioning(k#1L, 200), ENSURE_REQUIREMENTS, [plan_id=19]
      +- HashAggregate(keys=[k#1L], functions=[partial_sum(id#0L), partial_avg(id#0L)])
         +- Project [id#0L, (id#0L % 10) AS k#1L]
            +- Filter (id#0L > 100)
               +- Range (0, 1000000, step=1, splits=2)

Same operators, same order, same expression IDs. The language is the syntax you build the plan with; it is not in the plan. "Rewrite it in Scala for speed" is a non-argument for any job that is DataFrame operations and built-in functions end to end.

Where the languages genuinely differ

Area Scala / Java Python Source (verified 2026-11-22)
Typed Dataset[T] Yes No — "Python does not have the support for the Dataset API" SQL guide
Where a UDF runs In the executor JVM In a separate Python worker; data is serialised across Arrow in PySpark
Vectorised UDFs n/a pandas_udf; arrow_udf over pyarrow.Array, "Added in version 4.1.0" arrow_udf
Table functions in user code Not checked here Python UDTF: "Spark 3.5 introduces the Python user-defined table function" Python UDTFs
Custom data source Data Source V2: "a set of Java interfaces in the org.apache.spark.sql.connector package" Python Data Source API, "introduced in Spark 4.0" — "a wrapper for lightweight connectors written entirely in Python" DSV2, Python Data Source
Arbitrary stateful streaming transformWithState; legacy mapGroupsWithState / flatMapGroupsWithState transformWithState (Row), transformWithStateInPandas; legacy applyInPandasWithState transformWithState
transformWithState in Real-time Mode Yes, from 4.3.0 No Real-time Mode
Optimizer / parser extensions SparkSessionExtensions: analyzer rules, optimizer rules, planning strategies, custom parser No Python equivalent in the pages fetched ScalaDoc
Shipping dependencies One assembly jar --py-files, or a packed environment Submitting applications

Streaming. "TransformWithState is available in Scala, Java and Python," so custom stateful logic alone is no longer a reason to choose Scala. Real-time Mode is: "Starting in Spark 4.3.0, the Scala and Java APIs can also run with a Real-time trigger. The PySpark transformWithState and transformWithStateInPandas APIs are not supported in Real-time Mode."

⚠️ The PySpark grouping reference lists transformWithStateInPandas but not the Row-based transformWithState the guide describes. On 4.3.0, hasattr(GroupedData, "transformWithState") returned True — the page is behind the code.

Extensions. The ScalaDoc warns: "We make NO guarantee about the stability regarding binary compatibility and source compatibility of methods here." A custom optimizer rule is a Scala commitment and a per-upgrade maintenance commitment.

Ecosystem is the row the docs cannot settle. ⚠️ I verified no claim about which library ecosystem is "bigger" — decide from the libraries your pipeline actually needs.

The UDF row, with current defaults

PS0 lesson 1 and lesson 3 teach the mechanism: a Python UDF sends rows from the JVM to a Python worker and back, Arrow makes the transfer columnar, and a pandas UDF makes the computation columnar too. One thing changed since those were verified:

"In Spark 4.2, regular Python UDFs are Arrow-optimized by default. The configuration spark.sql.execution.pythonUDF.arrow.enabled now defaults to true." — Upgrading PySpark, verified 2026-11-22

The configuration page agrees (spark.sql.execution.pythonUDF.arrow.enabled = true, spark.sql.execution.pythonUDTF.arrow.enabled = true), and spark.conf.get on 4.3.0 returned true for both. Per-function override: udf(..., useArrow=False). The udf reference is careful about what this is: Arrow-optimized Python UDFs "still process data row-by-row with regular Python types, but use Arrow for more efficient data transfer".

⚠️ The docs contradict themselves. The Arrow tutorial still labels a bare @udf(returnType='int') "A default, pickled Python UDF" a few lines above saying Arrow is the default since 4.2. Trust the migration guide and the config table.

⚠️ The switch changes type coercion, not just speed — the same tutorial says pickled UDFs rely "on None as a fallback for type mismatches", so a UDF can behave differently after an upgrade. Glue and EMR ship their own Spark versions — 4.1.x at best on 2026-11-22, per lesson 5, which is before the 4.2 default change: read the default on the runtime you deploy to (PS0 lesson 5).

One measured run

This is one run on one laptop (Apple M3 Max, local[4], Spark 4.3.0, Python 3.14, pandas 3.1.1, pyarrow 26.0.1). It is not a benchmark. PySpark itself warned that it "does not yet fully support pandas >= 3.0.0". The function is trivial arithmetic, (x * 3 + 7) % 1000, over 10 million rows from spark.range, summed. Median of five runs after a warm-up:

Variant Physical operator in explain() Median
(a) Built-in column expression Project [(((id * 3) + 7) % 1000)] 0.05 s
SQL function (CREATE FUNCTION … RETURN) identical to (a) — inlined 0.03 s
(b) Scala UDF from a jar, called from PySpark Project [score_jvm(id)] 0.05 s
(b) Scala udf((x: Long) => …) in spark-shell Project [UDF(id)] 0.04 s
(c) Python UDF, useArrow=False BatchEvalPython 0.65 s
(d) Python UDF, default (Arrow-optimized) ArrowEvalPython 0.32 s
(e) pandas UDF ArrowEvalPython 0.21 s
arrow_udf over pyarrow.Array ArrowEvalPython 0.23 s

Read the ordering, not the numbers. Everything that stays in the JVM lands together; the differences between those rows are noise. Everything that crosses to a Python worker is several times slower, improving as transfer becomes columnar (c → d) and then as the computation does (d → e). With strings, wide rows, or a heavier function, the ratios will differ.

⚠️ A trap I hit while measuring. Calling collect() again on the same DataFrame object took 0.02 s for every variant. The UI's REST API showed why: on the second run the stage that evaluates the UDF had status SKIPPED. Build a new DataFrame for each timed run.

Spark Connect

Spark Connect (verified 2026-11-22) is "a decoupled client-server architecture that allows remote connectivity to Spark clusters using the DataFrame API and unresolved logical plans as the protocol". The client encodes plans as protocol buffers, sends them over gRPC, and gets results back "as Apache Arrow-encoded row batches". It "supports PySpark and Scala applications". The documented differences from a classic application:

The switch is spark.api.mode=connect (application development page). For the language decision: the client becomes a thin library (pyspark-client==4.3.0, or the spark-connect-client-jvm artifact), both languages lose the escape hatches (_jdf, SparkContext, RDDs), and code that stayed on the DataFrame API ports cleanly. Not executed here: the scratch environment has no gRPC client.

Mixed-team patterns

1. Call JVM code from PySpark. spark.udf.registerJavaFunction(name, javaClassName, returnType=None) exists in 4.3.0 ("Changed in version 3.4.0: Supports Spark Connect"). A Scala class implementing Spark's Java UDF1 interface qualifies. Compiled with the Scala 2.13.18 compiler into a jar and run:

package stl.udfs
import org.apache.spark.sql.api.java.UDF1

class Score extends UDF1[java.lang.Long, java.lang.Long] {
  override def call(x: java.lang.Long): java.lang.Long =
    if (x == null) null else java.lang.Long.valueOf((x * 3 + 7) % 1000)
}
spark = SparkSession.builder.config("spark.jars", "stl-udfs.jar").getOrCreate()
spark.udf.registerJavaFunction("score_jvm", "stl.udfs.Score", LongType())
spark.range(3).selectExpr("id", "score_jvm(id) AS score").show()   # 7, 10, 13

That is row (b) in the table: JVM speed, Python pipeline.

⚠️ The catalog form, CREATE FUNCTION name AS class_name USING JAR …, documents different base classes (Hive's UDF / GenericUDF family, or UserDefinedAggregateFunction). It does not list UDF1; I did not test Score with it.

2. Share logic as a SQL function. CREATE FUNCTION (SQL): the body "can be defined either a SQL expression or a query", temporary or persisted. One file, read and executed by both languages:

CREATE OR REPLACE TEMPORARY FUNCTION is_priority(amount BIGINT) RETURNS BOOLEAN RETURN amount >= 900

Run from PySpark and from spark-shell against the same Parquet file, where("is_priority(amount)") gave the same plan in both, with the predicate pushed into the scan:

SQL function : PushedFilters: [IsNotNull(id), GreaterThanOrEqual(id,900)]
Python UDF   : PushedFilters: []      (ArrowEvalPython above the scan)
Scala UDF    : PushedFilters: []      (Filter (score_jvm(id) >= 900))

⚠️ Read the third line again. A Scala UDF is fast and still opaque. It avoids the Python worker; it does not give the optimizer its predicate back. Only the SQL function is inlined. One documented limit: a persistent SQL function "cannot reference temporary views, temporary functions, or session variables".

3. Shipping the code. From Submitting applications: for the JVM, "create an assembly jar (or 'uber' jar) containing your code and its dependencies", listing Spark and Hadoop as provided. For Python, --py-files adds .py, .zip or .egg files — but Python Package Management says it "does not allow to add packages built as Wheels and therefore does not allow to include dependencies with native code". For pandas or pyarrow on executors the documented options are conda-pack or venv-pack (shipped with --archives), PEX (shipped with --files), or uv run.

⚠️ venv-pack "packs Python interpreter as a symbolic link" and a .pex file "does not include a Python interpreter", so both need the same interpreter on every node. A JVM team ships one artifact; a Python team ships an artifact plus an interpreter contract with the cluster. That cost of choosing Python is not performance.

The decision table

Workload Language Reason
Batch ETL expressible as DataFrame/SQL Whichever the maintainers know Identical plan (shown above)
Row-wise rule shared by both languages SQL function Inlined; pushdown survives
Hot row-wise logic no built-in covers Scala UDF in a jar, called from either side Stays in the JVM; opaque either way
Logic that needs pandas, NumPy or a model Python, pandas UDF or mapInPandas The library is the reason; pay the crossing in batches
Stateful streaming, micro-batch Either transformWithState exists in Scala, Java and Python
Custom stateful logic in Real-time Mode Scala / Java PySpark transformWithState not supported there in 4.3.0
Connector with pushdown or catalog integration Java / Scala DSV2 mix-ins are Java interfaces
Optimizer rule, custom parser Scala SparkSessionExtensions only
Typed domain model, compile-time field checks Scala Dataset[T] No Python Dataset API (lesson 2)

"It depends, and here's what I'd ask." For any pipeline not forced by a row above:

  1. Who is on call for it in a year, and what do they read fluently?
  2. What does the existing codebase use? A second language is a second build and test harness.
  3. Does any step need a library that exists on only one side?
  4. What is the latency target — batch, micro-batch, or Real-time Mode?
  5. Is any time actually spent in a UDF? If the plan is all built-ins, language is not the bottleneck (lesson 4).

What a lead does with this

Check yourself

  1. A colleague wants to port an all-joins-and-aggregations PySpark job to Scala "for performance". What do you show?
  2. In Spark 4.3.0, what does @udf(returnType="long") do by default, and what does it not do?
  3. You replace a Python UDF in a filter with a Scala UDF. What improves and what doesn't?
  4. Name one workload where Spark 4.3.0 forces the JVM.
  5. Your PySpark job needs pyarrow on the executors. Why is --py-files not enough?
  6. A library calls df._jdf. What happens under Spark Connect, per the docs?
Answers
  1. The plan is the same: "the same execution engine is used, independent of which API/language", and explain() on equivalent code printed identical physical plans. Porting changes syntax, not execution. Ask where the time is going first.
  2. It is Arrow-optimized: spark.sql.execution.pythonUDF.arrow.enabled defaults to true since 4.2. It still runs "row-by-row with regular Python types" — not vectorised, and still opaque to the optimizer.
  3. The Python worker round trip goes away. Pushdown does not come back: the Scala UDF filter still showed PushedFilters: []. Only the SQL function was pushed to the scan.
  4. Any of: transformWithState in Real-time Mode ("currently supports only the JVM (Scala/Java) transformWithState implementation"); a Data Source V2 connector; a SparkSessionExtensions rule; typed Dataset[T].
  5. --py-files ships .py, .zip and .egg files; it "does not allow to include dependencies with native code". Use conda-pack or venv-pack with --archives, or PEX with --files.
  6. It is "not possible": under Connect "the client does not use Py4J", so there is no _jdf.

Teaching this section

← PreviousDatasets, encoders, and closures — the Scala API on SparkNext →Performance tuning as a lead — an ordered triage, not a bag of configs