🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Data Skew Solutions

Apache SparkPerformance⭐ Premium

Data Skew Solutions

Difficulty: Senior Level | Companies: Databricks, Netflix, Uber, Apple, Airbnb

Understanding Data Skew

Data skew occurs when some partitions have significantly more data than others, causing straggler tasks that bottleneck the entire job.

Detecting Skew

python
from pyspark.sql import SparkSession, functions as F

spark = SparkSession.builder \
    .appName("DataSkew") \
    .config("spark.sql.adaptive.enabled", "true") \
    .config("spark.sql.adaptive.skewJoin.enabled", "true") \
    .getOrCreate()

# Detect skew by analyzing partition distribution
df = spark.read.parquet("hdfs://data/events")

# Check partition sizes
partition_stats = df \
    .withColumn("partition_id", F.spark_partition_id()) \
    .groupBy("partition_id") \
    .agg(
        F.count("*").alias("row_count"),
        F.sum(F.col("amount").isNotNull().cast("long")).alias("non_null_count")
    )

# Identify skewed partitions
mean_rows = partition_stats.agg(F.avg("row_count")).collect()[0][0]
stddev_rows = partition_stats.agg(F.stddev("row_count")).collect()[0][0]

skewed_partitions = partition_stats.filter(
    F.col("row_count") > mean_rows + 3 * stddev_rows
)

print(f"Skewed partitions: {skewed_partitions.count()}")
skewed_partitions.show()

â„šī¸

Interview Insight: Data skew is one of the most common performance issues in Spark. The key is to detect it early and apply the right mitigation strategy based on the skew pattern.

Skew Detection with Spark UI

python
# Monitor task execution times in Spark UI
# Look for:
# 1. Tasks with significantly longer execution times
# 2. Shuffle Read/Write imbalance across partitions
# 3. GC time variance across tasks

# Enable detailed task metrics
spark.conf.set("spark.eventLog.enabled", "true")
spark.conf.set("spark.eventLog.dir", "hdfs://logs/spark-events")

# Create a skewed dataset for demonstration
from pyspark.sql.types import StructType, StructField, StringType, IntegerType

schema = StructType([
    StructField("key", StringType(), True),
    StructField("value", IntegerType(), True)
])

# Create skewed data: one key has 10x more data
skewed_data = [(f"key_{i}", i) for i in range(1000)]  # Normal keys
skewed_data += [("skewed_key", i) for i in range(10000)]  # Skewed key

df = spark.createDataFrame(skewed_data, schema)

# This will show skew in task metrics
result = df.groupBy("key").agg(F.sum("value"))
result.explain(mode="formatted")

Solution 1: Salting

Salting adds a random prefix to the skewed key to distribute data evenly.

python
import random

# Salt the skewed key
def add_salt(df, salt_range=10):
    """Add random salt to handle skew"""
    salt_udf = F.udf(lambda: str(random.randint(0, salt_range - 1)))
    
    # Add salt column
    salted_df = df.withColumn("salt", salt_udf())
    
    # Combine original key with salt
    salted_df = salted_df.withColumn(
        "salted_key", 
        F.concat(F.col("key"), F.lit("_"), F.col("salt"))
    )
    
    return salted_df

# Apply salting to skewed dataset
df = spark.read.parquet("hdfs://data/skewed-events")
salted_df = add_salt(df, salt_range=10)

# Now group by salted key (evenly distributed)
result = salted_df.groupBy("salted_key").agg(F.sum("value").alias("partial_sum"))

# Remove salt and aggregate again
result = result \
    .withColumn("original_key", F.split(F.col("salted_key"), "_")[0]) \
    .groupBy("original_key") \
    .agg(F.sum("partial_sum").alias("total"))

result.show(20)

Advanced Salting for Joins

python
# Salt both sides of a join when one side is skewed
left = spark.read.parquet("hdfs://data/skewed-orders")
right = spark.read.parquet("hdfs://data/customers")

# Identify skewed keys in left table
skewed_keys = left \
    .groupBy("customer_id") \
    .agg(F.count("*").alias("count")) \
    .filter(F.col("count") > 10000) \
    .select("customer_id") \
    .collect()
skewed_keys = [row[0] for row in skewed_keys]

# Salt skewed keys in left table
salt_range = 10
salt_udf = F.udf(lambda: str(random.randint(0, salt_range - 1)))

left_salted = left.withColumn("salt", salt_udf())
left_salted = left_salted.withColumn(
    "join_key",
    F.when(
        F.col("customer_id").isin(skewed_keys),
        F.concat(F.col("customer_id"), F.lit("_"), F.col("salt"))
    ).otherwise(F.col("customer_id"))
)

# Expand right table for salted keys
from pyspark.sql.functions import explode, array

# Create multiple copies for skewed keys
right_expanded = right \
    .withColumn("salt_array", 
        F.when(F.col("customer_id").isin(skewed_keys),
            F.array([F.lit(str(i)) for i in range(salt_range)])
        ).otherwise(F.array(F.lit(None)))
    ) \
    .withColumn("salt", explode("salt_array")) \
    .withColumn("join_key",
        F.when(F.col("salt").isNotNull(),
            F.concat(F.col("customer_id"), F.lit("_"), F.col("salt"))
        ).otherwise(F.col("customer_id"))
    )

# Now join is balanced
result = left_salted.join(right_expanded, "join_key")

