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.
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
broadcastmethod ofSparkContextcreates a broadcast variable used through.valuein classic Spark task code. The input is a local value, not an RDD or DataFrame computation. - The
broadcastfunction frompyspark.sql.functionsmarks 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
-
easy
-
medium
-
medium
-
medium
-
hard
-
hard