E-NO
Apache Spark capacity planning 7 Min Read

Apache Spark Capacity Planning: A Practical Guide with Examples

calendar_today Published: 2026-10-17
update Last Updated: 2026-10-17
analytics SEO Efficiency: 100%
Technical guide illustration for Apache Spark Capacity Planning: A Practical Guide with Examples.

Intro

Apache Spark capacity planning often feels like guesswork. Teams either over-provision and waste money or under-provision and suffer job failures. This guide replaces guesswork with a repeatable process: observe current resource usage, calculate realistic sizes, apply changes in small increments, and verify results before scaling further.

We focus on the practical levers you control every day: executor cores, executor memory, driver memory, and dynamic allocation. For each lever, you will find commands, real configuration examples, expected outputs, and failure signals. You will also see common mistakes teams make, why they happen, and how to recover.

Throughout, we use a fictional startup called DataCrunch with a real workload: a nightly batch job that processes 2 TB of Parquet data and a streaming job reading from Kafka. These examples show how to plan capacity for typical analytics and streaming pipelines. By the end, you will be able to build a capacity plan tailored to your own Spark jobs.

Version and Environment Inventory

Before touching any settings, you need a clear picture of your environment. Capacity planning depends on your Spark version, cluster manager (YARN, Kubernetes, standalone), and available resources. A change that works on YARN may behave differently on Kubernetes.

Start with read-only commands to capture the current state. On a YARN cluster, check Spark and Hadoop versions and the resources of a running application:

spark-submit --version
# output lines like:
#   Welcome to
#         ____              __
#        / __/__  ___ _____/ /__
#       _\ \/ _ \/ _ `/ __/  '_/
#      /___/ .__/\_,_/_/ /_/\_\   version 3.4.1
#         /_/
#
# Using Scala version 2.12.17, Java HotSpot(TM) 64-Bit Server VM, 1.8.0_362
# Branch HEAD
# Compiled by user hoidayao on 2023-06-22T20:09:51Z
# Revision 2b3d4a55630f9a7a3bcd50c6e8e065c0a1458c9a
# Url https://github.com/apache/spark
# Type --help for more information.

yarn application -list -appStates RUNNING
# example output:
# Total number of applications (application-types: [], states: [RUNNING] and tags: []):2
#                 Application-Id      Application-Name        Application-Type          User       Queue             State        Final-State       Progress                        Tracking-URL
# application_1690000000000_0001   nightly-aggregation      spark                    dataeng   default           RUNNING         UNDEFINED            10%         http://node1:8088/proxy/application_1690000000000_0001/

For Kubernetes, list Spark pods and their requests and limits:

kubectl get pods -l spark-role=driver -n spark-jobs
kubectl describe pod <driver-pod-name> -n spark-jobs | grep -A 5 "Requests:\|Limits:"

Prerequisite checks include ensuring you have access to the resource manager UI or CLI and that your account can query application metrics. On YARN, use yarn application -status <app-id> to see allocated vcores and memory. On Kubernetes, use kubectl top pods if metrics-server is installed.

A common mistake is planning capacity based on the cluster total rather than what is actually available to your queue. In YARN, check queue capacities:

yarn queue -status default
# Example output:
# Queue Information :
# Queue Name : default
# State : RUNNING
# Capacity : 80%
# Current Capacity : 60%
# Maximum Capacity : 100%
# Default Node Label expression : <DEFAULT_PARTITION>
# Accessible Node Labels : *

If your job runs in a queue with 80 percent capacity on a 100-core cluster, your effective ceiling is 80 cores, not 100. Plan within your queue's maximum capacity. Always record cluster version, queue capacity, and current running applications before any change. This baseline helps you detect regressions.

For recovery, if a configuration change causes rapid failures, revert to the previous setting and compare job timelines. Keep a note of the previous values. Without a baseline, you cannot prove whether a change helped or hurt.

Safe Configuration Path

