CertSafari
    Databricks Certified Associate Developer for Apache Spark· Lessons

    Domain 3 · Lesson 20/32

    Broadcast variables and accumulators in Spark

    Describe different types of variables in Spark, including broadcast variables and accumulators.

    14 min read
    3% of exam
    6 sources
    Published 21 Oct 2026
    Docs as of 17 Oct 2026

    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?

    Sources12

    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.

    Creating a broadcast variable and reading it back through valuepython
    >>> 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.

    The two shared variable types side by side
    PropertyBroadcast variableAccumulator
    Created on the driver withSparkContext.broadcast(v)SparkContext.accumulator(v)
    What tasks can doRead it through valueAdd to it with add or +=
    Who reads the resultEvery task, from its node's cached copyOnly the driver, through value
    Direction of dataDriver to executorsExecutors to driver
    Cleanupunpersist() 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?

    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?

    Sources13

    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.

    An accumulator updated inside foreach, an action, and read on the driver afterwardspython
    >>> 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
    10

    Whether 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.

    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?

    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")))

    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?

    Sources14

    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)?

    Sources524

    Sources

    (6)

    Every claim above is drawn from one of these pages, quoted as it was written on the date shown.

    1. 1.
      “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. 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. 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. 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

    Ready to test yourself?

    Practise Databricks Certified Associate Developer for Apache Spark in quiz mode.

    Spotted a mistake, or was something unclear? Tell us.