Skip to content

About

Intelligent Apache Spark Configuration Optimization Tool

Topics

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Latest commit

Β 

History

108 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ”₯ Spark Optima

Python Version License Code style: ruff Pre-commit

Intelligent Apache Spark Configuration Optimization Tool

Spark Optima is a professional, production-ready tool that automatically finds the optimal Apache Spark configuration for your specific workload. Using a hybrid approach combining heuristic rules and Bayesian optimization, it eliminates the guesswork and tedious trial-and-error from Spark tuning.


✨ Features

  • 🧠 Hybrid Optimization: Combines Spark best practices with intelligent Bayesian search
  • βš–οΈ Multi-Objective Optimization: Optimize for time and cost simultaneously with a Pareto frontier of trade-offs
  • 🎯 Multi-Platform Support: Local, AWS Glue, AWS EMR, Databricks, Azure Synapse, GCP Dataproc, Kubernetes (7 platforms)
  • πŸ“Š Code Analysis: Detects Spark code smells (DataFrame and spark.sql() SQL via sqlglot) and suggests improvements
  • πŸ“œ Post-Run Analysis: Parse Spark event logs or query a Spark History Server for GC, shuffle, spill, and skew metrics plus tuning hints
  • πŸ€– ML Surrogate Model: Optional scikit-learn model learns from real runs to sharpen simulation estimates
  • πŸ’° Live Cloud Pricing: Opt-in live on-demand rates (AWS Pricing API, Azure Retail Prices, GCP Cloud Billing) with caching and static fallback
  • 🌐 Async REST API: FastAPI with background optimization jobs, webhooks, and pluggable job stores (memory, SQLite, Redis)
  • πŸ“‹ Workload Templates: Curated baselines for batch ETL, streaming, ML training, and interactive analytics
  • πŸš€ Dual Mode: Fast simulation mode or real execution mode with actual measurements
  • πŸ”’ Secure Execution: Docker-based isolation for untrusted code execution
  • πŸ“‹ 200+ Config Parameters: Comprehensive coverage of Spark 3.x and 4.x configurations
  • πŸ”§ Professional Grade: Docker-ready, Kubernetes-ready, production-ready

πŸš€ Quick Start

Prerequisites

  • Python 3.10+
  • uv (for dependency management)
  • Docker (required for execution mode - secure code isolation)
  • Java 17 (for local Spark execution)

Installation

Option 1: Using uv (Recommended for development)

# Clone the repository
git clone https://github.com/yildirimarda/spark-optima.git
cd spark-optima

# Install with uv
uv sync

# Verify installation
uv run python -c "import spark_optima; print(spark_optima.__version__)"

Option 2: Using pip (Simple installation)

pip install spark-optima

Install PySpark (Required for execution mode)

# Install PySpark in your environment
uv add pyspark  # If using uv
# OR
pip install pyspark  # If using pip

πŸ”§ Local Usage Guide

CLI Commands at a Glance

Command What it does
optimize Find the optimal Spark configuration for your code, platform, and data
analyze Detect code smells and improvement opportunities in Spark code (no optimization)
analyze-log Analyze a finished run from an event log file or a Spark History Server (--history-server URL)
wizard Interactive step-by-step optimization wizard
export Convert a saved result to platform formats (databricks-json, aws-glue, azure-synapse, emr, kubernetes, airflow, env, properties, pareto-json, pareto-csv, ...)
history Browse past optimization runs stored in the local history database
compare Diff two optimization result files
explain Explain the rationale behind each parameter in a result
pareto Display the Pareto frontier of a multi-objective result
validate Validate a spark-defaults.conf / JSON config against the parameter database and platform constraints
import Import an existing Spark config, optimize, and diff current vs. recommended
templates List curated workload templates or inspect one (--show etl-batch)
platforms list List supported platforms and their constraints

Run uv run spark-optima <command> --help for full options.

