What is broadcasting in PySpark and when would you use it?

Instruction: Describe the concept of broadcasting in PySpark and provide a scenario where it is beneficial.

Context: This question is designed to assess the candidate's understanding of broadcasting in PySpark and their ability to apply it to optimize data processing tasks.

Updated

Broadcasting distributes a read-only value or a small join side to the executors that need it. It creates copies and consumes memory; it does not distribute an arbitrarily large dataset without replication.

Two APIs serve different purposes:

  • The broadcast method of SparkContext creates a broadcast variable used through .value in classic Spark task code. The input is a local value, not an RDD or DataFrame computation.
  • The broadcast function from pyspark.sql.functions marks a DataFrame as a broadcast-join candidate. Spark plans and materializes that join side; the hint is not a general shared Python variable.

With an existing SparkSession named spark, a small product dimension can enrich transactions:

from pyspark.sql import functions as F

transactions = spark.createDataFrame([(1, 2), (2, 1), (3, 9)],
                                     "transaction_id int, product_id int")
products = spark.createDataFrame([(1, "Book"), (2, "Pen")],
                                 "product_id int, product string")
enriched = transactions.join(F.broadcast(products), "product_id", "left")
assert [(r.transaction_id, r.product) for r in
        enriched.orderBy("transaction_id").collect()] == [
    (1, "Pen"), (2, "Book"), (3, None)]

A broadcast join can avoid repartitioning the large input for this join, but broadcasting itself still transfers data. Check the materialized build-side size, available memory, timeout and final plan; a hint does not support every join type or make an oversized relation safe. Duplicate dimension keys still multiply matches. Use broadcast-variable cleanup methods when a variable is no longer needed, and do not mutate its value as shared state. Broadcast variables, Join strategy hints

Related Questions