Interview's MateData Science
Interview's Mate

Data Science

Python → ML → MLOps

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
Data Science topics
Lesson 40/ 160
02. SQL & Data Engineering Basics

Big Data Processing with PySpark

Distribute transforms with Spark DataFrames, partitions, and lazy execution for large datasets.

AdvancedSpark DataFrames · Partitions3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Spark splits big data across many computers, works on the pieces at the same time, and only starts working once you ask for a result.

Think of it like…

A team of clerks each handling a stack of ledgers (partitions) in parallel. Counting within one stack is quick; asking "total per customer across all stacks" requires carrying papers between clerks (shuffle), which is slow. Lazy evaluation is the manager writing the whole plan first, then reorganising it before any clerk starts.

Where you’ve seen it

A feature job aggregates 3 billion events (1.2 TB Parquet) into per-user features. The first version joins events to a 40,000-row user-segment table with a regular join, shuffling all 3 billion rows and taking 90 minutes. Broadcasting the small table (events.join(F.broadcast(segments), "user_id")) avoids the shuffle, and filtering to the last 90 days before the join prunes partitions; the job drops to 11 minutes. The final 2-million-row feature table is small enough for toPandas() into scikit-learn.

Words you’ll hear

Transformation vs action
Transformations (filter, select, join) are lazy; actions (count, collect, write) run the plan.
Partition
A chunk of data processed by one task; the unit of parallelism.
Shuffle
Redistributing data across the cluster for groupBy, join or orderBy; expensive.
Broadcast join
Sending a small table to every executor to join without shuffling the big one.

Visual diagram

Loading interactive diagram

Theory & deep dive

DataFrames, lazy evaluation and partitions

df = spark.read.parquet("events/") then df.filter(F.col("event_date") >= "2026-08-01").select("user_id", "amount").groupBy("user_id").agg(F.sum("amount").alias("spend")) builds a logical plan without reading data. .write.parquet(...), .count() or .show() triggers execution; df.explain() prints the physical plan. The optimiser pushes filters and column selection into the Parquet reader, so reading fewer columns and partitions is cheap, and Adaptive Query Execution (on by default in recent Spark) adjusts join strategies and partition counts at run time.

Data is split into partitions; each task processes one. Narrow transformations (filter, select, withColumn) work partition by partition with no data movement. Wide transformations (groupBy, join, distinct, orderBy, repartition) need a shuffle, writing and moving data across the network, so they dominate run time. Tune with sensible file layouts (Parquet partitioned by date), spark.sql.shuffle.partitions (default 200) and enough but not excessive partitions (aim for roughly 100 to 200 MB per partition).

Lazy until an action

result = df.filter(...).groupBy(...).agg(...) returns immediately. result.write.mode("overwrite").parquet("features/") runs the whole plan once, with the filter pushed down to the file scan.

Key takeaway: Nothing runs until an action; filters and columns are pushed down; shuffles are the cost.

Joins, skew, UDFs and moving to pandas

Joining two big tables shuffles both sides by key. If one side is small (up to hundreds of MB), broadcast it. Spark does this automatically below spark.sql.autoBroadcastJoinThreshold (10 MB by default), and you can force it with F.broadcast(small). Skew, where one key (a null id, a bot user) holds a huge share of rows, makes one task far slower than others; fix by filtering or handling the hot key separately, salting the key, or letting AQE split skewed partitions. Cache (df.cache()) only DataFrames reused several times, and avoid collect() on large data.

Prefer built-in functions (F.when, F.date_trunc, F.window) over Python UDFs, which serialise each row to Python and run slowly; if you need custom Python, use pandas UDFs (Arrow-based, vectorised). Window functions work as in SQL (F.row_number().over(Window.partitionBy("user_id").orderBy("ts"))). To hand data to scikit-learn or plotting, reduce first (aggregate, sample, filter) and then toPandas(); keep it to what fits in the driver's memory. For distributed ML use Spark MLlib or libraries that integrate with Spark; consider Dask, Polars or DuckDB if your data is large but fits on one big machine, since a single-node tool can be faster and simpler than a cluster.