1. Basic Optimization (Simulation Mode)

Simulation mode works out-of-the-box without Docker or Spark installation. It uses intelligent heuristics + Bayesian optimization to predict optimal configurations.

# Basic usage with your Spark code
uv run spark-optima optimize \
  --code-path /tmp/simple_spark_job.py \
  --platform local \
  --data-size 10 \
  --max-memory 16

# With JSON output (save for later export)
uv run spark-optima optimize \
  --code-path /tmp/simple_spark_job.py \
  --platform local \
  --data-size 5 \
  --output json > result.json

Example Output:

πŸ”₯ Spark Optima
Intelligent Spark Configuration Optimization

              Input Parameters
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Code Path     β”‚ /tmp/simple_spark_job.py β”‚
β”‚ Platform      β”‚ local                    β”‚
β”‚ Spark Version β”‚ 3.5.0                    β”‚
β”‚ Data Size     β”‚ 10.0 GB                  β”‚
β”‚ Data Format   β”‚ parquet                  β”‚
β”‚ Max Memory    β”‚ 16.0 GB                  β”‚
β”‚ Mode          β”‚ simulation               β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

⏱  Estimated Execution Time: 13.3 minutes
🎯 Confidence Score: 85%
πŸ’° Estimated Cost: $0.00

πŸ”§ TOP CONFIGURATION PARAMETERS
──────────────────────────────────────────────
  spark.executor.memory                         = 4g
  spark.executor.cores                         = 4
  spark.driver.memory                          = 1g
  spark.sql.adaptive.enabled                    = True
  spark.sql.shuffle.partitions                = 200
  spark.dynamicAllocation.enabled              = True

2. Execution Mode (Real Spark Measurements)

Execution mode runs your actual Spark code with different configurations in isolated Docker containers and measures real performance.

Prerequisites:

  • Docker must be installed and running
  • Docker image must be built
# Build Docker image (first time only)
docker build -f docker/Dockerfile -t spark-optima:latest .

# Run optimization with execution mode
uv run spark-optima optimize \
  --code-path /tmp/simple_spark_job.py \
  --platform local \
  --data-size 1 \
  --max-memory 4 \
  --mode execution

# Quick test with minimal trials
uv run python /tmp/test_execution.py

Note: Execution mode requires Docker for security isolation. Your Spark code runs in an isolated container.

3. Interactive Wizard

Let Spark Optima guide you through the optimization process step by step:

uv run spark-optima wizard

4. Code Analysis

Analyze your Spark code for optimization opportunities without running optimization:

uv run spark-optima analyze --code-path /tmp/simple_spark_job.py

# JSON output
uv run spark-optima analyze --code-path /tmp/simple_spark_job.py --output json

Example Output:

πŸ” Spark Code Analysis

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Operations Count β”‚ 2         β”‚
β”‚ Code Smells      β”‚ 2         β”‚
β”‚ Recommendations  β”‚ 2         β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

Code Smells
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ Line   β”‚ Type            β”‚ Severity β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”Όβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ 12     β”‚ data_skew       β”‚ medium   β”‚
β”‚        β”‚ _potential      β”‚          β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

5. Platform Management

List all supported platforms:

uv run spark-optima platforms list

6. Export Configuration

Export your optimization results to various platform-specific formats:

# Export to Databricks cluster JSON
uv run spark-optima export \
  --result-file result.json \
  --format databricks-json \
  --output cluster.json

# Export to AWS Glue
uv run spark-optima export \
  --result-file result.json \
  --format aws-glue

# Export as environment variables
uv run spark-optima export \
  --result-file result.json \
  --format env \
  --output spark_env.sh

# Export as spark-submit command
uv run spark-optima export \
  --result-file result.json \
  --format spark-submit

# Export to Azure Synapse Spark pool config
uv run spark-optima export \
  --result-file result.json \
  --format azure-synapse

7. Post-Run Analysis (Event Logs & History Server)

