Computer Engineering is coming soon

We're still writing and reviewing the notes for every subject, and we'll open it when every subject is ready. Meanwhile you can practise aptitude, ask Aria about any subject, or see the branches that are ready.

Apache Spark

Practical study notes on Apache Spark: what it is, core concepts (RDD/DataFrame/Dataset, transformations/actions, driver/executor/partitioning), key PySpark syntax, two runnable examples, common mistakes and exam guidance.

Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.

Why it matters

Apache Spark is used by engineers to process large datasets fast across many machines. It appears in data pipelines, analytics and machine learning steps of projects (for example after Hadoop HDFS or as part of a visualization workflow). Knowing Spark helps you scale Python/Scala code from a laptop to a cluster.

Key ideas

  • Driver — the process that runs your main program and creates Spark jobs. It plans work (creates tasks) and talks to the cluster manager.

  • Cluster Manager — Standalone, YARN, Kubernetes, or Mesos component that allocates resources (executors) to the Spark application.

  • Executor — a process launched on cluster nodes that runs tasks and stores data in memory or disk. Executors perform the actual computation.

  • Job — a computation triggered by an action; a job is divided into stages separated by shuffles.

  • Stage — a set of tasks that can be executed without requiring a shuffle; corresponds to a phase of narrow transformations.

  • Task — the unit of work that runs on a single partition within a stage.

  • Partition — a logical chunk of data processed by a task on an executor. Parallelism per stage is primarily the number of partitions (one task per partition), but actual concurrent execution is limited by available cores/task slots.

  • Resilient Distributed Dataset (RDD) — a fault-tolerant, immutable distributed collection of objects that can be processed in parallel. RDDs are defined by their lineage (a record of transformations to recreate them). Key properties:

    • Immutable: once created, cannot be changed.
    • Lazy: transformations build a plan; they do not execute until an action is called.
    • Lineage-based fault tolerance: if a partition is lost, Spark recomputes it using the lineage.
  • DataFrame — a distributed collection of data organized into named columns (like a table). A DataFrame is built on top of RDDs and offers optimizations (Catalyst optimizer). It is similar to a table in relational databases. In PySpark a DataFrame maps to pyspark.sql.DataFrame.

  • Dataset — (in Scala/Java) a strongly typed collection that combines the benefits of RDDs and DataFrames. PySpark does not have a separate typed Dataset API; DataFrame is the main API.

  • Transformation — a function that returns a new RDD/DataFrame (for example map, filter, join). Transformations are lazy (they build execution plans but do not run immediately).

  • Action — an operation that returns a result to the driver or writes data to storage (for example collect, count, RDD saveAsTextFile, DataFrame df.write.save(...)). Actions trigger execution of the transformations.

  • Narrow vs Wide dependencies — a narrow dependency means each partition of the parent RDD is used by only one child partition (e.g., map); a wide dependency requires data from many parent partitions (e.g., reduceByKey) and causes a shuffle (data movement across nodes). Wide dependencies define stage boundaries.

  • Shuffle — redistribution of data across executors to satisfy wide dependencies; costly in I/O and network. Minimise shuffles for performance.

  • Cache / Persist — store an RDD/DataFrame in memory (or disk) to reuse it across multiple actions. Use cache() for default in-memory, persist() to choose storage level.

  • Broadcast variable — a read-only variable sent to all executors efficiently when you need a small lookup table. Create it with sc.broadcast(value).

  • Accumulator — a write-only distributed variable for aggregating counters (e.g., counting bad records) on executors and reading in driver. Only the driver should read accumulator values; updates can occur more than once on task retries, so use them only for commutative/associative aggregates and not for control flow.

What to draw (exam diagram): draw a box labelled "Driver" with arrows to a "Cluster Manager". Draw several boxes labelled "Executor 1", "Executor 2". Inside each executor draw multiple small boxes labelled "Partition / Task". Show a job arrow from Driver to Executors. For a wide dependency (shuffle) draw arrows between partitions across executors labelled "Shuffle (network + disk)".

Step-by-step (map-reduce style derivation university exams ask for): to compute count of words in a distributed list:

  1. Map each record to tokens (flatMap) — this splits lines into words (narrow transformation, done in parallel per partition).
  2. Map each token to pair (word, 1) — still narrow.
  3. ReduceByKey — groups pairs by key and sums counts; this is a wide operation and triggers a shuffle to send same keys to the same reducer partition.
  4. An action (collect/save) triggers execution: tasks run for map stages, then shuffle, then reduce stage.

Assumptions behind correctness: immutable data (no side effects), deterministic user functions for transformations, enough cluster resources for parallel tasks, and reduction/aggregation functions that are associative and commutative to ensure deterministic parallel results.

Formulas

For a programming topic, remember the key PySpark syntax (each line is a syntax snippet; explanation follows):

from pyspark.sql import SparkSession

  • Create SparkSession class; used to start Spark in PySpark.

