- performance
- distributed-computing
Spark Optimization - Performance Tuning
Overview
The Spark Optimization skill focuses on diagnosing and fixing performance bottlenecks in Apache Spark jobs. This is a specialized, deep-focus skill for when you have a Spark job that's slow, consuming too much memory, or not scaling efficiently.
Use this skill when:
- A Spark job exceeds its SLA or budget
- You need to debug why a job is slower than expected
- You're optimizing for large-scale data processing
- Shuffles, skew, or memory pressure are causing failures
- You need to choose between partitioning strategies or join algorithms
Core Capabilities
- Performance Profiling: Read Spark UI, identify bottlenecks (shuffle, GC, serialization, I/O)
- Partitioning Optimization: Right-size partitions, implement skew handling, partition pruning
- Join Optimization: Choose between broadcast, sort-merge, and bucket joins based on data characteristics
- Memory Tuning: Optimize executor memory, cache strategy, and GC behavior
- Serialization: Configure Kryo, choose columnar formats for large data
- Caching Strategy: Identify what to cache, when to cache, and when to spill
When to Use
Workflow / Process
Phase 1: Diagnosis
- Enable Spark UI and run job to completion
- Analyze executor usage, task durations, and shuffle size
- Identify bottleneck: CPU, memory, I/O, or scheduling
Phase 2: Root Cause Analysis
- Check for data skew (uneven task durations)
- Review join strategy (broadcast vs sort-merge vs bucket)
- Analyze partition count and size
- Evaluate serialization and format choices
Phase 3: Optimization
- Apply targeted fix (e.g., repartition, broadcast join, caching)
- Measure impact: runtime, memory, cost
- Iterate if improvements insufficient
Phase 4: Validation
- Test with production data volume and characteristics
- Monitor side effects (new bottlenecks, memory pressure)
- Document optimization in runbook for future engineers
Constraints
Technical Constraints:
- Cannot fundamentally change data or algorithm (that's architect/pipeline-engineer role)
- Optimizations must not sacrifice correctness or data consistency
Scope Constraints:
- In Scope: Spark configuration tuning, query optimization, serialization, caching strategy
- Out of Scope: Infrastructure provisioning, algorithm redesign, non-Spark systems
Reference Examples
See examples/ directory for:
- Partitioning strategies and skew handling
- Join algorithm comparisons (broadcast, sort-merge, bucket)
- Memory tuning and caching patterns
- Serialization and format optimization
- Detailed Spark UI analysis walkthroughs
Version History:
## Configuration Cheat Sheet
```python
# Production configuration template
spark_configs = {
# Adaptive Query Execution (AQE)
"spark.sql.adaptive.enabled": "true",
"spark.sql.adaptive.coalescePartitions.enabled": "true",
"spark.sql.adaptive.skewJoin.enabled": "true",
# Memory
"spark.executor.memory": "8g",
"spark.executor.memoryOverhead": "2g",
"spark.memory.fraction": "0.6",
"spark.memory.storageFraction": "0.5",
# Parallelism
"spark.sql.shuffle.partitions": "200",
"spark.default.parallelism": "200",
# Serialization
"spark.serializer": "org.apache.spark.serializer.KryoSerializer",
"spark.sql.execution.arrow.pyspark.enabled": "true",
# Compression
"spark.io.compression.codec": "lz4",
"spark.shuffle.compress": "true",
# Broadcast
"spark.sql.autoBroadcastJoinThreshold": "50MB",
# File handling
"spark.sql.files.maxPartitionBytes": "128MB",
"spark.sql.files.openCostInBytes": "4MB",
}
Best Practices
Do's
- Enable AQE - Adaptive query execution handles many issues
- Use Parquet/Delta - Columnar formats with compression
- Broadcast small tables - Avoid shuffle for small joins
- Monitor Spark UI - Check for skew, spills, GC
- Right-size partitions - 128MB - 256MB per partition
Don'ts
- Don't collect large data - Keep data distributed
- Don't use UDFs unnecessarily - Use built-in functions
- Don't over-cache - Memory is limited
- Don't ignore data skew - It dominates job time
- Don't use
.count() for existence - Use .take(1) or .isEmpty()
Resources
1---2name: spark-optimization3description: Specialist in Apache Spark performance optimization—partitioning strategies, memory tuning, shuffle reduction, and job profiling for production systems. Use when optimizing Spark jobs, tuning performance, reducing costs, profiling applications, or scaling Spark workloads.4---5- performance6- distributed-computing78---910# Spark Optimization - Performance Tuning1112## Overview1314The Spark Optimization skill focuses on diagnosing and fixing performance bottlenecks in Apache Spark jobs. This is a specialized, deep-focus skill for when you have a Spark job that's slow, consuming too much memory, or not scaling efficiently.1516Use this skill when:1718- A Spark job exceeds its SLA or budget19- You need to debug why a job is slower than expected20- You're optimizing for large-scale data processing21- Shuffles, skew, or memory pressure are causing failures22- You need to choose between partitioning strategies or join algorithms2324## Core Capabilities2526- **Performance Profiling**: Read Spark UI, identify bottlenecks (shuffle, GC, serialization, I/O)27- **Partitioning Optimization**: Right-size partitions, implement skew handling, partition pruning28- **Join Optimization**: Choose between broadcast, sort-merge, and bucket joins based on data characteristics29- **Memory Tuning**: Optimize executor memory, cache strategy, and GC behavior30- **Serialization**: Configure Kryo, choose columnar formats for large data31- **Caching Strategy**: Identify what to cache, when to cache, and when to spill3233## When to Use3435## Workflow / Process3637### Phase 1: Diagnosis38391. Enable Spark UI and run job to completion402. Analyze executor usage, task durations, and shuffle size413. Identify bottleneck: CPU, memory, I/O, or scheduling4243### Phase 2: Root Cause Analysis44451. Check for data skew (uneven task durations)462. Review join strategy (broadcast vs sort-merge vs bucket)473. Analyze partition count and size484. Evaluate serialization and format choices4950### Phase 3: Optimization51521. Apply targeted fix (e.g., repartition, broadcast join, caching)532. Measure impact: runtime, memory, cost543. Iterate if improvements insufficient5556### Phase 4: Validation57581. Test with production data volume and characteristics592. Monitor side effects (new bottlenecks, memory pressure)603. Document optimization in runbook for future engineers6162## Constraints6364**Technical Constraints:**6566- Cannot fundamentally change data or algorithm (that's architect/pipeline-engineer role)67- Optimizations must not sacrifice correctness or data consistency6869**Scope Constraints:**7071- In Scope: Spark configuration tuning, query optimization, serialization, caching strategy72- Out of Scope: Infrastructure provisioning, algorithm redesign, non-Spark systems7374## Reference Examples7576See `examples/` directory for:7778- Partitioning strategies and skew handling79- Join algorithm comparisons (broadcast, sort-merge, bucket)80- Memory tuning and caching patterns81- Serialization and format optimization82- Detailed Spark UI analysis walkthroughs8384---8586**Version History:**8788- 1.0 (2026-01-24): Spark-focused optimization skill8990 skew_ratio = stats["max"] / stats["avg"]91 print(f"Skew ratio: {skew_ratio:.2f}x (>2x indicates skew)")9293```9495## Configuration Cheat Sheet9697```python98# Production configuration template99spark_configs = {100 # Adaptive Query Execution (AQE)101 "spark.sql.adaptive.enabled": "true",102 "spark.sql.adaptive.coalescePartitions.enabled": "true",103 "spark.sql.adaptive.skewJoin.enabled": "true",104105 # Memory106 "spark.executor.memory": "8g",107 "spark.executor.memoryOverhead": "2g",108 "spark.memory.fraction": "0.6",109 "spark.memory.storageFraction": "0.5",110111 # Parallelism112 "spark.sql.shuffle.partitions": "200",113 "spark.default.parallelism": "200",114115 # Serialization116 "spark.serializer": "org.apache.spark.serializer.KryoSerializer",117 "spark.sql.execution.arrow.pyspark.enabled": "true",118119 # Compression120 "spark.io.compression.codec": "lz4",121 "spark.shuffle.compress": "true",122123 # Broadcast124 "spark.sql.autoBroadcastJoinThreshold": "50MB",125126 # File handling127 "spark.sql.files.maxPartitionBytes": "128MB",128 "spark.sql.files.openCostInBytes": "4MB",129}130```131132## Best Practices133134### Do's135136- **Enable AQE** - Adaptive query execution handles many issues137- **Use Parquet/Delta** - Columnar formats with compression138- **Broadcast small tables** - Avoid shuffle for small joins139- **Monitor Spark UI** - Check for skew, spills, GC140- **Right-size partitions** - 128MB - 256MB per partition141142### Don'ts143144- **Don't collect large data** - Keep data distributed145- **Don't use UDFs unnecessarily** - Use built-in functions146- **Don't over-cache** - Memory is limited147- **Don't ignore data skew** - It dominates job time148- **Don't use `.count()` for existence** - Use `.take(1)` or `.isEmpty()`149150## Resources151152- [Spark Performance Tuning](https://spark.apache.org/docs/latest/sql-performance-tuning.html)153- [Spark Configuration](https://spark.apache.org/docs/latest/configuration.html)154- [Databricks Optimization Guide](https://docs.databricks.com/en/optimizations/index.html)