Transformations vs actions
Spark code looks like it does each step as you write it, but most lines do nothing at all until you ask for a result. That is lazy evaluation, and it is why Spark can plan a whole job before running it. This lesson shows which operations wait and which ones run.
Step 2 · Spark internals · Bronze · How a job runs, lesson 1 of 5
On this page
Read first: Driver, executors and the cluster manager (skip if you know it)
In plain words first
Writing a shopping list is not shopping. You can add, cross out and reorder items for an hour and nothing is bought; the work happens when you walk into the shop. And because you see the whole list first, you can plan a route through the aisles.
In Spark, transformations (filter, select, join) are writing the list. Actions (count, show, write) are going to the shop.
Two kinds of operations
| Transformations (lazy) | Actions (run the job) |
|---|---|
select, withColumn, filter | count(), collect(), take(n) |
groupBy().agg(), join, orderBy | show(), toPandas() |
union, distinct, repartition | write...save(), saveAsTable |
cache() (marks only) | foreach, foreachPartition |
A transformation returns a new DataFrame immediately, in microseconds, whatever the data size, because it only adds a step to a logical plan. An action returns a value or writes output, so Spark has to compute.
Walk through a pipeline
Line 1 · read
The command
orders = spark.read.parquet("s3://shop/orders")
Line 2 · filter
The command
paid = orders.filter(F.col("status") == "PAID")
Line 3 · aggregate
The command
daily = paid.groupBy("order_date").agg(F.sum("amount").alias("revenue"))
Line 4 · action
The command
daily.write.mode("overwrite").parquet("s3://shop/daily_revenue")
Why lazy?
Seeing the whole pipeline before running it is what makes CatalystCatalyst: Spark's query optimizer. It rewrites your DataFrame code into a faster equivalent plan before running it. Learn more →'s optimisations possible: filters move down next to the scan, unused columns are never read, consecutive projections merge into one, and joins can pick a strategy knowing what comes after. Running each line eagerly, as pandas does, would read everything first.
The recomputation trap
A DataFrame is a recipe, not a result. Every action re-runs the recipe from the source:
clean = raw.filter(...).withColumn(...) # expensive clean.count() # job 1: reads and cleans clean.write.parquet("out") # job 2: reads and cleans again
If a DataFrame is used by several actions, either cachecache: Keeping a computed DataFrame in memory (or on disk) so later actions reuse it instead of recomputing it. Learn more → it (see the Caching lesson) or restructure so a single action does the work. A common unnecessary action is a count() just to log a number.
Where errors show up
- Analysis errors (a missing column, a type mismatch) appear immediately when you write the transformation, because Spark resolves names eagerly.
- Runtime errors (a bad cast in ANSI mode, a division by zero, a corrupt file, an out-of-memory) appear only at the action, often many lines later. The stack trace points at the action, not at the transformation that caused it.
limit(10).show() after a suspicious step to force evaluation there. Remove it afterwards.Try it yourself
Each example says what it shows, then the output from a real run and what to notice in it, so you can follow without running anything. To try one yourself, paste it into a local Spark session, with spark already created: each builds its own data.
Goal: Build a pipeline from transformations, run it with a single action (the write), and collect metrics during that same write.
from pyspark.sql import Observation, functions as F def clean_orders(raw): return (raw.filter(F.col("status") == "PAID") .withColumn("amount", F.col("amount").cast("double")) .select("order_id", "country", "amount")) raw = spark.createDataFrame( [(1, "PAID", "IN", "120.5"), (2, "REFUNDED", "US", "80"), (3, "PAID", "IN", "45")], ["order_id", "status", "country", "amount"]) clean = clean_orders(raw) # transformations only: nothing has run yet # Metrics collected during the write, instead of an extra count() job before it. metrics = Observation("clean_orders") (clean.observe(metrics, F.count(F.lit(1)).alias("rows"), F.sum("amount").alias("amount")) .write.mode("overwrite").parquet("lab/actions/clean_orders")) # the one action print("written:", metrics.get) spark.read.parquet("lab/actions/clean_orders").orderBy("order_id").show()
Output from a real run
written: {'rows': 2, 'amount': 165.5}
+--------+-------+------+
|order_id|country|amount|
+--------+-------+------+
| 1| IN| 120.5|
| 3| IN| 45.0|
+--------+-------+------+What to notice:
- Order 2 is missing: it was
REFUNDED, and the filter keeps onlyPAIDorders. written: {'rows': 2, 'amount': 165.5}came fromobserve()while writing (120.5 + 45). There was no separatecount()job.clean_orders(raw)ran nothing by itself; only the write did.
Goal: See when Spark reports an error: a bad value fails at the action, a wrong column name fails at once.
from pyspark.sql import functions as F bad = (spark.createDataFrame([("1",), ("2",), ("oops",)], ["raw"]) .withColumn("n", F.col("raw").cast("int"))) # no error here: only a plan print("defined fine") try: # ANSI mode: the bad cast fails now bad.collect() except Exception as e: print("failed at the action:", str(e).split("]")[0] + "]") try: bad.select("no_such_column") # analysis errors are eager except Exception as e: print("failed immediately:", type(e).__name__)
Output from a real run
defined fine failed at the action: [CAST_INVALID_INPUT] failed immediately: AnalysisException
What to notice:
defined fine: building the DataFrame with a cast that will fail raised nothing, because nothing ran yet.- The cast error (
[CAST_INVALID_INPUT]onoops) appeared only atcollect(), the action. - Selecting a column that does not exist failed immediately (
AnalysisException): Spark checks names while building the plan.
Common mistakes
- Timing transformations — Measuring how long a filter "takes" measures nothing; time the action.
- Calling several actions on an uncached DataFrame — Each action recomputes everything from the source.
- Debug count() calls left in production — Each one is a full extra job.
Key takeaways
- Transformations build a plan; actions run it.
- Laziness lets Catalyst optimise the whole pipeline.
- Each action recomputes from the source unless you cache.
- Runtime errors surface at the action, not where they were caused.
Interview prep
THE QUESTION
"Why does this code read the source twice?"
cache() or persist() if the result is reused and fits, or remove the extra action. A good answer also explains why laziness exists: whole-plan optimisation.Avoid: "because Spark is lazy" and stopping there. Say what the action re-runs and how you would avoid it.
Follow-ups · answer out loud, then open
Follow-up"Name an operation that looks like a transformation but triggers a job."
inferSchema runs a job to sample the data. orderBy runs a sampling job to pick range boundaries. A broadcast join collects the small side. df.rdd.getNumPartitions() is cheap, but df.count() used for logging is a full job. Showing you know these hidden jobs is what the question tests.Scenario"A pipeline is slow, and the Spark UI shows the same file scan in six jobs. What happened?"
show(), writes to two outputs) each re-ran the plan from the source. Remove unnecessary actions, cache the shared DataFrame if it is reused and much smaller than the source, or restructure so one action produces everything, for example writing once and reading the written output for the second use.Trap"I put df.cache() before the loop, so the data is already in memory, right?"
cache() is lazy too: it only marks the DataFrame. Nothing is stored until the first action computes it, and a partial action like take(1) may cache only the partitions it touched. Trigger it with a full action such as count() if you need it materialised before the loop.Check yourself
3 questionsWhich is an action?
Show the answer
count(). count returns a value to the driver, so Spark must compute.
A DataFrame is written and then counted, with no cache. How many times is the source read?
Show the answer
Twice. Each action re-runs the plan from the source.
When does a missing column error appear?
Show the answer
Immediately, when the transformation is defined. Spark analyses names eagerly, so unresolved columns fail right away.
Practise this
Interview problems on spark performance, graded on hidden tests
Keep going
Up next · How a job runs · lesson 2 of 5 · 5 min readRDDs, DataFrames and Datasets
The three Spark APIs, what Catalyst can and cannot optimise, and when an RDD still makes sense.
Related lessons
Jobs, stages and tasksSpark internals · 6 min read
Caching and persistenceSpark internals · 6 min read
Catalyst and physical plans
Previous: Driver, executors and the cluster manager
Primary sources: RDD programming guide: lazy evaluation · Spark SQL guide