Sub topic 9
When not to autoscale: streaming and other limits
This chapter assumes you know the basics of Spark jobs, stages, tasks and partitions. It also assumes you have read the previous chapters on how autoscaling works and how to choose minimum and maximum worker counts. Autoscaling suits many batch and interactive workloads. It fits poorly with some others, and this chapter covers which ones and what to do instead.
What autoscaling can and cannot see
Standard cluster autoscaling reacts to Spark's own signals. It looks at pending tasks and at how long executors have been idle. That makes three assumptions:
- Demand rises and falls over minutes, not seconds.
- Idle executors really are idle, so removing them loses nothing.
- More workers make the work finish sooner.
Each limit below comes from one of these assumptions failing. Autoscaling only changes the number of workers. It does not change the driver, the node type, or Spark settings such as spark.sql.shuffle.partitions.
Structured Streaming
Structured Streaming runs a query as a series of small micro-batches. Even a quiet stream triggers a batch every few seconds, so executors rarely stay idle long enough to be removed. The cluster scales up under a burst of data, then tends to stay large. Databricks documents this as a limit of cluster autoscaling when scaling down for streaming workloads.
Scaling up is also awkward for streams. Requesting new nodes takes minutes, and a micro-batch may be over before the new executors can help. Meanwhile, a stream running on a changing set of executors gives you less predictable latency.
For continuous streaming, you have two practical options:
- Use a fixed-size cluster. Size it for the peak rate you must sustain, with headroom, and accept that you pay for it around the clock.
- Use Delta Live Tables (now part of Lakeflow Declarative Pipelines) with enhanced autoscaling. Enhanced autoscaling is a separate feature built for streaming. It uses batch backlog and processing time to scale, and it can scale down between batches. It is the option Databricks recommends for autoscaling streams.
A fixed-size specification for a streaming job looks like this:
{
"cluster_name": "stream-fixed",
"spark_version": "15.4.x-scala2.12",
"node_type_id": "i3.xlarge",
"num_workers": 4,
"aws_attributes": {
"first_on_demand": 1,
"availability": "ON_DEMAND"
}
}It uses num_workers instead of autoscale, and on-demand nodes, because a spot reclaim in the middle of a long-running stream causes a restart and a recovery delay.
An alternative: incremental batch
Not every stream needs to run continuously. If you can tolerate minutes or hours of latency, run the same logic as a scheduled job with availableNow=True. The query processes all data that has arrived since the last run, using a checkpoint, and then stops. The cluster exists only while work is running, and autoscaling behaves well because the job has a clear start, a burst of work, and an end.
path = "/tmp/demo/events"
spark.range(100000).write.format("delta").mode("overwrite").save(path)
query = (
spark.readStream.format("delta").load(path)
.writeStream.format("delta")
.option("checkpointLocation", "/tmp/demo/chk")
.trigger(availableNow=True)
.start("/tmp/demo/out")
)
query.awaitTermination()
print(f"Rows written: {spark.read.format('delta').load('/tmp/demo/out').count()}")Run it a second time and the checkpoint tells Spark that nothing new has arrived, so the query finishes with no new rows written.
spark-submit jobs
Jobs configured with the spark-submit task type do not support autoscaling. Define such a job with a fixed num_workers. If you want autoscaling for the same application, move it to a notebook, Python script, or JAR task instead.
Short jobs
Autoscaling has a startup cost. The cluster starts at the minimum, notices pending tasks, requests nodes from the cloud provider, waits for them to boot, and then registers executors. Even with an instance pool, this takes a short while. With plain on-demand nodes it can take several minutes.
If a job runs for five minutes in total, the ramp-up may consume a large part of that time. A fixed cluster that is already at the right size starts the work immediately. The reverse also holds: a job that takes hours with a clear peak profits from autoscaling, because the ramp-up cost is spread across a long run.
Work that does not parallelize
More workers help only when there are more tasks than task slots. Adding workers does not help in these cases:
- Data skew. One partition holds most of the rows, so one task runs long while the others finish. Autoscaling may even scale down, because most executors are idle, and you are left with the slow task regardless.
- Few partitions. If a stage has 8 tasks and the cluster already has 16 cores, extra workers have no tasks to run.
- Driver-bound work. Collecting large results, building huge broadcast tables, or running single-threaded Python on the driver gets no benefit from workers.
- Single-node libraries. Pandas, scikit-learn, and similar libraries run on the driver. A multi-worker cluster wastes money here, and a single node cluster is the better fit.
The cell from the earlier chapter on partitions helps you check this before you raise the maximum worker count:
total_cores = spark.sparkContext.defaultParallelism
shuffle_partitions = spark.conf.get("spark.sql.shuffle.partitions")
aqe_enabled = spark.conf.get("spark.sql.adaptive.enabled")
print(f"Default parallelism (approx. total cores): {total_cores}")
print(f"Shuffle partitions: {shuffle_partitions}")
print(f"Adaptive query execution enabled: {aqe_enabled}")If your largest stages have fewer tasks than the cluster's maximum core count, the upper bound is set too high.
Shuffle-heavy jobs and scale-down
Executors hold shuffle files on local disk. If a worker is removed while later stages still need its shuffle output, Spark must recompute those files. Databricks tries to avoid removing nodes that hold needed shuffle data, but this means scale-down can be slow or partial in the middle of a shuffle-heavy job. You may see a cluster stay large through the tail of a job. Do not read that as a malfunction. It is a trade-off that protects the job from recomputation.
Interactive clusters with bursty users
A shared all-purpose cluster looks like an ideal fit for autoscaling, but there is a catch. Users run queries in bursts with gaps between them, and the cluster scales up for each burst and back down in the gap. The next user then waits for the scale-up. If response time matters more than cost, set a higher minimum. If a team's usage is predictable, a fixed size during working hours may be better.
Instance pools and capacity
Autoscaling depends on the cloud provider having capacity. When the cluster uses an instance pool, the pool must also have room. If the pool's maximum capacity is lower than the cluster's max_workers, the cluster cannot reach its upper bound. Check this when a cluster appears stuck below its maximum.
Decision guide
| Situation | Choice | Reason |
|---|---|---|
| Continuous stream, steady rate | Fixed size | Executors never go idle, so scale-down does not happen |
| Continuous stream, variable rate | Delta Live Tables with enhanced autoscaling | Scales on backlog and can scale down |
| Stream with relaxed latency | Scheduled `availableNow` job | Cluster runs only during work |
| `spark-submit` task | Fixed size | Autoscaling is not supported |
| Skewed or few-partition job | Fix the data layout | Extra workers sit idle |
| Long batch job with varying load | Autoscaling | Ramp-up cost is spread over a long run |
Common mistakes
- Setting
min_workersequal tomax_workers. This is a fixed cluster with extra configuration. Usenum_workersto say what you mean. - Autoscaling a stream and expecting a lower bill. The cluster may stay near its maximum.
- Raising
max_workersto fix a slow job without checking the Spark UI for skew. - Assuming that autoscaling resizes the driver. It does not.
Exercise
A job runs a Structured Streaming query continuously on an autoscaling cluster (2 to 10 workers). The cluster stays at 9 or 10 workers even during quiet periods overnight. Give the likely reason and two ways to fix it.
Show answer
Micro-batches keep arriving, so executors never stay idle long enough to be removed, and standard autoscaling scales down poorly for streaming. Fix 1: switch to a fixed-size cluster sized for the peak rate. Fix 2: move the query into a Delta Live Tables pipeline with enhanced autoscaling, which scales on backlog and can scale down. If latency of minutes is acceptable, a third option is a scheduled job with trigger(availableNow=True).