Spark on Kubernetes

cat spark-on-k8s.md | grep production-scars

The cursed timeline made real. Operator setup, JVM memory vs cgroup fights, shuffle-spill survival, heterogeneous node scheduling, and the debugging gauntlet: from ex-Cloudera/YARN refugees.

24 entries
6 phases
updated 2026-05-13
phase showing 24
Phase Tool / Config What & Why Command / Snippet
cluster Node inventory First step on heterogeneous clusters. Know your actual allocatable resources before sizing executors. If you skip this, you will size executors wrong. Guaranteed.
kubectl get nodes -o custom-columns=\ NAME:.metadata.name,\ CPU:.status.allocatable.cpu,\ MEM:.status.allocatable.memory \ --sort-by='.status.allocatable.memory'
cluster Node labeling Taint and label nodes for Spark workloads. Prevents general pods from stealing resources from your executors mid-job.
# label nodes for spark scheduling kubectl label node <name> spark-role=executor kubectl taint node <name> \ spark-only=true:NoSchedule
cluster Resource audit See real vs requested resources across all nodes. Reveals over-commitment before Spark even starts.
kubectl describe nodes | grep -A5 \ "Allocated resources" # look at Requests vs Limits vs Allocatable # if requests > 80% allocatable, Spark # pods will pend or get evicted
cluster LimitRange guard Prevent rogue Spark configs from requesting the entire node. Especially important when multiple teams share the cluster.
# limitrange.yaml apiVersion: v1 kind: LimitRange metadata: name: spark-limits namespace: spark-jobs spec: limits: - type: Container max: memory: "48Gi" cpu: "8"
operator spark-operator GoogleCloudPlatform/spark-on-k8s-operator. The least-bad option for managing SparkApplication CRDs. Handles submission, monitoring, restart. Helm install.
helm repo add spark-operator \ https://kubeflow.github.io/spark-operator helm install spark-operator \ spark-operator/spark-operator \ --namespace spark-operator \ --create-namespace \ --set webhook.enable=true
operator SparkApplication CRD Minimal viable SparkApplication for heterogeneous clusters. Size executor to smallest node, let K8s bin-pack onto bigger ones. scar Sizing for the largest node = pods pending forever on small nodes.
apiVersion: sparkoperator.k8s.io/v1beta2 kind: SparkApplication metadata: name: etl-merge spec: type: Python mode: cluster image: registry/spark-py:3.5.3 mainApplicationFile: local:///app/merge.py driver: cores: 2 memory: "4g" executor: instances: 19 cores: 4 memory: "32g" memoryOverhead: "10g" nodeSelector: spark-role: executor tolerations: - key: spark-only operator: Equal value: "true" effect: NoSchedule
operator Restart policy Jobs fail. Executors get OOMKilled. Don't restart the whole job: let Spark replace the executor. Only restart on driver failure.
spec: restartPolicy: type: OnFailure onFailureRetries: 3 onFailureRetryInterval: 30 onSubmissionFailureRetries: 3 onSubmissionFailureRetryInterval: 20
operator Image strategy Don't pull multi-GB Spark images on every pod start. Use a local registry or pre-pull DaemonSet. scar 60s+ executor startup because 3GB image pulls over internal network.
# DaemonSet to pre-pull on all spark nodes apiVersion: apps/v1 kind: DaemonSet metadata: name: spark-image-prepull spec: selector: matchLabels: { app: spark-prepull } template: spec: nodeSelector: spark-role: executor initContainers: - name: pull image: registry/spark-py:3.5.3 command: ["true"] containers: - name: pause image: registry.k8s.io/pause:3.9
tuning Memory layout JVM memory vs cgroup limits: the #1 source of OOMKilled pods. Spark requests (memory + memoryOverhead). K8s limit = that sum. JVM doesn't respect cgroups cleanly. scar Default overhead (0.1) is a joke for PySpark: Arrow, off-heap, Python workers all live in overhead.
# The real formula: # K8s limit = spark.executor.memory # + spark.executor.memoryOverhead # For PySpark: overhead should be 25-40% spark.executor.memory 32g spark.executor.memoryOverhead 10g # K8s pod limit will be 42Gi # NEVER set K8s limits manually on top: # the operator handles this
tuning Memory fractions Execution vs storage inside Spark's unified memory. For join-heavy ETL, execution wins. Don't waste RAM caching when you're spilling shuffles.
# ETL / join-heavy: maximise execution spark.memory.fraction 0.8 spark.memory.storageFraction 0.2 # ML / iterative: cache matters more # spark.memory.storageFraction 0.5
tuning AQE Adaptive Query Execution. Non-negotiable at scale. Coalesces small partitions, handles skewed joins, optimizes shuffle partitions at runtime. Spark 3.2+ default on, but verify.
spark.sql.adaptive.enabled true spark.sql.adaptive.coalescePartitions.enabled true spark.sql.adaptive.skewJoin.enabled true spark.sql.adaptive.skewJoin.skewedPartition\ ThresholdInBytes 268435456 # 256MB skew threshold: tune for your data spark.sql.shuffle.partitions 4096 # AQE will coalesce; start high, let it shrink
tuning Bucketing Pre-sort tables by join key into buckets. Subsequent joins become bucket-to-bucket with ZERO shuffle. One expensive write, every downstream join is free. scar Without this, a 100TB 3-way join will spill 10s of TB through the network.
# write once, join many df.write \ .bucketBy(2048, "join_key") \ .sortBy("join_key") \ .mode("overwrite") \ .saveAsTable("table_a_bucketed") # bucket count: aim for 128-256MB/bucket # 33TB / 2048 = ~16GB: still large # consider 8192 for very large tables
tuning Column pruning With 150 columns per table, SELECT * is a death sentence. Every unnecessary column in the shuffle multiplies spill volume. Project at scan time.
# BAD: reads all 450 columns through shuffle result = a.join(b, "key").join(c, "key") # GOOD: project before join a_slim = a.select("key", "col1", "col2") b_slim = b.select("key", "col7", "col8") c_slim = c.select("key", "col12") result = a_slim.join(b_slim, "key") \ .join(c_slim, "key")
tuning Staged joins Don't three-way join in one query. Materialize intermediate results to Parquet. Each stage shuffles half the data, and you get restart semantics if stage 2 fails.
# stage 1: join A + B, checkpoint ab = a_slim.join(b_slim, "key") ab.write.parquet("/data/staging/ab") # stage 2: join AB + C ab = spark.read.parquet("/data/staging/ab") result = ab.join(c_slim, "key") result.write.parquet("/data/output/merged") # more total I/O, but each stage's shuffle # is half the size and restartable
storage Shuffle dirs Where shuffle spill goes determines everything. Multiple paths = parallel I/O. Local NVMe > emptyDir > hostPath > network PVC. scar On VMs sharing physical disks, 20 executors hammering shuffle I/O simultaneously saturates the hypervisor's I/O scheduler.
# multiple dirs = round-robin spill I/O spark.local.dir /mnt/scratch0,/mnt/scratch1 # in SparkApplication CRD: spec: volumes: - name: scratch0 hostPath: path: /data/spark-scratch type: DirectoryOrCreate executor: volumeMounts: - name: scratch0 mountPath: /mnt/scratch0
storage Shuffle compression When you're approaching PB scale, you're I/O-bound, not CPU-bound on compression. zstd gives better ratio than lz4: fewer bytes spilled to disk and over the network.
spark.shuffle.compress true spark.shuffle.spill.compress true spark.io.compression.codec zstd spark.io.compression.zstd.level 1 # level 1 = fast. only go higher if # CPU is genuinely idle during shuffle
storage Parquet tuning Source format determines read performance. Parquet + zstd + projection pushdown means Spark reads 20-30TB instead of 100TB. Column pruning only works if the format supports it.
# write optimised parquet spark.sql.parquet.compression.codec zstd spark.sql.parquet.mergeSchema false spark.sql.parquet.filterPushdown true # row group size: larger = fewer seeks, # but less granular predicate pushdown spark.sql.parquet.rowGroupSize.bytes 134217728 # 128MB: good default for large tables
storage History server Spark UI dies with the driver pod. History server persists event logs for post-mortem analysis. Point it at S3-compatible storage (MinIO if self-hosted).
# in sparkConf: spark.eventLog.enabled true spark.eventLog.dir s3a://spark-logs/events spark.eventLog.compress true # deploy history server separately: spark.history.fs.logDirectory s3a://spark-logs/events spark.history.fs.cleaner.enabled true spark.history.fs.cleaner.maxAge 7d
sched Volcano Gang scheduling: all-or-nothing pod groups. Without it, K8s schedules 5 of 19 executors and the job sits at 25% utilization burning resources. Also provides fair-share queuing and preemption.
kubectl apply -f \ https://raw.githubusercontent.com/\ volcano-sh/volcano/master/installer/\ volcano-development.yaml # in SparkApplication: spec: batchScheduler: volcano batchSchedulerOptions: queue: spark-queue
sched YuniKorn Alternative to Volcano. From Cloudera lineage: if you're ex-Cloudera, the queue model feels familiar. Hierarchical queues, gang scheduling, app-level resource tracking.
helm repo add yunikorn \ https://apache.github.io/yunikorn-release helm install yunikorn \ yunikorn/yunikorn \ --namespace yunikorn \ --create-namespace # annotate SparkApplication pods: # yunikorn.apache.org/app-id: etl-merge # yunikorn.apache.org/queue: root.spark
sched ResourceQuota Hard ceiling on namespace-level resources. Prevents one runaway SparkApplication from starving everything else on the cluster.
apiVersion: v1 kind: ResourceQuota metadata: name: spark-quota namespace: spark-jobs spec: hard: requests.cpu: "80" requests.memory: "800Gi" limits.cpu: "96" limits.memory: "900Gi" pods: "25"
sched PriorityClass When the cluster is full, decide what gets evicted. Production ETL should preempt dev/test Spark jobs, not the other way around.
apiVersion: scheduling.k8s.io/v1 kind: PriorityClass metadata: name: spark-production value: 1000000 globalDefault: false preemptionPolicy: PreemptLowerPriority # reference in SparkApplication: # spec.driver.priorityClassName: spark-production # spec.executor.priorityClassName: spark-production
debug OOMKilled triage The most common failure mode. Check whether it's JVM heap, off-heap, or Python worker. scar The pod just says "OOMKilled" with exit code 137: useless without knowing which memory region blew.
# find which executors died kubectl get pods -n spark-jobs \ -l spark-role=executor \ --field-selector=status.phase=Failed # check the reason kubectl get pod <name> -o jsonpath=\ '{.status.containerStatuses[0].state.terminated.reason}' # OOMKilled = bump memoryOverhead # Error (exit 1) = check driver logs
debug Driver logs The driver has the full DAG, stage progress, and failure context. Executor logs only show their slice. Always start with the driver.
# live driver logs kubectl logs -f -n spark-jobs \ <app-name>-driver # if driver pod is gone: kubectl logs -n spark-jobs \ --previous <app-name>-driver # or use history server if event logs # were enabled (see storage section)
debug Spark UI port-fwd The Spark UI is the only way to see stage-level shuffle read/write, spill metrics, and task distribution. It runs on the driver pod.
kubectl port-forward -n spark-jobs \ <app-name>-driver 4040:4040 # then open http://localhost:4040 # key tabs: # Stages > look for "Shuffle Spill (Disk)" # SQL > physical plan shows join strategy # Executors > memory usage per executor
debug Shuffle spill check If Shuffle Spill (Disk) is close to Shuffle Write, you're fully spill-dominated. The job is I/O-bound. More memory or bucketing is the only fix: no config tuning helps.
# in Spark UI > Stages > click any stage # look at Aggregated Metrics: # # Shuffle Write: 12.4 TB # Shuffle Spill (Mem): 8.1 TB # Shuffle Spill (Disk):11.9 TB ← pain # # if Disk ≈ Write: you are fully spilling # fix: bucket the tables (tuning section)
debug Skew detection One task takes 40 minutes, 4095 others finish in 2 minutes. That's join key skew. AQE handles mild skew; extreme skew needs manual salting.
# check in pyspark: df.groupBy("join_key") \ .count() \ .orderBy(F.desc("count")) \ .show(20) # if top key is 100x+ median: salt it # df = df.withColumn("salt", # F.concat(F.col("key"), # F.lit("_"), # (F.rand()*N).cast("int")))
debug VM I/O contention On virtualized infra, disk contention is invisible from inside the VM. If shuffle performance collapses mid-job, the hypervisor I/O scheduler is saturated. scar 20 VMs sharing physical disks, all spilling shuffle simultaneously.
# inside the VM: check I/O wait iostat -xz 5 # %iowait > 30% = storage bottleneck # await > 50ms = hypervisor contention # ask infra team to check hypervisor: # esxtop (VMware) or virsh domstats (KVM) # remediation: stagger job start times, # request SR-IOV for NVMe passthrough, # or dedicate physical disks to spark VMs
No entries match this filter.