Now that you have an inventory, the next step is adjusting Spark configurations. The golden rule: change one thing at a time, use a small test suite, and compare metrics before and after.

Spark configurations can be set in three places with increasing precedence: spark-defaults.conf, spark-submit command line, or inside the application code. For controlled testing, set them via spark-submit for a single run. For lasting changes, use spark-defaults.conf and version control the file.

The most important settings for capacity planning are executor cores, executor memory, driver memory, and dynamic allocation. Let's look at each with a concrete example.

Executor Cores

Executors are the workhorses of Spark; each executor can run multiple tasks in parallel depending on its core count. Setting spark.executor.cores too low wastes cluster resources and complicates memory overhead calculations; too high can lead to HDFS throughput bottlenecks and garbage collection pressure.

A good starting point is 5 cores per executor. This is grounded in research by Databricks and others showing that more than five concurrent tasks per executor can degrade performance for I/O-heavy workloads due to thread contention and memory pressure.

For DataCrunch's 100-core YARN cluster, let's allocate 5 cores per executor. But remember the queue capacity: if the queue has 80 percent capacity, the effective max is 80 cores, so total executor cores should not exceed 80 minus driver cores and ApplicationMaster overhead.

To observe the effect, compare a job with different core counts. Run the same job with spark.executor.cores=5 and note the duration, then try spark.executor.cores=3. Keep executor memory constant to isolate the core change. If the job speed improves significantly with 5 cores and there is no increase in garbage collection time or HDFS read errors, 5 cores is justified.

Executor Memory

Executor memory is the most misconfigured setting. Many users set spark.executor.memory to the total JVM heap, forgetting that Spark includes overhead beyond the heap. The correct formula for usable execution and storage memory is:

Total executor memory = JVM heap + overhead.

spark.executor.memory sets the JVM heap. spark.executor.memoryOverhead sets additional off-heap memory for thread stacks, native buffers, and other internals. The default overhead is max(384 MB, 10 percent of executor memory).

A common starting point is to set memoryOverhead to at least 10-15 percent of executor memory, or more for jobs with large shuffle or broadcast variables.

For DataCrunch's nightly job processing 2 TB of Parquet, initial tests used spark.executor.memory=4g and the job failed with ExecutorLostFailure and OutOfMemoryError: Java heap space. Increasing to 8g with spark.executor.memoryOverhead=1g resolved the failure. The job now runs in 27 minutes compared to failing before. However, 8 GB may be overkill; you could test 6 GB next to find the sweet spot.

To verify memory is sufficient, monitor Spark UI for each executor's peak memory usage. If total usage (heap + off-heap) approaches the configured limit, increase memory. If usage stays below 50 percent, you may be over-provisioning and could reduce executor memory to save resources.

Driver Memory

The driver coordinates the job and holds task results if you collect() them. Most jobs need a driver with 1-4 cores and 2-4 GB memory. The default spark.driver.memory=1g is often insufficient for jobs that collect large datasets or use broadcast variables.

DataCrunch's data science team ran a job that collected 5 million rows to the driver for analysis. With the default 1 GB, the job failed with OutOfMemoryError. Increasing spark.driver.memory=4g solved it. Use the following rule: for data collection, estimate the size of collected data and set driver memory at least twice that size.

spark-submit \
  --driver-memory 4g \
  --executor-memory 8g \
  --executor-cores 5 \
  --conf spark.executor.memoryOverhead=1g \
  your_job.py

Dynamic Allocation

Static allocation wastes resources when the workload varies. Dynamic allocation lets Spark request or release executors based on pending tasks. Enable it with:

spark.dynamicAllocation.enabled=true
spark.shuffle.service.enabled=true
spark.dynamicAllocation.minExecutors=2
spark.dynamicAllocation.maxExecutors=20
spark.dynamicAllocation.initialExecutors=5
spark.dynamicAllocation.executorIdleTimeout=60s

On YARN, the shuffle service must be started on NodeManagers. Check if it is running:

yarn node -list -all
# Look for nodes with NodeManager and Auxiliary Services: mapreduce_shuffle,spark_shuffle

If the shuffle service is not enabled, dynamic allocation will fail. You will see errors like "External shuffle service is not reachable" or executors will not be released.

Dynamic allocation is a powerful tool, but it does not eliminate the need for capacity planning. You still must set appropriate min and max values to avoid thrashing. Start with a narrow range and widen gradually.

Verification and Diagnostics

After applying a configuration change, you need to verify it works as expected. Verification happens at two levels: immediate job success and performance improvements.

Checking Job Success and Resource Usage

After running a job, check its status and resource usage. On YARN:

yarn application -status <application_id>
# Success status: Final-State : SUCCEEDED
# Failure: Final-State : FAILED or KILLED

Review the Spark UI at http://<driver-node>:4040 or the history server. Key metrics:

  • Executor summary shows the number of active executors, their cores, and memory used.
  • Task metrics show shuffle read/write, input size, and duration.
  • GC time per executor indicates memory pressure. If GC time exceeds 10 percent of task time, increase executor memory or reduce cores.

Example: DataCrunch's job with spark.executor.memory=4g had GC time of 18 percent, indicating memory thrashing. After increasing to 8 GB, GC time dropped to 5 percent.

Use the Spark REST API to fetch metrics programmatically:

curl http://<history-server>:18080/api/v1/applications/<app-id>/executors

This returns JSON with details like memoryUsed, totalCores, and totalDuration. You can script comparisons between runs.

Sizing Calculations

To verify you are using resources efficiently, calculate the total allocated cores and memory. For a YARN application:

yarn application -status <app-id> | grep -E "Aggregate Resource Allocation"
# Output: Aggregate Resource Allocation : 120000 MB-seconds, 200 vcore-seconds

Then compare with the job's actual work. If the job spent 80 percent of time waiting for tasks to be scheduled, you might be under-provisioned. If executors are idle most of the time, you are over-provisioned.

For dynamic allocation, check the executor count over time in the Spark UI. If the count fluctuates rapidly, adjust spark.dynamicAllocation.sustainedSchedulerBacklogTimeout to avoid premature release.

Failure Modes and Recovery

Every capacity planning change carries risk. Here are the most frequent failure modes and how to recover.

Out of Memory Exceptions

Symptoms: Executor logs show java.lang.OutOfMemoryError: Java heap space or messages like "Container killed by YARN for exceeding memory limits".

Root cause: Executor memory too low or data skew causing one executor to hold too much data.

Recovery: Increase spark.executor.memory or spark.executor.memoryOverhead. To address skew, enable spark.sql.adaptive.skewJoin.enabled=true to split skewed partitions.

DataCrunch encountered OOM for a join where one key appeared 10,000 times more than others. Enabling adaptive query execution with skew join handling fixed it without increasing memory.

Executor Lost Failures

Symptoms: ExecutorLostFailure with reason "Container killed by YARN for exceeding memory limits" or "Exit code 143".

Root cause: Off-heap memory exceeding overhead, often due to large shuffle blocks or native memory leaks.

Recovery: Increase spark.executor.memoryOverhead to 15-20 percent of executor memory. Reduce shuffle partitions with spark.sql.shuffle.partitions to control memory per task.

Slow Scheduling or Idle Executors

Symptoms: Jobs run slower than expected, and the Spark UI shows many idle cores.

Root cause: Too many cores per executor causing thread contention, or cluster fragmentation due to oversized executors.

Recovery: Reduce spark.executor.cores to 4 or 5. Ensure spark.dynamicAllocation.enabled=true to reclaim unused executors.

Disk Space Exhaustion

Symptoms: Shuffle spills fill local disks, causing errors like "No space left on device".

Root cause: Insufficient disk space for shuffle data or excessive spills due to memory pressure.

