Cert EspressoLearn. Practise. Find your flow.

A LITTLE FOCUS.
A BIG NEXT STEP.

Your pace. Your space.
Databricks · Databricks Spark Developer Associate

UDFs, State, Broadcast Variables, Accumulators

Databricks Spark Developer Associate · Lesson 12 of 18 · 1:34:21

YouTube loads only after you press play. This chapter opens at its timestamp in the full course. Watch on YouTube ↗

Learning with these videos? Subscribe for new courses and exam-style questions.

In this lesson

Prepare for the Databricks Certified Associate Developer for Apache Spark exam. In this lesson: Python UDFs and spark.udf.register, stateless and stateful operations with the state store, broadcast variables, and accumulators. Includes three original practice questions.

Study notes

The text of this lesson, to read at your own pace. Information as of November 2026.

Custom rules, live state, shared values

Coralpeak computes a loyalty tier with its own Python rules, keeps a running count for each player in a live stream, shares a small lookup table with every task, and counts the malformed records it skips. Each of these needs a different tool, with its own cost. This lesson covers user defined functions, stateless and stateful operations, broadcast variables, and accumulators.

User defined functions

A user defined function, or UDF, wraps your own Python function so that Spark can apply it to a column, with the udf function and a return type, or with the udf decorator. To call it from SQL, you register it with spark.udf.register, under a name. A Python UDF runs row by row in a Python worker, so Spark must convert every value between the executor and Python, which is slow. It is also a black box for the optimizer, which cannot look inside it, so a built-in function is the better choice whenever one exists. When you do need Python, a pandas UDF, or a UDF with Arrow turned on, processes the data in batches, which is much faster.

Stateless and stateful operations

A stateless operation handles each row on its own, like a filter, a select, or a UDF, so it scales out easily, and needs nothing from earlier rows. In Structured Streaming, a stateful operation must remember something between micro-batches, such as a running count, a window that is still open, or the keys already seen for deduplication. Spark keeps that state in a state store: a versioned key-value store on each executor, saved with the checkpoint, so a restarted query picks up where it stopped. The default provider keeps the state in executor memory, while the RocksDB provider keeps it in a local database, which suits a very large state. For your own logic with state, Spark offers mapGroupsWithState and flatMapGroupsWithState, applyInPandasWithState in Python, and, in newer releases, transformWithState.

Broadcast variables

A broadcast variable sends a read only value, such as a small lookup dictionary, to every executor once, instead of with every task. You create it on the driver with the broadcast method of the SparkContext, which a Spark Connect session does not expose, and tasks read it through its value attribute. It is cached on each machine, so it must stay small, and you must not change it after creating it, so that every node sees the same value. unpersist frees the copies on the executors, and destroy removes the variable for good.

Accumulators

An accumulator goes the other way: tasks on the executors add to it, and only the driver reads its value. You create it on the driver with the accumulator method of the SparkContext, with a starting value such as zero, and tasks call add, or use the plus equals operator. Tasks cannot read the value, so an accumulator is meant for counters and sums, like the number of malformed records skipped. Inside an action, such as foreach, Spark applies the update of each task only once, even if the task is restarted. Inside a transformation, an update can be applied more than once, when a task or a stage runs again, so the total may be too high.

Recap

Let's recap. A Python UDF wraps your own function, and spark.udf.register makes it callable from SQL. Python UDFs are slow and opaque to the optimizer, so prefer a built-in function, or a pandas UDF. Stateful operations, like streaming aggregations and deduplication, keep their state in a state store, saved with the checkpoint. A broadcast variable is a read only value, sent once to each executor. And tasks only add to an accumulator, which the driver reads, and only updates inside actions are counted exactly once.

Quick checks for this lesson

The 3 questions of this lesson, as plain text. The button above runs them with shuffled choices and the reason behind every choice.

  1. A developer wraps a simple conversion to upper case in a Python UDF, and the job becomes slow. What is the best fix?

    • Use the built-in upper() function instead
    • Register the UDF with spark.udf.register
    • Cache the DataFrame before calling the UDF
    • Add more partitions with repartition()
    Show the answer

    Use the built-in upper() function instead

    The built-in function runs inside the engine, with no transfer to Python, and the optimizer understands it. “Register the UDF with spark.udf.register” only makes the UDF callable from SQL, and it stays just as slow. “Cache the DataFrame before calling the UDF” would store the input, but every row would still go through Python. And “Add more partitions with repartition()” would spread the same slow work, without removing it.

  2. Which of these operations, in a streaming query, needs a state store?

    • filter(col("amount") > 0)
    • withColumn("tier", tier("total"))
    • dropDuplicates(["event_id"])
    • select("event_id", "ts", "amount")
    Show the answer

    dropDuplicates(["event_id"])

    Deduplication in a stream must remember the event IDs already seen, and that memory is state. “filter(col("amount") > 0)” is a filter, which handles each row on its own, with no state. “withColumn("tier", tier("total"))” is also stateless, since the UDF sees one row at a time. And “select("event_id", "ts", "amount")” only picks columns, row by row.

  3. A job counts malformed rows with an accumulator updated inside a UDF, in a withColumn call, and the count is sometimes too high. Why?

    • The tasks read the value and add it twice
    • Updates in a transformation can be applied again when a task reruns
    • Accumulators only count distinct values
    • The driver resets the value at every stage
    Show the answer

    Updates in a transformation can be applied again when a task reruns

    Only the updates made inside actions are guaranteed to count once, so a task that runs again inside a transformation adds again. “The tasks read the value and add it twice” is wrong, since tasks cannot read an accumulator. “Accumulators only count distinct values” is wrong, since an accumulator simply adds what it receives. And “The driver resets the value at every stage” is wrong, since the driver does not reset it.