âš ī¸

Warning: Salting increases data volume by the salt factor. Use it only when skew is severe (>10x difference) and other solutions don't work.

Solution 2: Adaptive Query Execution (AQE)

Spark 3.x's AQE automatically handles skew.

python
# Enable AQE skew handling
spark = SparkSession.builder \
    .appName("AQESkewHandling") \
    .config("spark.sql.adaptive.enabled", "true") \
    .config("spark.sql.adaptive.skewJoin.enabled", "true") \
    .config("spark.sql.adaptive.skewJoin.skewedPartitionThresholdInBytes", "256MB") \
    .config("spark.sql.adaptive.skewJoin.skewedPartitionFactor", "5") \
    .getOrCreate()

# AQE automatically detects and handles skew
df = spark.read.parquet("hdfs://data/skewed-dataset")

result = df.groupBy("key").agg(F.sum("value"))

# AQE will:
# 1. Detect skewed partitions after shuffle
# 2. Split skewed partitions into smaller sub-partitions
# 3. Optimize join strategy based on runtime statistics

result.explain(mode="formatted")
# Look for "AdaptiveSparkPlan" in the plan

Solution 3: Broadcast Join

python
from pyspark.sql.functions import broadcast

# If the skewed side is the larger table, broadcast the other side
large_skewed = spark.read.parquet("hdfs://data/skewed-fact")  # Skewed
small_dimension = spark.read.parquet("hdfs://data/dimensions")  # Small

# Broadcast the small table to avoid shuffle
result = large_skewed.join(broadcast(small_dimension), "key")

# Check that broadcast was used
result.explain(mode="formatted")
# Look for "BroadcastHashJoin"

Solution 4: Repartitioning

python
# Pre-repartition data to avoid skew
df = spark.read.parquet("hdfs://data/events")

# Repartition by a different key to distribute evenly
df_repartitioned = df.repartition(200, "event_type")  # Instead of skewed "user_id"

# Or use random repartitioning
df_random = df.repartition(200)  # Random distribution

# For joins, repartition both sides
left = df.repartition(200, "join_key")
right = spark.table("other_table").repartition(200, "join_key")
result = left.join(right, "join_key")

Solution 5: Two-Phase Aggregation

python
# Split aggregation into two phases to handle skew
df = spark.read.parquet("hdfs://data/skewed-events")

# Phase 1: Partial aggregation with salt
salt_range = 10
salt_udf = F.udf(lambda: str(random.randint(0, salt_range - 1)))

salted = df.withColumn("salt", salt_udf())
partial = salted \
    .withColumn("salted_key", F.concat(F.col("key"), F.lit("_"), F.col("salt"))) \
    .groupBy("salted_key") \
    .agg(F.sum("value").alias("partial_sum"))

# Phase 2: Final aggregation without salt
result = partial \
    .withColumn("original_key", F.split(F.col("salted_key"), "_")[0]) \
    .groupBy("original_key") \
    .agg(F.sum("partial_sum").alias("total"))

result.show(20)

â„šī¸

Pro Tip: Two-phase aggregation is most effective for count/sum operations. For distinct operations, you may need a different approach.

Monitoring Skew in Production

python
# Monitor skew metrics continuously
spark = SparkSession.builder \
    .appName("SkewMonitoring") \
    .config("spark.eventLog.enabled", "true") \
    .config("spark.eventLog.dir", "hdfs://logs/spark-events") \
    .getOrCreate()

# Log skew metrics
def log_skew_metrics(df, operation_name):
    stats = df \
        .withColumn("partition_id", F.spark_partition_id()) \
        .groupBy("partition_id") \
        .agg(F.count("*").alias("row_count")) \
        .collect()
    
    counts = [row[1] for row in stats]
    if counts:
        max_count = max(counts)
        min_count = min(counts)
        avg_count = sum(counts) / len(counts)
        
        skew_ratio = max_count / avg_count if avg_count > 0 else 0
        
        print(f"{operation_name}:")
        print(f"  Max: {max_count}, Min: {min_count}, Avg: {avg_count:.0f}")
        print(f"  Skew ratio: {skew_ratio:.2f}")
        
        if skew_ratio > 3:
            print(f"  WARNING: Significant skew detected!")

# Use in pipeline
df = spark.read.parquet("hdfs://data/events")
log_skew_metrics(df, "Input")

result = df.groupBy("key").agg(F.sum("value"))
log_skew_metrics(result, "After aggregation")

â„šī¸

Key Takeaway: Data skew requires a multi-faceted approach: detect early, use AQE for automatic handling, apply salting for severe cases, and broadcast when possible. Always monitor skew metrics in production.

Follow-Up Questions

  • How does Spark's AQE skew detection work under the hood?
  • Explain the trade-offs between salting and broadcast joins for skew handling.
  • How would you handle skew in a streaming application?
  • Describe strategies for preventing skew in data ingestion pipelines.
  • How does skew affect dynamic allocation and resource utilization?

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type — Always start by categorizing the problem
  2. Incorrect formula application — Verify the formula applies to your specific case
  3. Unit errors — Always check units are consistent throughout
  4. Sign errors — Pay careful attention to positive and negative values
  5. Rounding too early — Keep full precision until the final answer
  6. Forgetting constraints — Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
🔒

Premium Content

Data Skew Solutions

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement