The previous lesson ended with Spark as the main player in a replacement: it took over from MapReduce, from Pig and from Hive as an engine. It managed this because it is not just a faster engine but a unified platform: the same core serves for batch, SQL, streaming, machine learning and graphs, it can be deployed on several cluster managers and it connects to almost any storage system.
You have been using Spark since Module 2, but always the same pieces: DataFrames, Spark SQL, a little Structured Streaming and MLlib. This lesson draws the complete map so that you know what else there is, where what you already know fits in, and what you will need on the day your script leaves your laptop. And it ends with a question that a good professional should be able to answer without hesitation: when not to use Spark.
Map of the ecosystem
flowchart TB
subgraph Languages[Language APIs]
PY[Python]
SQ[SQL]
SC[Scala / Java]
R[R]
end
subgraph Libraries[Libraries]
SS[Structured<br/>Streaming]
ML[MLlib]
GR[GraphX /<br/>GraphFrames]
PS[pandas API<br/>on Spark]
end
SQL[Spark SQL and DataFrames<br/>Catalyst + Tungsten]
CORE[Spark Core<br/>RDD, task scheduler, shuffle, memory]
subgraph Managers[Cluster managers]
ST[Standalone]
YA[YARN]
K8[Kubernetes]
end
subgraph Data[Storage, via connectors]
OB[Objects / HDFS<br/>Parquet, Delta, Iceberg]
KA[Kafka]
BD[JDBC, Cassandra,<br/>MongoDB, Elasticsearch]
end
Languages --> Libraries
Languages --> SQL
Libraries --> SQL
SQL --> CORE
CORE --> Managers
CORE --> Data
What you have already seen, and where:
| Piece | Lesson | What you saw |
|---|---|---|
| Spark Core and RDD | 03-02 | Driver, executors, DAG, transformations and actions |
| DataFrames and Spark SQL | 03-02, 03-03 | Schemas, joins, aggregations, windows |
| Performance | 03-04 | explain, shuffle, AQE, cache |
| Structured Streaming | 03-05 | Windows, watermark, checkpoint |
| MLlib | 04-03 | Pipelines, K-Means, classification |
One detail in the diagram matters more than the rest: all the modern libraries go through Spark SQL. Structured Streaming, MLlib and the pandas API are built on DataFrames, so any improvement to the optimiser benefits all of them. Spark Core is still underneath, but you almost never touch it directly.
Inside the engine: Catalyst and Tungsten
In lesson 03-04 you read plans with explain() and saw that Spark reorders your query. Two components do that work.
Catalyst is the optimiser: it decides which operations to run and in what order. It works in four phases, which you can see together with df.explain("extended"):
| Phase | What it does | Example with events.where("event_type = 'purchase'").select("date") |
|---|---|---|
| 1. Analysis | Resolves table and column names against the catalogue and checks types | Fails here if you write evnt_type |
| 2. Logical optimisation | Applies rules that do not depend on the data: predicate pushdown, column pruning, expression simplification | Decides to read only two columns from the Parquet files |
| 3. Physical planning | Generates alternative plans and chooses by cost: which type of join, where to put the shuffle | Would choose a broadcast join if there were a small table |
| 4. Code generation | Turns the plan into Java code compiled on the fly | A compact loop instead of a chain of calls |
AQE, which you already know, adds a fifth opportunity: re-optimising during execution with real statistics.
Tungsten is the execution engine: it decides how each operation is carried out on the machine. Its three ideas:
- Its own binary in-memory format. Rows are not stored as Java objects, which take up a lot of space and overwhelm the garbage collector, but as compact bytes that Spark manages itself.
- Code generation for whole stages (whole-stage code generation). This is the asterisk with a number,
*(1), that appears in physical plans: all the operators in the stage have been fused into a single function. - Vectorised execution when reading columnar formats: Parquet is read in batches of values, not row by row.
You already know the practical consequence, but now you can explain it: a Python UDF is a black box for both. Catalyst cannot see inside it to optimise it, and Tungsten has to take the data out of its format to hand it to Python. That is why the built-in functions in pyspark.sql.functions are always the first choice (lesson 03-03).
And another one: with DataFrames, the language has almost no effect on performance. Python, Scala and SQL produce the same plan, which the same engine runs.
Structured Streaming and MLlib: where they stand
Structured Streaming (lesson 03-05) is Spark's current streaming engine. There was an earlier one, Spark Streaming, based on RDDs and on objects called DStreams: it is obsolete and receives no improvements. If you come across code with StreamingContext or DStream, it is legacy; new code is written with readStream and writeStream.
MLlib (lesson 04-03) has a similar history. There are two packages:
pyspark.ml: the DataFrame-based API, withPipeline, which is the one you used. It is the current one.pyspark.mllib: the original RDD-based API, in maintenance mode. Do not use it in new code.
The pattern repeats across the whole ecosystem: what was built on RDDs has been giving way to what is built on DataFrames. It works as a rule of thumb for judging how old any tutorial is.
Graph processing: GraphX and GraphFrames
A graph represents relationships: vertices (things) joined by edges (relationships). In lesson 02-03 a NovaMarket case came up: products "bought together". The vertices are products; there is an edge between two products if they appear in the same order, with a weight equal to the number of orders in which they coincide.
Spark offers two libraries:
| GraphX | GraphFrames | |
|---|---|---|
| Foundation | RDD | DataFrames |
| Languages | Scala and Java (no Python) | Python, Scala and Java |
| Distribution | Included in Spark | External package, added with --packages |
| Status | In maintenance, not evolving | Independent project; check its activity and compatibility with your Spark version |
Before installing anything, it is worth knowing that building the graph does not require any library: it is a self-join. Create ~/novamarket/bought_together.py:
from pathlib import Path
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
LAKE = Path.home() / "novamarket" / "lake"
spark = SparkSession.builder.master("local[*]").appName("bought_together").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
lines = spark.read.parquet(str(LAKE / "silver" / "order_lines")).select("order_id", "product_id")
# 1. Edges: one pair of products for each order in which they coincide
a = lines.alias("a")
b = lines.alias("b")
edges = (
a.join(b, on="order_id")
.where(F.col("a.product_id") < F.col("b.product_id"))
.groupBy(F.col("a.product_id").alias("source"), F.col("b.product_id").alias("target"))
.agg(F.countDistinct("order_id").alias("orders_together"))
)
edges.cache()
print("Products (vertices):", lines.select("product_id").distinct().count())
print("Distinct pairs (edges):", edges.count())
edges.orderBy(F.desc("orders_together"), "source", "target").show(5)
# 2. Degree: how many distinct products each one has been bought with
degree = (
edges.select(F.col("source").alias("product_id"))
.union(edges.select(F.col("target").alias("product_id")))
.groupBy("product_id").count().withColumnRenamed("count", "degree")
)
degree.agg(F.min("degree").alias("minimum"), F.round(F.avg("degree"), 1).alias("mean"),
F.max("degree").alias("maximum")).show()
spark.stop()- Block 1. The lines table is joined with itself on
order_id: each order generates every pair of its products. The conditiona.product_id < b.product_idavoids pairing a product with itself and counting each pair twice (25-91 and 91-25). Then it counts how many orders each pair appears in. - Block 2. The degree of a vertex is its number of edges. As each edge has two ends, the
sourceandtargetcolumns are combined and counted.
Products (vertices): 200 Distinct pairs (edges): 18159 +------+------+---------------+ |source|target|orders_together| +------+------+---------------+ | 25| 91| 12| | 39| 76| 10| | 40| 195| 10| | 74| 195| 10| | 116| 153| 10| +------+------+---------------+ only showing top 5 rows +-------+-----+-------+ |minimum| mean|maximum| +-------+-----+-------+ | 167|181.6| 193| +-------+-----+-------+
Two honest readings. The first: the data is synthetic and the products in each order were picked at random, so the graph is almost complete (18,159 of the 19,900 possible pairs) and the most frequent pair, a lamp and a smartphone, means nothing. In a real shop the graph would be sparse and structured: cases alongside phones, cables alongside televisions. The second: the self-join is an expensive operation, because an order with n products generates n(n-1)/2 pairs; with very large orders you have to put a cap on it.
Graph libraries provide what comes next: algorithms that traverse the graph over several hops. With GraphFrames it would look like this (illustrative; requires adding the package):
from graphframes import GraphFrame
vertices = products.withColumnRenamed("product_id", "id")
relationships = edges.withColumnRenamed("source", "src").withColumnRenamed("target", "dst")
graph = GraphFrame(vertices, relationships)
importance = graph.pageRank(resetProbability=0.15, maxIter=10) # "central" products
groups = graph.connectedComponents() # product familiesGraphFrames requires those column names: id for the vertices, src and dst for the edges. pageRank scores each product according to how connected it is to other well-connected products; connectedComponents labels the groups of products that are linked to one another.
When to use it: batch graph analysis on data that is already in the lake (communities, influence, fraud rings that share a card or an address). When not to: interactive graph queries ("friends of friends of this user, right now"), which are the territory of a graph database such as Neo4j (lesson 02-03).
The pandas API on Spark
Marc is fluent in pandas. The pandas API on Spark (pyspark.pandas) lets him write code with pandas syntax that runs in a distributed way, because every operation is translated into a Spark plan.
A note on versions. This API depends on the installed version of pandas, and PySpark releases take a while to support the latest pandas versions. While this lesson was being prepared, the PySpark build used in the tests failed when importing
pyspark.pandaswith pandas 3, and worked with pandas 2. If this happens to you, do not touch your main environment: create a separate one (python -m venv .venv-psand, inside it,python -m pip install pyspark "pandas<3" pyarrow) and check the Spark documentation for the supported pandas version.
Create ~/novamarket/pandas_on_spark.py:
from pathlib import Path
import pyspark.pandas as ps
from pyspark.sql import SparkSession
LAKE = Path.home() / "novamarket" / "lake"
spark = SparkSession.builder.master("local[*]").appName("pandas_on_spark").getOrCreate()
spark.sparkContext.setLogLevel("ERROR")
orders = ps.read_parquet(str(LAKE / "silver" / "orders_complete"))
not_returned = orders[orders["status"] != "returned"]
summary = (
not_returned.groupby("channel")
.agg(orders=("order_id", "count"),
sales=("total_amount", "sum"),
avg_order_value=("total_amount", "mean"))
.sort_index()
)
print(type(summary))
print(summary.round(2))
spark.stop()The bracket filter, the groupby and the named agg are pure pandas. But ps.read_parquet does not load anything into memory, and the type of the result gives it away:
<class 'pyspark.pandas.frame.DataFrame'>
orders sales avg_order_value
channel
app 7598 12749007.27 1677.94
web 11401 19149250.26 1679.61Sales add up to the usual €31,898,257.53. You will also see a warning about the "default index": pandas gives each row a position, and numbering rows in a distributed system is expensive.
| Good fit | Poor fit |
|---|---|
| Migrating a pandas analysis that no longer fits in memory | New pipeline code: use Spark DataFrames |
| Teams that know pandas and occasionally need scale | Operations that depend on the order of rows or on the index |
| Prototypes that will be rewritten later | When the data fits in memory: plain pandas is faster |
It is not full pandas. While preparing the example, a first version with groupby("channel")["total_amount"].agg([...]) failed with PandasNotImplementedError: some methods are not implemented. And you can move between the two worlds: df.pandas_api() converts a Spark DataFrame, and psdf.to_spark() does the reverse.
Spark Connect and the language APIs
In the classic architecture (lesson 03-02), your program is the driver: it carries a Java virtual machine inside it and must use exactly the same Spark version as the cluster. Spark Connect separates the two:
flowchart LR
subgraph Client[Your application, notebook or IDE]
C[Thin client<br/>DataFrame API]
end
subgraph Cluster[Cluster]
S[Spark Connect server<br/>= driver]
E1[Executor]
E2[Executor]
end
C -- "unresolved logical plan (gRPC)" --> S
S -- "results (Arrow)" --> C
S --> E1
S --> E2
The client only builds the plan and sends it; the server optimises and runs it. For you, a single line changes (illustrative):
Advantages: the client does not need Java, it is lightweight, it can be upgraded independently of the cluster, and an out-of-memory error in your notebook does not bring down the shared driver. The trade-off: there is no access to the low-level APIs (RDD, sparkContext). It is the way more and more managed platforms work, and the gateway to clients in other languages.
| Language | Current role |
|---|---|
| Python (PySpark) | The most widely used; practically complete API |
| SQL | For analysts, dbt and BI tools |
| Scala | The language Spark is written in; for libraries and low-level code |
| Java | Complete API, more verbose; in companies with a Java base |
| R (SparkR) | Deprecated in recent versions; the alternative is the sparklyr package |
Cluster managers: standalone, YARN and Kubernetes
Spark does not manage machines: it requests resources from a cluster manager (lesson 03-02). There is none in your exercises, because local[*] runs everything in a single process.
| Standalone | YARN | Kubernetes | |
|---|---|---|---|
| What it is | Simple manager included with Spark | Hadoop's manager (lesson 03-01) | General-purpose container orchestrator |
| Where it fits | Small cluster dedicated to Spark only; testing | Existing Hadoop clusters, EMR, Dataproc | New deployments; companies that already use it for their applications |
| Isolation | Limited | Queues with quotas | Containers: each job carries its own image and dependencies |
| Python dependencies | Installed on every node | Installed on the nodes or packaged | Inside the container image |
| Operational difficulty | Low | Medium (requires Hadoop) | High without prior experience |
| Trend | Stable, niche | Declining | Growing |
Mesos, which appeared in older documentation as a fourth manager, has been removed from Spark.
The same daily_load.py would be submitted to each of them like this (illustrative):
# Standalone: give the address of the master node
spark-submit --master spark://master.novamarket.example:7077 \
--total-executor-cores 16 --executor-memory 14g \
daily_load.py 2026-06-15
# YARN: the address is taken from the Hadoop configuration (HADOOP_CONF_DIR)
spark-submit --master yarn --deploy-mode cluster \
--num-executors 4 --executor-cores 4 --executor-memory 14g \
daily_load.py 2026-06-15
# Kubernetes: give the cluster API and the container image
spark-submit --master k8s://https://k8s.novamarket.example:6443 --deploy-mode cluster \
--conf spark.kubernetes.container.image=registry.novamarket.example/daily-load:1.4 \
--conf spark.executor.instances=4 --conf spark.executor.cores=4 \
--conf spark.executor.memory=14g \
local:///opt/novamarket/daily_load.py 2026-06-15Only --master and the way resources are requested change; the script is identical. On Kubernetes, the local:// prefix indicates that the file is inside the image, and each executor is a container (a pod) that is created for the job and disappears when it finishes. In practice, many teams do not use spark-submit directly on Kubernetes but an operator that lets them declare the job in a YAML file.
Connectors: Spark and the rest of the world
Spark reads from and writes to almost any system through the data source API: spark.read.format("...") and df.write.format("..."). Parquet, ORC, JSON, CSV and JDBC come built in; the rest are connectors that are added when launching the application with --packages group:artifact:version, and whose version must match Spark's.
| System | format |
Typical use at NovaMarket |
|---|---|---|
| Kafka | kafka |
Reading the web_events topic (lesson 03-05) |
| Relational database | jdbc |
Nightly load of orders from the shop's database |
| Cassandra | org.apache.spark.sql.cassandra |
Writing events_by_customer |
| MongoDB | mongodb |
Reading the product catalogue |
| Elasticsearch / OpenSearch | org.elasticsearch.spark.sql / opensearch |
Indexing products for the search engine (lesson 06-03) |
| Delta Lake / Iceberg | delta / iceberg |
Lakehouse tables (lesson 02-05) |
Three illustrative snippets:
# JDBC: parallel read, the replacement for Sqoop
orders = (
spark.read.format("jdbc")
.option("url", "jdbc:postgresql://shop-db:5432/novamarket")
.option("dbtable", "(SELECT * FROM orders WHERE order_date >= '2026-06-15') AS o")
.option("user", user).option("password", password)
.option("partitionColumn", "order_id")
.option("lowerBound", 1).option("upperBound", 20000).option("numPartitions", 4)
.load()
)
# Cassandra: writing the per-customer history
(events.write.format("org.apache.spark.sql.cassandra")
.options(keyspace="novamarket", table="events_by_customer")
.mode("append").save())
# Iceberg: tables are named through a catalogue
spark.sql("SELECT COUNT(*) FROM lake.silver.web_events WHERE date = DATE '2026-06-15'")- With JDBC,
partitionColumn,lowerBound,upperBoundandnumPartitionsmake Spark open four connections, each with a range oforder_id: this is Sqoop's--num-mappers. Without them, the whole table is read through one connection and into a single partition. The subquery indbtablemakes the database apply the filter. The credentials arrive in variables and are never written in the code. - Well-built connectors push filters down to the source system (predicate pushdown, lesson 02-02), but they do not all push down the same things. Check with
explain().
Caution: a parallel JDBC read against the shop's database at peak time can degrade the website. Loads are run in the small hours, against a read replica if there is one, and with few connections.
Managed platforms and neighbouring projects
Hardly anyone installs Spark by hand in production. Managed platforms offer clusters that are created in minutes:
| Platform | Provider | Key feature |
|---|---|---|
| Databricks | The company founded by Spark's creators; runs on AWS, Azure and Google Cloud | Complete lakehouse; its own engine and features on top of Spark |
| Amazon EMR | AWS | Spark on YARN, on Kubernetes or serverless |
| Dataproc | Google Cloud | Ephemeral clusters that start quickly; serverless option |
| Synapse / Fabric | Microsoft | Spark integrated into its analytics platform |
Here we only place them on the map; lesson 06-04 compares them within each cloud.
Around Spark, projects have grown up that are often confused with it:
- Delta Lake. The table format you practised with in lesson 02-05. It was born at Databricks, is open source and is a separate project from Spark, even though Spark is its most common engine.
- MLflow. An open platform for the model life cycle: experiment tracking, packaging and a model registry. It works with any library, not just MLlib. It will come back when MLOps is discussed in lesson 08-01.
- Koalas. The original name of the pandas API on Spark when it was a separate package. It was merged into Spark as
pyspark.pandas; if you seeimport databricks.koalas, it is old code.
When Spark is not the right tool
Spark has fixed costs: several seconds to start a session, the planning of each query, the shuffle. With large data they are irrelevant; with small data, they are everything.
| Situation | Why Spark does not fit | Alternative |
|---|---|---|
| Data that fits on one machine (up to tens of GB) | Fixed costs dominate; you checked this in lesson 04-01 | DuckDB, Polars, pandas |
| Millisecond latency, event by event | Micro-batches have a latency floor | Flink, Kafka Streams (lesson 06-03) |
| Interactive queries from many users at once | Start-up time and concurrency are not its strong points | Trino, a data warehouse, ClickHouse |
| Reading or writing one row by its key | It is not a database | An operational or NoSQL database |
| Text search | It has no indexes | Elasticsearch / OpenSearch |
| Training deep neural networks | MLlib does not cover them | PyTorch or TensorFlow, with Spark to prepare the data |
NovaMarket is a good example of balance. Its practice data (38 MB) does not need Spark at all: DuckDB handles it in milliseconds. Its real data (7.6 GB a day, almost 3 TB a year) does justify a distributed engine for the nightly load, but Irene's dashboard, which reads gold/daily_kpis with 30 rows, does not. The rule from lesson 04-01 still holds: aggregate big, analyse small.
Common Mistakes and Tips
- Learning from old tutorials. If you see
SparkContextas the entry point,DStream,pyspark.mlliborSQLContext, the material predates the current API. - Using the pandas API on Spark as if it were free. Operations that are cheap in pandas (sorting, positional access, iterating over rows) can trigger a full shuffle.
- Mismatched connector versions. A connector compiled for another version of Spark or Scala fails with unhelpful errors (
NoSuchMethodError,ClassNotFoundException). Always check its compatibility table. - Reading over JDBC without partitioning. A single connection, a single partition and an executor out of memory.
- Choosing Kubernetes "because it's the modern thing" with nobody on the team who knows how to operate it. A managed or serverless service gives the same result with much less effort.
- Using Spark for everything. It is the mirror image of never using it. Ask first how big the data is.
- Confusing Databricks with Spark. Spark is the open project; the platforms add their own features that do not exist outside them. It pays to know which side each feature you use is on, in case you need to move one day.
Exercises
Exercise 1: placing each need
Say which piece of the ecosystem (or which external alternative) you would use to: a) load the customers table from PostgreSQL into the lake every night; b) detect groups of accounts that share a delivery address; c) Marc wants to reuse a pandas notebook on 300 GB of events; d) the website's search engine; e) score the fraud risk of a payment in 20 milliseconds; f) run the daily load at a company that already has all its applications in containers.
Exercise 2: "customers who bought this also bought"
Write recommend_together.py: given a product_id (use 91), show the three products it most often shares an order with, with their name and category. Hint: you do not need the full self-join.
Exercise 3: Spark or not?
A colleague proposes setting up a Spark cluster on Kubernetes to generate the monthly sales report (lesson 05-05) from gold/fact_sales, which takes up about 2 GB in production. Argue for or against.
Solutions
Exercise 1
a) Spark with the JDBC connector (or a managed ingestion tool). b) GraphFrames: connected components on an account–address graph. c) pandas API on Spark, on the assumption that some methods will need adapting. d) No Spark piece at all: Elasticsearch or OpenSearch; at most, Spark loads the index. e) Not Spark either: an event-by-event engine or a scoring service; Spark trains the model in batch. f) Spark on Kubernetes, with the code in an image.
Exercise 2
With the same header as bought_together.py (imports, LAKE, session and reading lines):
PRODUCT = 91
products = spark.read.parquet(str(LAKE / "silver" / "products"))
orders_with = lines.where(F.col("product_id") == PRODUCT).select("order_id")
neighbours = (
lines.join(orders_with, on="order_id")
.where(F.col("product_id") != PRODUCT)
.groupBy("product_id")
.agg(F.countDistinct("order_id").alias("orders_together"))
.join(products, on="product_id")
.select("product_id", "name", "category", "orders_together")
.orderBy(F.desc("orders_together"), "product_id")
)
print("Orders containing the product:", orders_with.distinct().count())
neighbours.show(3, truncate=False)Orders containing the product: 252 |product_id|name |category |orders_together| |25 |Lamp Lumen 235 |home |12 | |60 |Headphones Nova 943|audio |9 | |63 |TV Mount Altea 268 |television|7 |
First the 252 orders containing the product are located, and only those are joined with the lines: much cheaper than building all 18,159 edges. Look at the figure: 12 co-occurrences out of 252 orders is less than 5%. With random data, the "recommendation" is noise; a real system would require a minimum number of co-occurrences and would correct for each product's popularity, because the best sellers appear alongside everything.
Exercise 3
Against. With 2 GB in Parquet, DuckDB or even Spark in local mode on a single modest machine can generate the report in seconds. A cluster on Kubernetes would add infrastructure that someone has to maintain, start-up times longer than the calculation itself and a cost with nothing to show for it. It would make sense if the report started from the raw events (terabytes) or if there were already a shared cluster for other workloads; in that case the report would be just one more job. The right question is not "can we do it with Spark?" but "what is the simplest tool that meets the requirement?".
Conclusion
Spark is an ecosystem with a very clear centre: Spark SQL and DataFrames, optimised by Catalyst and executed by Tungsten, on which Structured Streaming, MLlib, graph processing and the pandas API rest; what was built on RDDs (DStreams, pyspark.mllib, GraphX) has been left behind. Spark Connect separates the client from the cluster; three managers (standalone, YARN and Kubernetes) supply it with machines without the code changing; and connectors link it to Kafka, databases and table formats. Around it, managed platforms and projects such as Delta Lake and MLflow round out the offering. And you have seen its limits: small data, millisecond latencies, search and key-based access call for another tool.
Those limits are the starting point of the next lesson. Other Tools and Platforms presents precisely what fills the gaps Spark leaves: Flink for event-by-event streaming, Kafka as a complete platform rather than just a queue, Elasticsearch for search, Trino for querying several sources at once, and real-time analytical databases. It is the lesson that 03-05 promised.
