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.
- π§ 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
- Python 3.10+
- uv (for dependency management)
- Docker (required for execution mode - secure code isolation)
- Java 17 (for local Spark execution)
# 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__)"pip install spark-optima# Install PySpark in your environment
uv add pyspark # If using uv
# OR
pip install pyspark # If using pip| 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.
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.jsonExample 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
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.pyNote: Execution mode requires Docker for security isolation. Your Spark code runs in an isolated container.
Let Spark Optima guide you through the optimization process step by step:
uv run spark-optima wizardAnalyze 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 jsonExample Output:
π Spark Code Analysis
βββββββββββββ¬ββββββββββββ
β Operations Count β 2 β
β Code Smells β 2 β
β Recommendations β 2 β
βββββββββββββ΄ββββββββββββ
Code Smells
ββββββββββ¬ββββββββββββββββββ¬ββββββββββ
β Line β Type β Severity β
ββββββββββΌββββββββββββββββββΌββββββββββ€
β 12 β data_skew β medium β
β β _potential β β
ββββββββββ΄ββββββββββββββββββ΄ββββββββββ
List all supported platforms:
uv run spark-optima platforms listExport 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-synapseAnalyze 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-1234Optimize 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-csvAll 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 |
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}")βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β 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) β β
β βββββββββββββββββββββββββββββββββββββββββββββββ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
| 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 |
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
# 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# 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 -vNote: Do not run the full test suite more than once concurrently. Test execution takes time. For specific tests, you can run them in parallel.
# 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_optimaServe documentation locally with:
uv run mkdocs serveWe welcome contributions! Please see our Contributing Guide for details.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
- 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