Analyze a finished Spark run to get GC, shuffle, spill, and skew metrics plus tuning advice:

# From an event log file (plain JSON lines or .gz)
uv run spark-optima analyze-log -l ./application_1234_eventlog

# From a running Spark History Server
uv run spark-optima analyze-log --history-server http://localhost:18080 --app-id app-1234

8. Multi-Objective Optimization (Pareto)

Optimize for time and cost at once, then inspect the trade-off frontier:

uv run spark-optima optimize \
  --code-path job.py --platform aws_glue --data-size 200 \
  --objective minimize_time --objective minimize_cost \
  --output json > result.json

uv run spark-optima pareto -r result.json
uv run spark-optima export -r result.json -f pareto-csv

βš™οΈ Environment Variables

All settings are optional β€” Spark Optima works out of the box with sensible defaults.

Variable Purpose Default
SPARK_OPTIMA_HISTORY_DB Path of the local optimization-history SQLite database (history command) ~/.spark_optima/history.db
SPARK_OPTIMA_MODEL_DIR Directory for trained ML surrogate models ~/.spark_optima/models
SPARK_OPTIMA_JOB_STORE REST API job store backend: memory, sqlite, or redis memory
SPARK_OPTIMA_JOB_DB SQLite job store database path (when JOB_STORE=sqlite) ~/.spark_optima/jobs.db
SPARK_OPTIMA_REDIS_URL Redis connection URL (when JOB_STORE=redis) redis://localhost:6379/0
SPARK_OPTIMA_API_KEYS Comma-separated API keys; setting this enables X-API-Key auth on the REST API disabled
SPARK_OPTIMA_RATE_LIMIT Requests-per-minute budget for the REST API (opt-in) disabled
SPARK_OPTIMA_LIVE_PRICING Set to 1/true to fetch live cloud pricing instead of the static price tables disabled
SPARK_OPTIMA_PRICING_CACHE Live pricing cache file path ~/.spark_optima/pricing_cache.json
SPARK_OPTIMA_PRICING_TTL_HOURS Live pricing cache time-to-live in hours 24
SPARK_OPTIMA_GCP_API_KEY Google Cloud Billing Catalog API key (required for GCP Dataproc live pricing) unset
SPARK_OPTIMA_HOST REST API bind host 127.0.0.1
SPARK_OPTIMA_PORT REST API bind port 8000

🐍 Python API

from pathlib import Path
from spark_optima import Optimizer
from spark_optima.platforms.models import ResourceSpec

# Initialize optimizer
optimizer = Optimizer(
    platform="databricks",
    spark_version="3.5.0",
    optimization_mode="simulation",  # or "execution"
)

# Define resources
resources = ResourceSpec(
    cpu_cores=16,
    memory_gb=64,
)

# Define data profile
data_profile = {
    "size_gb": 100,
    "format": "parquet",
    "compression": "snappy",
}

# Run optimization
result = optimizer.optimize(
    code_path="./my_spark_job.py",
    resources=resources,
    data_profile=data_profile,
    use_bayesian=True,
    bayesian_trials=50,
    objectives=["minimize_time"],
)

# Access results
print(f"Optimal config: {result.configuration}")
print(f"Estimated time: {result.estimated_time_minutes:.1f} min")
print(f"Confidence: {result.confidence_score:.0%}")

# Get code suggestions
for suggestion in result.code_suggestions:
    print(f"Line {suggestion.line_number}: {suggestion.issue_type}")
    print(f"  Suggestion: {suggestion.suggestion}")