Recovery: Increase executor memory to reduce spills, or add more disks per node. Monitor spark.local.dir usage.

Operations Checklist

Capacity planning is not a one-time task; it is an ongoing practice. Use this checklist to keep your cluster healthy.

ItemOwnerFrequencyVerification
Review executor memory and cores for top 5 jobsData Engineering LeadWeeklyCompare current settings with Spark UI peak usage; adjust if utilization < 50% or > 90%
Check queue capacity utilizationDevOps EngineerWeeklyRun yarn queue -status <queue>; ensure current capacity is not consistently above 80% of max
Monitor job duration trendsData EngineerDailyAutomatic alerts if job duration increases by 20% week-over-week
Test scaling limits with a benchmark jobPerformance EngineerMonthlyRun a representative workload and record completion time and resource usage
Review dynamic allocation settingsData Engineering LeadQuarterlyAnalyze executor usage patterns; adjust min/max executors and timeout
Update capacity plan documentationTech LeadAfter any major changeEnsure docs reflect current cluster size and job profiles

For each item, the owner is a single accountable person, not a group. They are responsible for running the check, interpreting results, and initiating changes if needed. The verification column defines what success looks like.

When implementing changes, follow this safe sequence:

  1. Capture current metrics (job duration, resource usage).
  2. Apply the change in a test environment or on a subset of jobs.
  3. Compare metrics after the change.
  4. Roll back if results are worse or inconclusive.
  5. Document the change and its impact.

This sequence prevents simultaneous changes from muddying cause and effect.

Common Pitfalls

Oversubscribing Cores

Many teams set spark.executor.cores to the number of CPUs on the node, e.g., 8 or 16. Research and practical experience show that 5 cores per executor is optimal for most workloads. Why? Each Spark task runs in a thread; with too many threads, you get context switching overhead and contention on shared resources like network and disk. How to avoid: Start with 5 cores and benchmark. If you see task throughput plateau or GC time increase with more cores, stick with 5.

Ignoring Memory Overhead

Setting spark.executor.memory=10g and expecting the container to use exactly 10 GB is a classic mistake. YARN and Kubernetes enforce memory including overhead. If overhead is not accounted for, containers get killed. How to avoid: Always set spark.executor.memoryOverhead explicitly, at least 10 percent of executor memory.

Static Sizing for Variable Workloads

Using fixed executor counts for workloads that change daily results in wasted resources at low times and poor performance at peak. How to avoid: Enable dynamic allocation with sensible min/max. For DataCrunch, min 2 executors at night (when traffic is low) and max 20 executors in the morning peak.

Forgetting Driver Resources

Driver defaults are often too small for jobs that collect data or use large broadcast variables. How to avoid: Profile driver memory needs and set spark.driver.memory accordingly. A simple test: run the job with default driver memory; if it fails with OOM, increase in steps of 2 GB until stable.

Not Testing with Real Data

Planning based on synthetic data or guessing row counts leads to inaccurate memory and core estimates. How to avoid: Use a representative sample of production data, at least 10 percent of actual size, to benchmark. DataCrunch learned that their Parquet files were highly compressed, so actual in-memory size was 3 times larger than on-disk size, causing initial under-provisioning.

Conclusion

Apache Spark capacity planning is a continuous cycle of observation, calculation, safe change, and verification. By inventorying your environment, adjusting executor cores and memory systematically, enabling dynamic allocation, and following a clear operations checklist, you can avoid most performance and reliability issues.

Start with one job that matters. Record its current configuration and runtime. Use the sizing guidelines here to propose a new configuration. Test it in isolation. Compare metrics. Then expand to other jobs. This incremental, evidence-based approach transforms capacity planning from guesswork into a repeatable, safe process.

Article Quality Score

Reader usefulness 100%
  • check_circle Reader-ready guide
  • check_circle Practical examples included
  • check_circle Clean SEO article URL