A broadcast join and window

w = Window.partitionBy("user_id").orderBy(F.col("ts").desc()); latest = (events.join(F.broadcast(segments), "user_id").withColumn("rn", F.row_number().over(w)).filter("rn = 1")) picks each user's latest event after attaching the segment without shuffling the events for the join.

Key takeaway: Broadcast small tables, handle skew, avoid Python UDFs, and reduce before toPandas.

How it works, step by step

Step 1 of 4
Plan

1. Decide if you need Spark

If the data fits in one machine's memory or disk with Polars, DuckDB or pandas, prefer that; use Spark when it doesn't.

1.2 TB → Spark · 8 GB → pandas/DuckDB
Key numbers at this step
Cluster
has overhead

When to use it & trade-offs

What it is

Apache Spark processes data too large for one machine by splitting it into partitions spread across a cluster and running tasks on them in parallel. PySpark is its Python API; the main abstraction is the DataFrame, with a SQL-like and pandas-like set of operations (select, filter, groupBy, join, withColumn). Spark is lazily evaluated: transformations only build a plan, and an action (count, write, show) triggers execution after the optimiser (Catalyst) has planned it. Operations that regroup data across partitions cause a shuffle, the main cost to manage.

Why it matters: When a dataset outgrows pandas (tens of gigabytes and up), Spark is the standard answer, and ML pipelines at large companies are often built on it. But Spark has a different performance model: the code looks like pandas, yet a careless join or collect can crash a cluster. Understanding lazy evaluation, partitions, shuffles and broadcast joins is the difference between a 5-minute job and a 5-hour one.

When to reach for it

  • Feature engineering over billions of events
  • Batch ETL on data lakes
  • Large-scale joins and aggregations before modelling

When to avoid or be careful

  • collect() or toPandas() on large DataFrames
  • Python UDFs where built-in functions exist
  • Spark for data that fits comfortably in pandas

Tools for larger-than-pandas data

PySpark (cluster)
Best for: Hundreds of GB to petabytes; shared data platforms

Strengths: Scales horizontally; rich ecosystem (SQL, streaming, MLlib).

Watch out: Cluster overhead; shuffles and skew to manage.

DuckDB / Polars (single machine)
Best for: Data that fits on one large machine

Strengths: Very fast, simple, no cluster.

Watch out: Bounded by one machine.

Warehouse SQL (BigQuery, Snowflake)
Best for: Analytics already living in the warehouse

Strengths: No infrastructure to manage; scales automatically.

Watch out: Cost per query or compute; less control for custom code.

Interview signals & numbers to know

When this topic comes up

  • “The notebook runs out of memory”
  • “What's a shuffle?”
  • “The Spark job has one slow task”
  • Lazy evaluation
  • Broadcast joins

Benchmarks & rules of thumb

200 -
default spark.sql.shuffle.partitions
10 MB -
default auto-broadcast threshold
90 min → 11 min -
speed-up from broadcasting in the example
100 – 200 MB -
a good partition size

Common mistakes & follow-ups

Common interview mistakes

  • Calling toPandas() on a billion-row DataFrame and crashing the driver.
  • Joining a huge table to a tiny lookup with a regular shuffle join.
  • Writing a row-by-row Python UDF for logic that F.when expresses natively.

Likely interviewer follow-ups

  • What is lazy evaluation in Spark?
  • Why is a shuffle expensive, and how do you reduce it?
  • When would you use DuckDB or Polars instead of Spark?
Interview tip: Connect each concept to a cost: lazy plans enable pushdown, shuffles are the bill, broadcasting avoids it. That story is more convincing than defining terms.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Big Data Processing with PySpark with data science interview Q&A and hands-on practice.

Open Data Science Q&A →Machine Learning Q&A
Previous topic
NoSQL Databases (MongoDB Basics)
Next topic
Descriptive Statistics (Mean, Median, Mode)