Broadcast variables and accumulators
Code that updates an ordinary Python variable inside a Spark function looks fine and silently does nothing: the driver's variable never changes. This lesson shows why, and the two shared variables Spark provides instead: broadcast variables for reading and accumulators for counting.
Step 2 · Spark internals · Silver · Memory and resources, lesson 2 of 3
On this page
Read first: Driver, executors and the cluster manager · Transformations vs actions (skip if you know them)
In plain words first
A manager hands each worker a photocopy of a tally sheet. The workers make marks on their own copies, and the manager's original stays blank. To get the totals back, workers must report their counts, and the manager adds them up.
That is why changing a normal variable inside a Spark tasktask: The work for one partition in one stage, run on one CPU core. Learn more → does nothing for the driverdriver: The process that runs your program, plans the work and sends tasks to executors. Learn more →. An accumulator is the "report back your count" mechanism; a broadcastbroadcast join: A join where the small table is copied to every machine, so the big table never has to be shuffled. Learn more → variable is a read-only copy handed out efficiently.
The closure problem
When a task runs a Python UDFUDF: User-defined function: your own Python function applied to each row. Flexible but much slower than built-in functions. Learn more → or an RDD function, Spark serializes the function together with every outside variable it references (its closure) and sends that copy with the task. Each executorexecutor: A worker process on a cluster machine that runs tasks and holds data in memory. Learn more → changes its own copy; the driver's variable never changes.
bad_rows = 0 def parse(line): global bad_rows if not line.strip(): bad_rows += 1 # changes a copy on the executor return line.split(",") rdd.map(parse).count() print(bad_rows) # still 0
The same goes for appending to a driver-side list or dict inside a UDF. The second cost of closures is size: a 50 MB lookup dict referenced in a UDF is shipped with every task. With 2,000 tasks that is 100 GB sent over the network.
Broadcast variables
rates = {"EUR": 1.08, "GBP": 1.27, "INR": 0.012} # built on the driver b_rates = spark.sparkContext.broadcast(rates) @F.udf("double") def to_usd(amount, currency): return amount * b_rates.value.get(currency, 1.0) # read on executors orders.withColumn("amount_usd", to_usd("amount", "currency")) b_rates.unpersist() # drop executor copies (re-sent if used again) b_rates.destroy() # remove everywhere; unusable afterwards
- The value is serializedserialization: Turning objects into bytes so they can be sent over the network or stored, and back again. Learn more → once and fetched by each executor the first time a task needs it, then kept in the executor's block manager for all later tasks. Executors fetch pieces from the driver and from each other (a BitTorrent-like protocol), so the driver is not the only source.
- It is read-only. Changing
.valueon an executor changes only that executor's copy. - It counts against storage memory on every executor, and must first fit on the driver.
| Broadcast variable | Broadcast join | |
|---|---|---|
| What is shipped | Any Python or JVM object | A small DataFrame |
| Who uses it | Your UDF or RDD code, via .value | Spark's join operator |
| How you get one | sparkContext.broadcast(obj) | Automatic under the threshold, or F.broadcast(df) |
| Prefer when | Code that cannot be expressed as a join (a parser, a model, a regex table) | Anything that can be a join: it stays inside CatalystCatalyst: Spark's query optimizer. It rewrites your DataFrame code into a faster equivalent plan before running it. Learn more → |
Accumulators
An accumulator is a variable tasks can only add to and only the driver can read. Spark merges every task's updates and sends them to the driver with task results.
bad_rows = spark.sparkContext.accumulator(0) def check(row): if row.amount is None: bad_rows.add(1) orders.foreach(check) # an action: updates counted exactly once print(bad_rows.value)
When accumulators over-count
Inside actionsaction: An operation that needs a result (count, show, write), so Spark has to run the job. Learn more →
foreach, foreachPartition: Spark applies each task's update only once, even if the task is retried.Inside transformationstransformation: An operation that describes a new DataFrame (filter, select, join) without running anything yet. Learn more →
map, UDFs, filter: updates can be applied again when a task is retried, a speculative copy runs, a lost stagestage: A group of steps Spark can run without moving data between machines. A new stage starts at every shuffle. Learn more → is recomputed, or the DataFrame is computed by a second action. Treat these values as approximate.Accumulators are also lazy: their value stays at zero until an action runs the transformation that updates them. In Python, custom types (sets, lists, dicts) need an AccumulatorParam with zero and addInPlace.
In DataFrame code, prefer these
- Counting with an aggregation:
F.sum(F.when(cond, 1).otherwise(0))is exact, retry-safe and optimised by Catalyst. - Observation (PySpark 3.3+): collect metrics during the action you were going to run anyway, with no extra job.
- A broadcast join instead of a broadcast variable whenever the lookup is a table.
from pyspark.sql import Observation obs = Observation("quality") checked = orders.observe(obs, F.count(F.lit(1)).alias("rows"), F.sum(F.col("amount").isNull().cast("int")).alias("null_amounts")) checked.write.mode("overwrite").parquet("out") print(obs.get) # {'rows': ..., 'null_amounts': ...}
SparkContext, so sparkContext.broadcast and sparkContext.accumulator are not available. Use a broadcast join, observe, or an aggregation instead.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: Count bad rows and look up exchange rates the DataFrame way, without accumulators or broadcast variables.
from pyspark.sql import Observation, functions as F raw = spark.createDataFrame( [("1", "EUR", "100.0"), ("2", "GBP", "oops"), ("3", "INR", "1000")], ["order_id", "currency", "amount"]) rates = spark.createDataFrame( [("EUR", 1.08), ("GBP", 1.27), ("INR", 0.012)], ["currency", "rate"]) quality = Observation("quality") usd = (raw.withColumn("amount", F.expr("try_cast(amount AS DOUBLE)")) .observe(quality, F.count(F.lit(1)).alias("rows"), F.count_if(F.col("amount").isNull()).alias("bad_amounts")) .where(F.col("amount").isNotNull()) # the lookup: sent once per executor .join(F.broadcast(rates), "currency") .withColumn("usd", F.round(F.col("amount") * F.col("rate"), 2))) usd.write.mode("overwrite").parquet("lab/shared/usd_orders") print("metrics:", quality.get) spark.read.parquet("lab/shared/usd_orders").orderBy("order_id").show()
Output from a real run
metrics: {'rows': 3, 'bad_amounts': 1}
+--------+--------+------+-----+-----+
|currency|order_id|amount| rate| usd|
+--------+--------+------+-----+-----+
| EUR| 1| 100.0| 1.08|108.0|
| INR| 3|1000.0|0.012| 12.0|
+--------+--------+------+-----+-----+What to notice:
- The GBP order is gone: its amount
oopsis not a number.bad_amounts: 1counted it during the same write. usdisamount × rate: 100 EUR becomes 108.0, 1,000 INR becomes 12.0.observe()replaces an accumulator (exact, no extra job), and a broadcast join replaces a broadcast variable.
Goal: See why a normal Python variable cannot count rows, and how an accumulator can count twice.
counter = 0 def bump(x): global counter counter += 1 # changes a copy inside a Python worker return x sc = spark.sparkContext sc.parallelize(range(100), 4).map(bump).count() print("plain variable after 100 rows:", counter) acc = sc.accumulator(0) sc.parallelize(range(100), 4).foreach(lambda x: acc.add(1)) # in an action: once print("accumulator in foreach:", acc.value) acc2 = sc.accumulator(0) def tag(x): acc2.add(1) return x rdd = sc.parallelize(range(100), 4).map(tag) # in a transformation rdd.count() rdd.count() # two actions: the map runs twice print("accumulator in map, two actions:", acc2.value)
Output from a real run
plain variable after 100 rows: 0 accumulator in foreach: 100 accumulator in map, two actions: 200
What to notice:
plain variable after 100 rows: 0: each worker changed its own copy; the driver's variable never moved.- The accumulator updated in
foreach(an action) counted exactly 100. - The accumulator updated in
mapcounted 200: the RDD was computed twice, once per action, and both runs added.
Common mistakes
- Incrementing a Python global inside a UDF — Each executor updates its own copy; the driver sees nothing.
- Using accumulator values from transformations as exact numbers — Retries, speculation and recomputation can count rows twice.
- Referencing a big dict directly in a UDF — It is serialized into every task. Broadcast it, or make it a broadcast join.
- Reading an accumulator before any action — Transformations are lazy, so it is still zero.
Key takeaways
- Closures are copied to executors; changes never return to the driver.
- Broadcast variables send read-only data once per executor instead of once per task.
- Accumulators are add-only on executors and readable only on the driver.
- Only accumulator updates in actions are guaranteed exactly once.
- In DataFrame code, prefer broadcast joins, aggregations and observe().
Interview prep
THE QUESTION
"You need to count malformed records while parsing. A global counter in the parse function always prints 0. Why, and what do you do?"
Avoid: "make the variable global" or "use a Python list". Neither leaves the executor.
Follow-ups · answer out loud, then open
Follow-up"When can an accumulator count the same row twice?"
foreach are applied exactly once.Scenario"A UDF looks up a 200 MB Python dict, and the job ships gigabytes of task data. How do you fix it?"
sparkContext.broadcast and read .value inside the UDF, or better, turn the dict into a small DataFrame and use a broadcast join, which keeps the work in the JVM.Trap"I am on Spark Connect. How do I create an accumulator?"
SparkContext, so sparkContext.accumulator and broadcast are unavailable. Use an aggregation, DataFrame.observe with an Observation, or a broadcast join instead.Check yourself
3 questionsA UDF increments a driver global. What does the driver see after the action?
Show the answer
The original value. Executors update serialized copies of the variable.
Where are accumulator updates guaranteed to be applied exactly once?
Show the answer
In actions such as foreach. For actions Spark applies each task's update once; transformations may be re-executed.
How often is a broadcast variable sent to an executor?
Show the answer
Once per executor. It is fetched on first use and cached in the executor's block manager.
Practise this
Interview problems on spark performance, graded on hidden tests
Keep going
Up next · Memory and resources · lesson 3 of 3 · 6 min readDynamic allocation
Add and remove executors with the workload, and keep shuffle files safe while executors come and go.
Related lessons
Broadcast joinsPySpark functions · 7 min read
UDFs and pandas UDFsSpark internals · 5 min read
Spark Connect
Previous: Caching and persistence
Primary sources: RDD guide: shared variables · RDD guide: understanding closures