spark-optimization
wshobson/agents
Optimize Apache Spark jobs with partitioning, caching, shuffle optimization, and memory tuning.
What is spark-optimization?
This skill provides production patterns for optimizing Apache Spark jobs, including partitioning strategies, memory management, shuffle optimization, and performance tuning. Use it when improving Spark performance, debugging slow jobs, or scaling data processing pipelines.
- Enable Adaptive Query Execution (AQE) and coalesce partitions automatically
- Implement efficient partitioning strategies and right-size partition counts
- Optimize shuffle operations and handle data skew with salting and broadcast joins
- Configure memory management, executor settings, and Kryo serialization
- Monitor and debug Spark performance using the Spark UI
- Use columnar formats (Parquet/Delta) with compression for efficient data storage
How to install spark-optimization
npx skills add https://github.com/wshobson/agents --skill spark-optimization- Apache Spark installed and configured
- Python with PySpark library
- Access to Spark cluster or local Spark environment
- Basic understanding of Spark execution model (jobs, stages, tasks)
How to use spark-optimization
- 1.Create a SparkSession with optimized configurations (AQE enabled, Kryo serializer, appropriate shuffle partitions)
- 2.Read data using efficient formats like Parquet with schema inference disabled
- 3.Apply filters early to reduce data volume before transformations
- 4.Use built-in SQL functions instead of UDFs when possible
- 5.Implement broadcast joins for small tables to avoid shuffles
- 6.Monitor the Spark UI to identify bottlenecks like data skew, GC pressure, and spills
- 7.Write results to columnar formats (Parquet/Delta) with appropriate partitioning
Use cases
- Optimizing slow-running Spark jobs by identifying and reducing shuffle operations
- Tuning executor memory and partition counts for large-scale data processing pipelines
- Debugging performance issues by analyzing Spark UI metrics for data skew and GC pressure
- Implementing broadcast joins for small table joins to avoid expensive shuffles
- Scaling Spark applications to handle larger datasets without memory spills or task failures
- Data engineers optimizing Spark pipelines
- Data scientists scaling machine learning jobs on Spark
- DevOps engineers tuning Spark cluster configurations
- Analytics engineers improving ETL job performance
spark-optimization FAQ
Enable AQE by default in production. Set `spark.sql.adaptive.enabled` to `true`. AQE automatically handles partition coalescing, skew joins, and other optimizations without manual tuning.
Use salting (add random prefix to skewed keys before grouping), implement broadcast joins for small tables, or enable `spark.sql.adaptive.skewJoin.enabled`. Monitor the Spark UI to identify which keys are causing skew.
Aim for 128MB-256MB per partition. Set `spark.sql.shuffle.partitions` based on your cluster size and data volume. Too few partitions reduce parallelism; too many cause overhead.
Cache selectively only when a DataFrame is reused multiple times. Over-caching wastes memory and can cause spills. Monitor memory usage in the Spark UI and use `.unpersist()` when done.
Check the Spark UI for data skew (uneven task durations), excessive shuffles, GC pauses, or memory spills. Use columnar formats, enable AQE, and avoid collecting large data to the driver.
Full instructions (SKILL.md)
Source of truth, from wshobson/agents.
name: spark-optimization description: Optimize Apache Spark jobs with partitioning, caching, shuffle optimization, and memory tuning. Use when improving Spark performance, debugging slow jobs, or scaling data processing pipelines.
Apache Spark Optimization
Production patterns for optimizing Apache Spark jobs including partitioning strategies, memory management, shuffle optimization, and performance tuning.
When to Use This Skill
- Optimizing slow Spark jobs
- Tuning memory and executor configuration
- Implementing efficient partitioning strategies
- Debugging Spark performance issues
- Scaling Spark pipelines for large datasets
- Reducing shuffle and data skew
Core Concepts
1. Spark Execution Model
Driver Program
↓
Job (triggered by action)
↓
Stages (separated by shuffles)
↓
Tasks (one per partition)
2. Key Performance Factors
| Factor | Impact | Solution |
|---|---|---|
| Shuffle | Network I/O, disk I/O | Minimize wide transformations |
| Data Skew | Uneven task duration | Salting, broadcast joins |
| Serialization | CPU overhead | Use Kryo, columnar formats |
| Memory | GC pressure, spills | Tune executor memory |
| Partitions | Parallelism | Right-size partitions |
Quick Start
from pyspark.sql import SparkSession
from pyspark.sql import functions as F
# Create optimized Spark session
spark = (SparkSession.builder
.appName("OptimizedJob")
.config("spark.sql.adaptive.enabled", "true")
.config("spark.sql.adaptive.coalescePartitions.enabled", "true")
.config("spark.sql.adaptive.skewJoin.enabled", "true")
.config("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
.config("spark.sql.shuffle.partitions", "200")
.getOrCreate())
# Read with optimized settings
df = (spark.read
.format("parquet")
.option("mergeSchema", "false")
.load("s3://bucket/data/"))
# Efficient transformations
result = (df
.filter(F.col("date") >= "2024-01-01")
.select("id", "amount", "category")
.groupBy("category")
.agg(F.sum("amount").alias("total")))
result.write.mode("overwrite").parquet("s3://bucket/output/")
Detailed patterns and worked examples
Detailed pattern documentation lives in references/details.md. Read that file when the navigation tier above is insufficient.
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()
Related skills
More from wshobson/agents and the wider catalog.

spark-training-gotchas
Diagnose the ten known failure modes for ML training on NVIDIA DGX Spark before they waste hours.

sql-optimization-patterns
Master SQL query optimization, indexing strategies, and EXPLAIN analysis to eliminate slow queries.

startup-financial-modeling
Build 3-5 year financial models with revenue projections, cost structures, cash flow analysis, and scenario planning for early-stage startups.

startup-metrics-framework
Track and optimize key startup metrics from seed through Series A across SaaS, marketplace, consumer, and B2B models.

stride-analysis-patterns
Apply STRIDE methodology to systematically identify threats across authentication, integrity, confidentiality, availability, and authorization.

stripe-integration
Implement Stripe payment processing with checkout, subscriptions, and webhooks for PCI-compliant payment flows.