spark = SparkSession.builder.master("local[*]").appName("AppName").getOrCreate()

  • master: master URL (e.g., local[*], spark://host:port, yarn, k8s); local[*] uses all local cores. appName: name of job.

sc = spark.sparkContext

  • sc is the SparkContext (low-level). Use for RDDs, broadcast, accumulators.

rdd = sc.parallelize(list_of_items, numSlices)

  • Create an RDD from a Python collection. numSlices sets partitions.

rdd.map(func), rdd.flatMap(func), rdd.filter(func)

  • Transformations on RDDs. map returns one output per input, flatMap can return zero or more.

rdd.reduceByKey(func)

  • For RDDs of (key, value), reduce values per key; causes shuffle.

spark.createDataFrame(data, schema=[...])

  • Create a DataFrame from a list of tuples or dicts. schema gives column names.

df.select("col"), df.filter("col > 10"), df.groupBy("col").agg(func)

  • DataFrame transformations; agg uses functions from pyspark.sql.functions.

df.createOrReplaceTempView("view") and spark.sql("SELECT ... FROM view")

  • Use Spark SQL on DataFrames.

df.cache(), df.persist(StorageLevel.MEMORY_AND_DISK)

  • Cache/persist DataFrame in memory or disk. Import StorageLevel: from pyspark import StorageLevel (or from pyspark.storagelevel import StorageLevel).
  • Cache/persist DataFrame in memory or disk.

bc = sc.broadcast(value)

  • Create broadcast variable.

acc = sc.longAccumulator("acc_name") and acc.add(1) inside tasks

  • Create and use accumulator.

df.collect(), rdd.collect(), df.show(), rdd.count()

  • Actions that trigger execution. Avoid collect() on very large datasets (OOM risk).

Worked examples

Example 1 — Word count using RDD (complete runnable PySpark code). This demonstrates transformations, shuffle and action.

Code:

from pyspark.sql import SparkSession

spark = SparkSession.builder.master("local[*]").appName("AiCanCodeWordCount").getOrCreate()
sc = spark.sparkContext

# Sample input (small list of lines)
data = ["hello world", "hello spark", "hello world"]

rdd = sc.parallelize(data)
counts = (rdd.flatMap(lambda line: line.split())
             .map(lambda w: (w, 1))
             .reduceByKey(lambda a, b: a + b))

result = sorted(counts.collect())
print(result)

spark.stop()

Sample input (the list in code): ["hello world", "hello spark", "hello world"]

Exact output (printed by program):

[('hello', 3), ('spark', 1), ('world', 2)]

Example 2 — DataFrame group and filter with Spark SQL functions (complete runnable PySpark code). Shows DataFrame API, aggregation and deterministic output.

Code:

from pyspark.sql import SparkSession
from pyspark.sql.functions import avg

spark = SparkSession.builder.master("local[*]").appName("AiCanCodeDF").getOrCreate()

# Input rows: name, age, salary
data = [("Alice", 34, 2000.0), ("Bob", 45, 3000.0), ("Charlie", 23, 1500.0), ("Alice", 29, 2200.0)]

df = spark.createDataFrame(data, schema=["name", "age", "salary"])

avg_salary = df.groupBy("name").agg(avg("salary").alias("avg_sal"))
filtered = avg_salary.filter("avg_sal > 2000.0").orderBy("name")

out = [(row['name'], float(row['avg_sal'])) for row in filtered.collect()]
print(out)

spark.stop()

Sample input (the list data inside code): [("Alice", 34, 2000.0), ("Bob", 45, 3000.0), ("Charlie", 23, 1500.0), ("Alice", 29, 2200.0)]

Exact output (printed by program):

[('Alice', 2100.0), ('Bob', 3000.0)]

Notes: both examples use local[*] so they run on a single machine using all cores. They avoid writing files and use collect() only on tiny datasets; in real work do not collect large results to driver.

Common mistakes

  • Confusing RDDs and DataFrames: DataFrames have schema and optimizer (Catalyst); RDDs are lower level.
  • Not understanding shuffle cost: using wide operations (join, reduceByKey, groupBy) without anticipating network I/O.
  • Broadcasting very large objects (broadcast is for small lookup tables only).
  • Expecting exact row order without ordering step: distributed collections are not ordered unless you orderBy.
  • Forgetting to stop the SparkSession in scripts (resource leaks).
  • Using groupByKey for aggregations instead of reduceByKey/aggregateByKey, causing excessive shuffle and memory use.

For your exam

Kinds of questions:

  • Definitions: define RDD, DataFrame, driver, executor, transformation vs action. Full marks need concise definitions and a short note on lazy evaluation and lineage.
  • Short notes: explain shuffle and why it's expensive; explain caching and storage levels. Full marks include example use-cases and performance considerations.
  • Derivations/algorithms: show step-by-step how word-count works in Spark (map → pair → reduceByKey → collect) and draw the job/stage/task diagram.
  • Numericals: small traces of partitioning and counts — show how data moves in a shuffle stage. Full marks require partition-level reasoning and showing the shuffle destination for keys.
  • Programs: write PySpark code to perform a groupBy/aggregation and show exact printed output for a small input. Full marks require correct PySpark API usage and a brief explanation of transformations vs actions.
  • Diagrams: draw driver, cluster manager, executors and partitions; label shuffle and tasks. Full marks include clear arrows showing job → stages → tasks and where data is cached.

Quick check

  1. What is lazy evaluation in Spark?
  2. Name one wide operation and why it is costly.
  3. When should you use broadcast variables?

Answers: 1) Transformations are not executed until an action triggers the plan, saving unnecessary work. 2) reduceByKey (or join/groupBy) — causes a shuffle (network/disk I/O). 3) Use broadcast for small read-only lookup data that all executors need.

Finished this topic? Mark it so your progress, study plan and readiness keep up.

Stuck on something here?