

Running distributed Spark workloads on HPC clusters is a common task in bioinformatics and data science. Integrating Spark with SLURM, the dominant HPC job scheduler, takes some care: compute resources must be allocated through SLURM, a Spark master has to be started, worker processes coordinated, and dependencies such as Java, PySpark and Python made available on every node. This post describes a reproducible way to run Spark clusters on SLURM using Pixi for environment management and sparkhpc for orchestration, based on the gkit Spark-on-SLURM implementation.
On most HPC clusters, SLURM controls resource allocation and job execution. To run Spark:
Without an orchestration layer, the setup is often done by hand:
# Manually request resourcessalloc -N 2 -c 4 --time=00:30:00
# SSH to first node, start Spark master manuallyssh node1SPARK_HOME=/opt/spark ./bin/spark-class org.apache.spark.deploy.master.Master
# SSH to second node, start worker manuallyssh node2SPARK_HOME=/opt/spark ./bin/spark-class org.apache.spark.deploy.worker.Worker \ spark://node1:7077 --cores 4
# Run your driver scriptpython my_analysis.py
# Manual cleanup# Kill processes if they're still running...Problems:
# Single command sets everything up with reproducible dependenciesmake setup
# Single command runs the entire workflowmake exampleBehind the scenes:
┌─────────────────────────────────────────────┐│ User Machine (submit dir) ││ ┌───────────────────────────────────────┐ ││ │ Python Driver (run_example.py) │ ││ └───────────────────────────────────────┘ │└─────────────────────────────────────────────┘ ↓ (sparkhpc.submit())┌─────────────────────────────────────────────┐│ SLURM Controller ││ (sbatch sparkjob.slurm.template) │└─────────────────────────────────────────────┘ ↓ (srun)┌─────────────────────────────────────────────┐│ Spark Master (Node 1) ││ Spark Workers (Nodes 1-N via srun) ││ ││ Environment: Python, Java, PySpark ││ (from Pixi) │└─────────────────────────────────────────────┘spark-on-slurm/├── pixi.toml # Environment definition├── Makefile # User entry points├── sparkhpc/│ ├── run_example.py # End-to-end workflow│ ├── sparkhpc/│ │ ├── sparkjob.py # Base Spark job class│ │ ├── slurmsparkjob.py # SLURM-specific implementation│ │ └── templates/│ │ └── sparkjob.slurm.template # SLURM batch script template│ └── scripts/└── sparkhpc.log # Cluster logsPixi is a cross-platform package manager that creates reproducible environments. Unlike venv or conda, Pixi locks all transitive dependencies, which helps keep setups identical across machines.
[workspace]authors = ["Vieomics"]channels = ["conda-forge", "bioconda"]name = "spark-on-slurm"platforms = ["linux-64"]version = "0.1.0"
[tasks]sparkhpc-example = "python sparkhpc/run_example.py"
[dependencies]python = "3.11.*"openjdk = "==17.0.18"pyspark = ">=4.1.1,<5"Key aspects:
conda-forge and bioconda provide pre-built packages (including Java and Spark)openjdk = "==17.0.18" fixes the exact Java version across runssparkhpc-example command runs the Python driver inside the Pixi environmentlinux-64 matches typical HPC clusters# Install Pixi (first time)curl -sSL https://pixi.sh/install.sh | sh
# Install dependencies into pixi.lockpixi install
# Run a command in the Pixi environmentpixi run sparkhpc-example# or via Makefilemake exampleWhen pixi run sparkhpc-example executes:
JAVA_HOME is set automaticallySPARK_HOME is resolved from the PySpark installationThe sparkjob class wraps Spark on SLURM by:
sbatchExample usage (from run_example.py):
from sparkhpc import sparkjob
# Create a Spark job: 2 cores total, 2 cores per executor, 10 min walltimesj = sparkjob.sparkjob(ncores=2, cores_per_executor=2, walltime="00:10")
# Submit to SLURMcluster_id = sj.submit()print(f"submitted cluster_id={cluster_id} jobid={sj.jobid}")
# Poll until master starts (max 3 minutes)started = Falsedeadline = time.time() + 180while time.time() < deadline: master = sj.master_url() if master: print(f"master={master}") started = True break time.sleep(1)
if not started: sj.stop() raise RuntimeError("Spark master did not start in time")
# Start PySpark contextsc = sj.start_spark(graphframes_package=None)
# Run Spark actionscount_result = sc.parallelize(range(100)).count()sum_result = sc.parallelize(range(1, 11)).sum()print(f"count={count_result}")print(f"sum={sum_result}")
# Always clean uptry: # ... run spark tasks ...finally: sc.stop() sj.stop() print("cluster stopped")Behind the scenes, sparkhpc generates a SLURM script of roughly this form:
#!/bin/bash#SBATCH --job-name=sparkjob#SBATCH --nodes=1#SBATCH --cpus-per-task=2#SBATCH --time=00:10:00#SBATCH --output=sparkcluster-%j.log
# Start Spark master on this nodeexport SPARK_HOME=/path/to/pyspark$SPARK_HOME/bin/spark-class org.apache.spark.deploy.master.Master \ --host $(hostname) \ --port 7077 \ --webui-port 8080 \ > master.log 2>&1 &MASTER_PID=$!
# Extract master URL and write to metadata filesleep 2MASTER_URL="spark://$(hostname):7077"echo $MASTER_URL > $HOME/.sparkhpc_${SLURM_JOBID}_master
# Start Spark workers via srun (parallel on allocated nodes)srun $SPARK_HOME/bin/spark-class org.apache.spark.deploy.worker.Worker \ --cores 2 \ $MASTER_URL
# Cleanupwait $MASTER_PIDKey points:
srun parallelizes worker startup across allocated nodesThe master_url() method polls for the metadata file:
def master_url(self): """Check if master URL is available in metadata file.""" metadata_path = f"{os.path.expanduser('~')}/.sparkhpc_{self.jobid}_master" if os.path.exists(metadata_path): with open(metadata_path, 'r') as f: return f.read().strip() return NoneThis avoids hardcoding hostnames (which vary across clusters) and lets the driver and master run asynchronously.
If you have a local SLURM cluster (for example, via Docker):
cd spark-on-slurm
# Install dependenciesmake setup
# Run the examplemake exampleExpected output:
submitted cluster_id=abc123 jobid=12345master=spark://node1:7077count=100sum=55cluster stoppedThe same commands work on a SLURM-managed HPC cluster:
# Log in to the clusterssh user@hpc.example.comcd spark-on-slurm
# First time: install Pixi and dependenciesmake setup
# Run Spark via SLURMmake example
# View Spark master logs if neededtail -f sparkhpc/sparkcluster-*.log# Remove generated artifactsmake clean
# Manually check for lingering jobssqueue -u $USERpixi.lockmake setup then make example, or pixi run sparkhpc-exampleCombining Pixi's reproducibility with sparkhpc's SLURM orchestration makes it easier to build Spark workflows that are auditable and portable across clusters.