πŸ—οΈ Architecture

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                    Spark Optima Engine                       β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”‚
β”‚  β”‚   Input     β”‚  β”‚   Code      β”‚  β”‚  Hybrid Optimizer   β”‚  β”‚
β”‚  β”‚ Collection  β”‚β†’ β”‚  Analysis   β”‚β†’ β”‚ (Heuristic + Bayes) β”‚  β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β”‚
β”‚                                           ↓                  β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚
β”‚  β”‚              Simulation / Execution                  β”‚    β”‚
β”‚  β”‚         (Performance Measurement & Feedback)         β”‚    β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚
β”‚                                           ↓                  β”‚
β”‚  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”    β”‚
β”‚  β”‚          Optimal Configuration Output                β”‚    β”‚
β”‚  β”‚  (JSON, YAML, Platform-specific formats, Code fixes) β”‚    β”‚
β”‚  β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ“‹ Supported Platforms

Platform Status Notes
Local/Standalone βœ… Ready Full support with Docker
AWS Glue βœ… Ready Including Glue 3.0/4.0
Databricks βœ… Ready DBR 10.x - 14.x
Azure Synapse βœ… Ready Node sizes: Small to XXLarge
AWS EMR βœ… Ready EMR 6.9 - 7.5 on EC2 (m5/r5/c5)
GCP Dataproc βœ… Ready Image 2.0 - 2.2 (n2-standard/highmem)
Kubernetes βœ… Ready Spark-on-K8s + Spark Operator CRD

πŸ“¦ Project Structure

spark-optima/
β”œβ”€β”€ src/spark_optima/          # Main source code
β”‚   β”œβ”€β”€ core/                  # Core optimization engine
β”‚   β”‚   β”œβ”€β”€ optimizer.py      # Main optimizer class
β”‚   β”‚   β”œβ”€β”€ config_engine/   # Spark config knowledge base
β”‚   β”‚   β”œβ”€β”€ bayesian/        # Bayesian optimization (Optuna)
β”‚   β”‚   β”œβ”€β”€ simulation/      # Performance simulator
β”‚   β”‚   └── execution/      # Real Spark execution
β”‚   β”œβ”€β”€ platforms/             # Platform adapters
β”‚   β”œβ”€β”€ analysis/              # Code analysis
β”‚   β”œβ”€β”€ cli/                    # Command-line interface
β”‚   β”œβ”€β”€ api/                    # REST API (FastAPI)
β”‚   └── data/                  # Sample data & profiling
β”œβ”€β”€ tests/                     # Test suite
β”œβ”€β”€ docker/                    # Docker configurations
β”œβ”€β”€ docs/                      # Documentation
β”œβ”€β”€ kubernetes/                # K8s manifests & Helm charts
└── examples/                  # Usage examples

πŸ› οΈ Development

Setup Development Environment

# Clone repository
git clone https://github.com/yildirimarda/spark-optima.git
cd spark-optima

# Install dependencies with uv
uv sync

# Install pre-commit hooks
uv run pre-commit install

Running Tests

# Run all tests (takes a while, be patient)
uv run pytest

# Run with coverage
uv run pytest --cov=src/spark_optima --cov-report=html

# Run specific test categories
uv run pytest -m unit -v          # Unit tests only
uv run pytest -m integration -v   # Integration tests only

# Run a specific test file
uv run pytest tests/unit/test_optimizer.py -v

Note: Do not run the full test suite more than once concurrently. Test execution takes time. For specific tests, you can run them in parallel.

Code Quality

# Linting
uv run ruff check .
uv run ruff check . --fix  # Auto-fix issues

# Formatting
uv run ruff format .

# Type checking
uv run mypy src/spark_optima

# Security scan
uv run bandit -r src/spark_optima

πŸ“– Documentation

Serve documentation locally with:

uv run mkdocs serve

🀝 Contributing

We welcome contributions! Please see our Contributing Guide for details.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“ License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.


πŸ™ Acknowledgments

  • Apache Spark community for the excellent documentation
  • Optuna team for the Bayesian optimization framework
  • All contributors who helped make this project possible

Made with ❀️ by the Spark Optima Contributors

About

Intelligent Apache Spark Configuration Optimization Tool

Topics

Resources

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages