What you will be able to do
- Explain why Spark copies captured variables into every task, and why updates made on executors never reach the driver
- Use a broadcast variable to give each executor one read-only copy of a lookup value, and release it with unpersist or destroy
- Use an accumulator as a counter that tasks add to and only the driver reads, and predict when its value can be counted twice
- Recognise where SparkContext-based shared variables are unavailable on Databricks, and name the DataFrame replacements
Key concept
Shared variables — The two exceptions to Spark's rule that every task gets its own private copy of the variables it uses. A broadcast variable is a read-only value cached once per node, and an accumulator is a value that tasks can only add to and only the driver can read.
1.Ordinary variables are copied into every task
A Python variable that a Spark function refers to does not stay in one place. When the driver sends a function to the cluster, Spark serializes the function's closure, meaning the function plus every variable it captures, and ships it with each task. A lookup_country UDF that reads a dictionary called country_codes therefore carries a copy of country_codes in every task it runs in. On a 500 million row DataFrame split into thousands of partitions, that is thousands of copies of the same dictionary crossing the network.
The copies only flow one way. Each executor works on its own copy, and nothing it changes is sent back. A counter declared as total = 0 on the driver and incremented inside a UDF still reads 0 on the driver when the job finishes, because every task incremented a private copy that was thrown away when the task ended. Spark has no general read-write variable shared across the cluster, since keeping one consistent across hundreds of tasks would be slow.
Spark offers two restricted kinds of shared variable for the two patterns that people actually need: sending one value out to all tasks efficiently, and collecting a total back from all tasks safely. Broadcast variables handle the first and accumulators the second. Each one gets its safety by limiting what you can do with it. A broadcast variable is read-only. An accumulator is add-only for tasks, and only the driver can read it.
Checkpoint 1 of 7· Check yourself
On the driver, a developer creates error_counts = {}. A UDF that runs over a large multi-partition DataFrame does error_counts[code] = error_counts.get(code, 0) + 1 for each row. After the job writes its output, the driver prints error_counts. What does it show?
Spark serializes the closure and sends a copy of each captured variable with every task. Changes made on executors are never sent back, so the driver's dictionary stays empty. Collecting values back to the driver needs a shared variable such as an accumulator.
“it ships a copy of each variable used in the function to each task”Source: spark.apache.org
2.Broadcast variables: one read-only copy per node
A broadcast variable sends a value to each executor once and keeps it cached there, so tasks read the local copy instead of getting their own. You create one on the driver with SparkContext.broadcast(v), which in a notebook is spark.sparkContext.broadcast(v). Inside functions you read it through the .value attribute. For the country lookup, that means bc = spark.sparkContext.broadcast(country_codes) on the driver and bc.value.get(code, "Unknown") inside the UDF. The UDF should refer to bc rather than country_codes, or the original dictionary is captured in the closure and shipped with every task again.
>>> broadcastVar = sc.broadcast([1, 2, 3])
<pyspark.core.broadcast.Broadcast object at 0x102789f10>
>>> broadcastVar.value
[1, 2, 3]Read-only is a rule you have to follow yourself, because Spark does not enforce it. If the driver changes the original object after broadcasting it, an executor that joins the cluster later may receive the changed version while older executors keep the old one. Executors that mutate their cached copy change only their own copy. If a lookup table changes, broadcast it again as a new variable.
A broadcast value takes up executor memory until you release it. unpersist() deletes the cached copies on the executors, and the value is broadcast again automatically if a later task uses it. destroy() deletes all of its data and metadata permanently, and using the variable after that fails. Neither call blocks by default.
Spark already broadcasts the data that tasks within one stage share. An explicit broadcast variable is worth creating when the same value is used across several stages or jobs, as with a lookup dictionary that one UDF reads in every task of a long pipeline.
The broadcast() function in pyspark.sql.functions is a different tool that shares the name. It takes a DataFrame and tells the optimizer to copy that DataFrame to every executor for a join. spark.sql.autoBroadcastJoinThreshold likewise controls only which tables get broadcast in joins. Neither one has any effect on a Python dictionary captured by a UDF. The join-side mechanism is covered in broadcast joins.
| Property | Broadcast variable | Accumulator |
|---|---|---|
| Created on the driver with | SparkContext.broadcast(v) | SparkContext.accumulator(v) |
| What tasks can do | Read it through value | Add to it with add or += |
| Who reads the result | Every task, from its node's cached copy | Only the driver, through value |
| Direction of data | Driver to executors | Executors to driver |
| Cleanup | unpersist() or destroy() | None needed; read value after the action |
Checkpoint 2 of 7· Check yourself
A UDF in a long pipeline reads a large Python dictionary, country_codes, in every task. The goal is to stop a copy of that dictionary from being shipped with each task. Which change does that?
Only SparkContext.broadcast creates a broadcast variable. Each node caches its value once, and tasks read it through .value. The UDF must refer to bc, because if it captures country_codes the dictionary is still shipped with every task. The functions.broadcast() call and the autoBroadcastJoinThreshold setting only affect join planning for DataFrames.
“A broadcast variable created with SparkContext.broadcast(). Access its value through value.”Source: spark.apache.org
Checkpoint 3 of 7· Exam question
What is the primary motivation for using a broadcast variable instead of relying on Spark's default task closure mechanism to make a value available to executors?
Correct answer: A — It caches a read-only copy of the value once per executor, avoiding the cost of resending that same value with every task needing it.
- A. This is the documented purpose of broadcast variables: keep a read-only copy cached on each machine rather than shipping a fresh copy of the value with every task.
- B. Broadcast variables are explicitly read-only after creation; changes made on an executor are local and are never synchronized back to the driver or to other executors.
- C. Broadcast variables live in executor memory for the life of the Spark application and have no relationship to the Delta transaction log or to durability across separate application runs.
- D. Broadcasting keeps the full value intact on every executor rather than splitting it into partitions; partitioning a value across the cluster describes a distributed Dataset, not a broadcast variable.
- E. Broadcast variables are held in executor memory (and can spill to local disk under pressure), and creating one has no requirement to first write the value to durable cloud storage.
3.Accumulators: tasks add, only the driver reads
An accumulator sends information the other way, from tasks back to the driver. You create one on the driver with sc.accumulator(0). Tasks add to it with add() or +=. Spark merges the additions from each finished task into the driver's copy, and the driver reads the total through .value. Because the merge only has to add, accumulators suit counters and sums: rows with a negative amount, records that failed to parse, bytes processed.
>>> accum = sc.accumulator(0)
>>> accum
Accumulator<id=0, value=0>
>>> sc.parallelize([1, 2, 3, 4]).foreach(lambda x: accum.add(x))
...
10/09/29 18:41:08 INFO SparkContext: Tasks finished in 0.317106 s
>>> accum.value
10Whether you can trust the number depends on where the add happens. When the update runs inside an action, such as foreach, Spark applies each task's update exactly once, even if the task is retried. A foreach(flag_negative) over orders_df followed by print(neg_count.value) on the driver prints the exact number of negative rows. No registration step is needed, and no second action is needed, because the value is ready once the action returns.
Inside a transformation, such as a map or a UDF in withColumn, there is no exactly-once guarantee. A failed or speculative task that runs again adds a second time. A stage that is recomputed adds again too, which happens when a DataFrame that was never cached feeds two actions. Lazy evaluation adds a separate trap: until an action runs, the transformation has not run at all, so the accumulator still reads 0. The rules for when work actually runs are in lazy evaluation.
About 100, because each action re-runs the transformation and adds again. If the plan optimizes the UDF away for count(), the result could be a different number entirely. To get a trustworthy count, do the counting in an action or with a DataFrame aggregation.
Accumulators are also not a substitute for DataFrame logic. A filter(col("amount") < 0).count() gives the same answer with no shared state, and it is the replacement Databricks recommends where accumulators are unavailable.
Checkpoint 4 of 7· Check yourself
A job looks up each record's region in a fixed Python dictionary inside a UDF. It must also report on the driver how many records had no matching region. Which design fits Spark's shared-variable rules?
Data flows one way for each type. A broadcast variable sends a read-only value from the driver to the tasks, and an accumulator collects additions from the tasks for the driver to read. Tasks cannot read an accumulator, and changes to a broadcast copy are never sent back to the driver.
“accumulators, which are variables that are only “added” to, such as counters and sums”Source: spark.apache.org
Checkpoint 5 of 7· Exam question
A data engineer has a small Python dictionary country_codes (well under 1 MB) that maps ISO codes to country names, and needs to look it up inside a PySpark UDF applied to a 500 million row DataFrame. To avoid Spark serializing and shipping a fresh copy of country_codes with every task, which change should the engineer make to the following code?
def lookup_country(code):
return country_codes.get(code, "Unknown")
lookup_udf = udf(lookup_country, StringType())
df = df.withColumn("country_name", lookup_udf(col("iso_code")))
Correct answer: A — Wrap country_codes with spark.sparkContext.broadcast(country_codes) and reference bc.value.get(code, "Unknown"), so every executor keeps one cached copy.
- A. Broadcasting caches a single read-only copy of the dictionary on each executor, and referencing
.valueinside the UDF avoids re-serializing and re-sending the dictionary with every task. - B. Rebuilding the dictionary inside the function makes the problem worse: Spark still ships whatever data built it, and the work of constructing the mapping now repeats on every single row.
- C. A join is a valid pattern for larger reference tables, but for a small in-memory dictionary it adds an unnecessary shuffle and does not fix the serialization behavior of the existing UDF code.
- D. Accumulators are write-only aggregators whose running total only the driver can read; they are not a mechanism for distributing an arbitrary read-only mapping for executors to look values up in.
- E.
spark.sql.autoBroadcastJoinThresholdonly influences whether Catalyst chooses a broadcast join strategy for DataFrame joins, and has no effect on a plain Python closure referenced inside a UDF.
Checkpoint 6 of 7· Exam question
A team runs the following PySpark job to count rows where amount is negative, then submits it as a batch job:
neg_count = spark.sparkContext.accumulator(0)
def flag_negative(row):
if row.amount < 0:
neg_count.add(1)
orders_df.foreach(flag_negative)
print(neg_count.value)
The job runs once with no task failures or retries. What does print(neg_count.value) output?
Correct answer: A — The exact count of rows with a negative amount, because foreach is an action, and Spark guarantees exactly-once accumulator updates here.
- A.
foreachis an action, so it forces evaluation, and without retries each task's accumulator update is guaranteed to apply exactly once, giving an exact negative-row count. - B. Once an action like
foreachcompletes, the driver can immediately read the accumulator's.value; a second unrelated action is not required to make the update visible. - C. Spark does not re-execute a successfully completed task twice by default; double execution only happens under retries or speculative execution, neither of which occurred here.
- D. PySpark's default numeric accumulator created with
spark.sparkContext.accumulator(0)is registered automatically and its.valueis readable on the driver without any extra registration call. - E. The driver can read an accumulator's
.valueonce the action that updates it has finished; it is not blocked simply because other unrelated jobs are running in the cluster.
4.Where shared variables are unavailable on Databricks
Both kinds of shared variable are created through SparkContext, so they only work where your code can reach a SparkContext. Serverless compute supports only Spark Connect APIs, and Databricks also uses Spark Connect for Python notebooks on standard access mode compute from Databricks Runtime 14.3. On those compute types the client talks to a remote Spark server and gets no SparkContext, so spark.sparkContext.broadcast(...) and sc.accumulator(...) are not available. Classic compute in dedicated access mode still supports them.
The Databricks migration guidance replaces each one with a DataFrame operation that the engine distributes for you. A broadcast lookup dictionary becomes a small DataFrame joined with the broadcast() hint. An accumulator counter becomes an aggregation such as count or sum over a filtered DataFrame. Both replacements are declarative, so they avoid the double-counting problem as well.
Spark Connect also changes how ordinary captured variables behave. Python UDFs are serialized when they run, not when they are defined, so a UDF that captures x = 123 and runs after the driver sets x = 456 uses 456. More on the client-server split is in Spark Connect.
Checkpoint 7 of 7· Check yourself
Which Databricks compute choice still lets a Python notebook create a broadcast variable with spark.sparkContext.broadcast(...) and a counter with sc.accumulator(0)?
Both shared variables are created through SparkContext. Serverless compute, and Python notebooks on standard access mode compute from Databricks Runtime 14.3, use Spark Connect, which gives the client no SparkContext. Only classic compute in dedicated access mode still supports them. The autoBroadcastJoinThreshold setting affects join planning only.
“Python notebooks with Databricks Runtime version 14.3 and above, on standard compute”Source: docs.databricks.com
Sources
(6)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.https://spark.apache.org/docs/latest/rdd-programming-guide.htmlSecondary source
“it ships a copy of each variable used in the function to each task”
↩︎ Ordinary variables are copied into every task“These variables are copied to each machine, and no updates to the variables on the remote machine are propagated back to the driver program.”
↩︎ Ordinary variables are copied into every task“Broadcast variables allow the programmer to keep a read-only variable cached on each machine rather than shipping a copy of it with tasks.”
↩︎ Broadcast variables: one read-only copy per node“explicitly creating broadcast variables is only useful when tasks across multiple stages need the same data”
↩︎ Broadcast variables: one read-only copy per node“To permanently release all resources used by the broadcast variable, call .destroy().”
↩︎ Broadcast variables: one read-only copy per node“Tasks running on a cluster can then add to it using the add method or the += operator. However, they cannot read its value.”
↩︎ Accumulators: tasks add, only the driver reads“Spark supports two types of shared variables: broadcast variables, which can be used to cache a value in memory on all nodes, and accumulators”
↩︎ Key concept“However, they cannot read its value.”
↩︎ Exam trap 1“the object v should not be modified after it is broadcast”
↩︎ Exam trap 3“Only the driver program can read the accumulator’s value, using its value method.”
↩︎ Prediction“accumulators, which are variables that are only “added” to, such as counters and sums”
↩︎ Checkpoint - 2.
“It is generally considered bad practice for UDFs to depend on mutable external variables”
↩︎ Ordinary variables are copied into every task“Python notebooks with Databricks Runtime version 14.3 and above, on standard compute”
↩︎ Where shared variables are unavailable on Databricks“In Spark Connect, Python UDFs are lazy. Their serialization and registration are deferred until execution time.”
↩︎ Where shared variables are unavailable on Databricks - 3.
“Marks a DataFrame as small enough for use in broadcast joins.”
↩︎ Broadcast variables: one read-only copy per node“Marks a DataFrame as small enough for use in broadcast joins.”
↩︎ Exam trap 2 - 4.
“sc.accumulator → DataFrame aggregation”
↩︎ Accumulators: tasks add, only the driver reads“sc.broadcast → broadcast join”
↩︎ Where shared variables are unavailable on Databricks - 5.
“Only Spark Connect APIs are supported. Spark RDD APIs are not supported.”
↩︎ Where shared variables are unavailable on Databricks“Only Spark Connect APIs are supported. Spark RDD APIs are not supported.”
↩︎ Exam trap 4
Also cited
- https://spark.apache.org/docs/latest/api/python/reference/api/pyspark.Broadcast.htmlSecondary source
“A broadcast variable created with SparkContext.broadcast(). Access its value through value.”
↩︎ Checkpoint