🎬No video for this question yet. The written answer is below.
Narrow and Broadcast Transformations
📝 Answer
Interviewer:
Can you explain Narrow Transformations and Broadcast Transformations in Spark with real-time examples?
Candidate:
So basically, when I think about transformations in Spark, I try to understand how data moves across the cluster, because that directly impacts performance.
Let me start with Narrow Transformations.
A narrow transformation is one where each partition of the output depends only on a single partition of the input. So there is no data shuffle across nodes.
In simple terms, data stays within the same partition.
Examples are map, filter, and select.
In one of my projects, I was filtering large datasets based on conditions like date or status. These operations were very fast because they were narrow transformations and did not involve any data movement.
Now coming to Broadcast Transformations, or more accurately broadcast joins.
This is a technique used to optimize joins.
Instead of shuffling both datasets, we broadcast the smaller dataset to all nodes.
So each node gets a copy of the smaller dataset, and the join happens locally.
In my project, I had a large sales dataset and a small lookup table for product details.
Initially, I used a normal join, and it was slow due to shuffle.
Then I applied broadcast join to the small table, and performance improved significantly.
So basically, narrow transformations are about avoiding shuffle, and broadcast joins are about reducing shuffle during joins.
Let me show a quick example.
# Narrow Transformation filtered_df = df.filter(df["price"] > 1000) # Broadcast Join from pyspark.sql.functions import broadcast result_df = large_df.join(broadcast(small_df), "id")
One important thing I learned is… performance in Spark is all about minimizing data movement.
So whenever possible, I try to use narrow transformations and optimized joins like broadcast.
Also, I always check the execution plan to confirm whether shuffle is happening or not.
Interviewer (Follow-up):
That’s good. Can you explain what Wide Transformations are and how they impact performance?