Everyone thinks a pod autoscaler is a thermostat with a for-loop. “Read CPU, if it is above 70% add a pod, if it is below 70% remove one, sleep, repeat.” That model survives exactly until you run it against real traffic and watch the replica count oscillate like a car alarm: a load balancer hashes a burst of requests onto three pods, their CPU spikes, you scale from 10 to 16, the burst drains across 16 pods, average CPU craters, you scale back to 9, the next burst hits, you scale to 15 again, and now you are churning six pods up and down every thirty seconds, each new pod paying a cold-start tax, each terminated pod dropping in-flight connections. The naive loop also has no answer for the questions that make this a real system: what is “the CPU” of a Deployment when one pod has no metric reported yet, one is mid-startup burning 100% warming a cache, and one just got OOM-killed? If you want to scale on a custom metric like requests-per-second from your ingress, where does that number even come from, and what happens to scaling when that metrics pipeline is down? When you run forty thousand of these loops in one cluster, how do you not melt the metrics server?
A Horizontal Pod Autoscaler is deceptive because the single-workload thermostat demo works and then falls apart the moment you need a stable control loop (the output must not oscillate when the input is noisy, which rules out reacting to every sample), metric aggregation under missing and unready data (a replica count is a function of N pods’ metrics, and at any instant some of those are absent, cold, or garbage), pluggable metric sources (CPU and memory come from a resource metrics API, but “scale on queue depth” or “scale on p99 latency” comes from somewhere you do not control), and scale (tens of thousands of autoscaled workloads, each sampled every 15 seconds, means the metrics plane - not the scaling math - is the thing that falls over). The design comes down to a few decisions that are not obvious: making the autoscaler a stateless periodic reconciler that recomputes desired replicas from scratch each tick rather than tracking deltas, computing the target with a single ratio formula (desired = ceil(current * currentMetric / targetMetric)) instead of step rules, and - the heart of it - gating scale-down behind a stabilization window that takes the maximum recommended replica count over a trailing window so a transient dip cannot shrink the fleet, while leaving scale-up fast so a real overload is answered in seconds.
This lives one layer above a container orchestration system: the orchestrator converges actual replicas to a desired count, and the HPA is the controller that decides what that desired count should be, moment to moment, from metrics. Let me do it properly.
Functional Requirements (FR)
In scope:
- Per-workload target tracking. A user declares an autoscaling policy for a scale target (a Deployment, StatefulSet, or anything with a
/scalesubresource): “keep average CPU utilization at 60%,” or “keep requests-per-second-per-pod at 1000,” with aminReplicasandmaxReplicas. The HPA continuously adjusts the target’s replica count so the observed metric tracks the target value, staying inside the bounds. - Multiple metric types. Support resource metrics (CPU, memory) expressed as a utilization percentage of the pod’s request or as a raw quantity; pod custom metrics (an application metric averaged across pods, e.g. active connections per pod); object metrics (a single metric describing one Kubernetes object, e.g. requests/sec on an Ingress); and external metrics (a metric from outside the cluster, e.g. a cloud queue’s depth). When several metrics are configured, compute a desired replica count for each and take the maximum (any metric saying “scale up” wins).
- Min/max clamping. The computed desired count is always clamped to
[minReplicas, maxReplicas].minReplicasmay be 0 only if scale-to-zero is explicitly enabled via a separate feature; default floor is 1. - Stabilization (anti-thrash). Dampen scale-down with a configurable stabilization window (default 300s): the actual scale-down target is the highest recommendation seen in the trailing window, so a brief metric dip does not shrink the fleet. Scale-up has its own, usually zero or short, stabilization window so overload is answered immediately.
- Scaling-velocity policies. Bound how fast the count can move per unit time: “scale up by at most 100% or 4 pods per 60s, whichever is larger”; “scale down by at most 10% per 60s.” Prevents a single bad metric reading from doubling or halving the fleet in one tick.
- Graceful behavior under missing metrics. A pod with no metric yet (just started) or a failed metric read must not be silently treated as 0 (which would trigger scale-up forever) or as the target (which would mask real load). Handle unready/missing pods conservatively and directionally.
- Observability. Expose the current/desired replicas, the per-metric current values, the last scale time, and conditions (
AbleToScale,ScalingActive,ScalingLimited) so an operator can see why the autoscaler did or did not act.
Explicitly out of scope (own the boundary):
- Collecting the metrics. The HPA reads metrics from a metrics API; it does not scrape pods or run a time-series database. A metrics server (resource metrics) and adapters (custom/external metrics) are separate systems we query.
- Actually running/stopping pods. The HPA only writes a new
.spec.replicasto the scale target. The orchestrator’s reconciliation loop and scheduler place and start the pods. We decide the number, not the placement. - Vertical scaling (right-sizing CPU/memory requests of a pod) and cluster autoscaling (adding/removing nodes). Different controllers, different metrics, different failure modes. We scale replica count only.
- Request-level load balancing. Distributing traffic across the replicas is the service/data-plane job; we assume it exists and spreads load roughly evenly (an assumption we will stress-test in the deep dive).
The one decision that drives everything: the HPA is a stateless periodic reconciler that, every tick, reads the current replica count and the current metric values, computes a desired replica count purely as a function of those inputs, and writes it back - it keeps no authoritative state except a short ring buffer of past recommendations used only to compute the stabilization maximum. That is what makes it crash-safe (restart, re-read, recompute), makes the math trivially testable (pure function of inputs), and lets “scale up,” “scale down,” and “hold steady” be the same operation: recompute from scratch and clamp. Everything below follows from it.
Non-Functional Requirements (NFR)
- Scale: on the order of tens of thousands of HPA objects per large cluster (call it up to ~30,000 autoscaled workloads), each referencing a scale target with anywhere from 1 to a few thousand pods. The controller reconciles every HPA on a fixed cadence; the pressure is the metric fan-in - tens of thousands of HPAs each needing metric values for their pod sets every tick.
- Control-loop cadence: the HPA resync period is 15 seconds by default. Every HPA is recomputed at least every 15s. This is the fundamental latency floor: the fastest the system can notice and begin reacting to a change is one tick.
- Reaction latency (the real target): when a workload genuinely overloads, desired replicas should increase within one to two ticks (sub-30s). When load genuinely drops, scale-down is intentionally slow - it waits out the full stabilization window (default 300s) before shrinking. These two asymmetric targets are the entire point of the design.
- Availability: the HPA controller targets the control plane’s availability (99.95%+), but the critical property is fail-safe degradation: if the metrics pipeline or the controller is down, replica counts freeze at their last value - workloads keep running at current size. A metrics outage must never cause a scale-to-zero or a runaway scale-up.
- Consistency: the write to the scale target’s
.spec.replicasmust be atomic and conflict-checked (optimistic concurrency via resource version) so two controllers or a humankubectl scalecannot silently clobber each other. Metric reads are eventually consistent and best-effort - they are the latest observation, staleness is tolerated, the next tick re-reads. - Durability: HPA config (the policy) is durable cluster state in the consistent datastore. The recommendation ring buffer used for stabilization is in-memory and disposable - losing it on controller restart means the stabilization window resets, which at worst delays a scale-down, never causes a wrong scale.
- Stability over optimality (stated explicitly): we accept running somewhat more replicas than strictly necessary during and after a dip (the cost of the stabilization window) in exchange for never thrashing. Over-provisioning for five minutes is cheap; flapping a stateful service’s replica set every thirty seconds is not.
Back-of-the-Envelope Estimation (BoE)
Let me ground the design in numbers.
Workload and HPA volume:
HPA objects in cluster: 30,000
Avg pods per autoscaled target: ~20
Pods under autoscaling control: 30,000 * 20 = 600,000 pods sampled
Resync period: 15 s
=> HPA reconciles/sec: 30,000 / 15 = 2,000 reconciles/sec, steady
Metric read load (the real pressure, and it is not the scaling math):
Each reconcile of an HPA needs the metric for EVERY pod in its target
(for pod/resource metrics). Naively:
600,000 pods / 15 s = 40,000 pod-metric reads/sec against the metrics API.
Plus object metrics (one read per such HPA) and external metrics
(one read per such HPA, often to a cloud API with its own rate limit).
The first non-obvious number: the cost is metric fan-in, not replica math. Computing ceil(current * ratio) is nanoseconds; fetching the CPU of 600,000 pods every 15 seconds is 40,000 reads/sec hammering a metrics server that is itself aggregating from 15,000 kubelets. A naive “each HPA reconcile independently queries each pod’s metric from the source” design melts the metrics plane long before the controller CPU matters. This is why the HPA reads from an aggregated metrics API that serves pre-collected, cached values, and why the metrics server, not the autoscaler, is the component you shard and scale.
Scaling-math cost (trivial, to show it is not the bottleneck):
Per reconcile: aggregate ~20 pod metrics (sum/avg), one ratio, one max over a
ring buffer of ~20 past recommendations (300s window / 15s tick), one clamp.
~a few microseconds of CPU per HPA.
2,000 reconciles/sec * few us = single-digit CPU cores for the math.
The controller is I/O-bound on metric reads and apiserver writes, never CPU-bound
on arithmetic.
Write load back to the apiserver:
Most reconciles result in NO change (the metric is near target, or stabilization
holds the count). Only reconciles that actually change replicas write.
Assume ~5% of ticks produce a scale action at steady state:
2,000 reconciles/sec * 5% = 100 scale writes/sec to /scale subresources.
Each write is a small optimistic-concurrency PATCH. Cheap. The write path is not
the bottleneck; the metric read path is.
Memory footprint of the controller:
Per HPA in-memory: config + a ring buffer of recommendations.
Ring buffer: 300s / 15s = 20 entries, each a small struct (~32 B) => ~640 B.
Plus the HPA spec/status cached: ~2 KB.
30,000 HPAs * ~3 KB = ~90 MB. The controller state fits comfortably in RAM on
one process; the stabilization history is tiny. This confirms: keep the ring
buffer in memory, do not persist it.
The shape of the problem: small state, cheap math, brutal metric fan-in, and an intentional latency asymmetry (fast up, slow down). Everything hard is in (a) getting trustworthy aggregate metrics cheaply and (b) making scale-down patient without making scale-up patient.
High-Level Design (HLD)
+--------------------------------------------------+
| CONTROL PLANE |
| |
kubectl / | +------------------+ +------------------+ |
user applies | | API Server |<---->| etcd (consistent| |
HPA object --->| | (REST + watch) | | datastore) | |
| +---+----------+---+ +------------------+ |
| ^ | watch HPAs + scale targets |
| | PATCH v |
| | /scale +------------------------------+ |
| +---------| HPA CONTROLLER (reconciler) | |
| | - periodic loop (15s) | |
| | - per-HPA: read metrics, | |
| | compute desired, stabilize| |
| | clamp, PATCH replicas | |
| | - in-mem recommendation ring| |
| +------+----------------+------+ |
| | read metrics | |
| +-----------v----+ +-------v-------+ |
| | metrics.k8s.io | | custom/external| |
| | (resource API) | | metrics API | |
| +-------+--------+ | (adapter) | |
| ^ +-------+--------+ |
+--------------------|--------------------|---------+
| scrape | query
+---------------v-----+ +--------v---------+
| METRICS SERVER | | Prometheus / |
| (aggregates kubelet| | cloud monitoring|
| cAdvisor samples) | | (custom metrics)|
+----------+----------+ +------------------+
^ /metrics/resource
+----------+-----------+----------+-----...
| kubelet | kubelet | kubelet | (15,000 nodes)
| +cAdvisor| +cAdvisor | +cAdvisor|
| pods... | pods... | pods... |
+----------+-----------+----------+
Request flow, tick by tick, for a single HPA:
- Desired state in. A user applies an HPA object: target = Deployment
checkout, metric = CPU at 60% average utilization,minReplicas=4,maxReplicas=50. It is persisted in etcd via the API server. The HPA controller WATCHES all HPA objects, so it learns about it immediately. - Tick fires. Every 15s the controller reconciles this HPA. It reads the scale target’s current
.spec.replicasand its label selector (via the/scalesubresource), which tells it both the current replica count and which pods belong to the target. - Fetch metrics. For CPU, the controller calls
metrics.k8s.iofor all pods matching the selector. The metrics server has already scraped each kubelet’scAdvisor-sourced resource metrics, so this is one aggregated API call returning per-pod CPU, served from the metrics server’s cache - not 20 calls to 20 kubelets. - Aggregate and handle missing data. The controller computes average CPU utilization across ready pods, explicitly accounting for pods that are missing metrics or not yet ready (deep dive below). Say it gets 85% against a 60% target.
- Compute desired.
desiredReplicas = ceil(currentReplicas * currentValue / targetValue) = ceil(20 * 85 / 60) = ceil(28.3) = 29. If multiple metrics are configured, it does this per metric and takes the max. - Stabilize. The raw recommendation (29) is pushed into the in-memory ring buffer. For scale-up, the controller (with default 0s up-window) uses it directly. If this were a scale-down (recommendation below current), it would instead take the maximum recommendation over the trailing 300s window - so a one-tick dip cannot shrink the fleet.
- Apply velocity policy and clamp. Bound the change by the configured rate policy (e.g. at most +100%/60s) and clamp to
[4, 50]. Result: 29. - Write back (if changed). If the final number differs from current
.spec.replicas, the controller PATCHes the scale subresource with an optimistic-concurrency check (resource version). The API server persists it; the orchestrator’s Deployment/ReplicaSet controllers now see a new desired count and create 9 more pods; the scheduler places them. The HPA’s job ends at the number. - Status out. The controller updates the HPA’s
status(current metrics, current/desired replicas, last scale time, conditions) so operators can see what happened and why.
The whole thing is a closed loop with a deliberate rectifier in it: the forward path (metric high -> more replicas) is fast; the reverse path (metric low -> fewer replicas) is passed through the stabilization maximum, which is a low-pass filter that only lets sustained decreases through.
Component Deep Dive
1. The scaling formula and why step rules fail
Naive approach: threshold step rules. “If avg CPU > 70%, add 2 pods. If avg CPU < 30%, remove 1 pod.” This is the thermostat everyone writes first.
Where it breaks. Step rules have no notion of how far you are from target, so they are simultaneously too slow and too fast. A workload at 95% CPU with 10 replicas needs to roughly double; adding 2 pods per tick takes several ticks to catch up while the service is on fire. A workload that briefly touches 71% adds 2 pods it did not need. Worse, the two thresholds (70% up, 30% down) create a dead band whose edges are arbitrary and whose behavior near the boundary is a coin flip - a workload hovering at 70% CPU adds pods, which drops it to 60%, which does nothing, until noise pushes it to 71% again. The step size (2 pods) is a constant that is wrong for a 3-replica service and wrong for a 300-replica one.
The fix: a single proportional ratio. The utilization you observe is proportional to load divided by capacity, and capacity is proportional to replica count. So to move observed utilization from its current value to the target, scale the replica count by the same ratio:
desiredReplicas = ceil( currentReplicas * (currentMetricValue / targetMetricValue) )
At 85% CPU with a 60% target and 20 replicas: ceil(20 * 85/60) = 29. One computation, correct for any size, correct for any distance from target, no step constant. If current equals target, the ratio is 1 and the count does not move. This is the whole scaling decision for one metric.
One critical refinement: a tolerance band. Floating-point metric noise means currentValue/targetValue is rarely exactly 1.0; it jitters around it. If you acted on every ratio of 1.02 or 0.98 you would scale on pure noise. So the controller applies a tolerance (default 10%): if |ratio - 1.0| <= 0.1, do nothing. This is the dead band done right - symmetric, proportional, and centered on the target rather than on two arbitrary thresholds.
Multiple metrics: max wins. Configure CPU-at-60% and requests-per-pod-at-1000 together. Compute desired for each independently, take the maximum. The logic: any metric indicating overload must be honored, because under-provisioning on any dimension is a user-visible failure. You never average across metrics (that would let a quiet CPU mask a saturated queue).
2. The stabilization window - the hard part
Naive approach: act on every recommendation immediately, both directions. Each tick, compute desired, write it. Fast and symmetric.
Where it breaks: thrash. Traffic and metrics are noisy on the same timescale as the resync period. A load balancer rehashing connections, a batch job finishing, a GC pause, a metrics-scrape landing mid-spike - any of these moves average CPU by 20-30% for one or two ticks. With symmetric immediate action, the controller scales up on the spike (10 -> 15), the spike passes, average CPU drops further than baseline because now 15 pods share the old load (so maybe 40% against a 60% target), it scales down (15 -> 10), the next spike repeats it. The replica set oscillates every 30-60 seconds. Each scale-up pays cold-start cost (image already cached, but process init, cache warming, connection pool fill, readiness-probe delay - often 10-60s of a pod being up but not useful). Each scale-down terminates pods, draining connections and, for stateful or sticky workloads, causing rebalancing storms. The system spends its energy fighting its own noise and the workload is never in a steady state.
Why asymmetry is the right shape. The two directions have wildly different costs of being wrong. Scaling up when you did not strictly need to costs you a few minutes of one extra pod - cheap, and safe (you can always shrink later). Scaling down when you should not have costs you a service that is now under-provisioned for a load that is about to return - expensive, and user-visible (latency, errors, maybe cascading failure). So: react fast when going up, react slowly and only to sustained signal when going down.
The fix: a stabilization window on scale-down, implemented as a trailing maximum. The controller keeps a ring buffer of the raw recommendations from the last stabilizationWindowSeconds (default 300s -> 20 entries at a 15s tick). Each tick:
raw = ceil(current * currentMetric / targetMetric) # this tick's recommendation
push raw into ring buffer (evicting entries older than the window)
if we are scaling DOWN (candidate < current):
# do not shrink below the HIGHEST thing we wanted in the last 5 minutes
stabilized = max(all recommendations in window)
final = stabilized # a single dip cannot reduce the fleet
else:
# scale UP: use a short/zero window so overload is answered now
stabilized = max(recommendations in up-window) # up-window often 0 => raw
final = stabilized
Walk the thrash scenario through this. Baseline recommendation is 10. A spike pushes one tick’s recommendation to 15; since 15 > current (10), it is a scale-up, answered immediately: fleet goes to 15. The spike passes; the next tick’s raw recommendation drops to 9 (over-provisioned now). That is a scale-down candidate, so the controller takes the max over the trailing window, which still contains the 15 and the intervening values - so final = 15, no shrink. The fleet holds at 15. It will only come down once every recommendation in the full 300s window has fallen below 15, i.e. once the lower load is sustained for the whole window. A transient dip is structurally incapable of causing a scale-down. A genuine, sustained traffic decrease ages the high recommendations out of the window and the max falls, shrinking the fleet smoothly.
The tension this creates, stated honestly. The stabilization window trades promptness of scale-down for stability. Set it too long and you keep paying for pods you do not need for many minutes after load truly drops (prolonged under-utilization - wasted money). Set it too short and thrash leaks back in. 300s is the default because it is comfortably longer than the timescale of typical transient dips (seconds to a minute) but short enough that sustained drops are reclaimed within a coffee break. It is a per-HPA tunable precisely because a spiky web front end and a steady batch consumer want different values. Crucially, the window is one-sided: it never delays scale-up, so the design never trades away overload responsiveness to get stability - it only slows the cheap, safe direction.
Why max and not an average or a decay. A moving average would let a deep enough dip drag the mean down and still shrink the fleet on a transient - it dampens but does not prevent thrash. The trailing max gives a hard guarantee: the fleet cannot drop below the peak demand of the recent past, full stop. It is a ratchet that only releases when demand has genuinely, durably fallen. Simpler to reason about and impossible to fool with a single bad sample.
3. Metric aggregation with missing and unready pods
Naive approach: average the metric over all pods, treat a missing metric as 0. Sum each pod’s CPU, divide by pod count.
Where it breaks. At any tick, some pods have no usable metric: a pod created 3 seconds ago has not been scraped yet; a pod that just OOM-restarted has a garbage sample; a pod being deleted is reporting phantom numbers. If you treat a missing metric as 0%, every freshly added pod lowers the average, which makes the controller think it over-scaled and claw pods back - directly fighting its own scale-up, guaranteeing oscillation during exactly the moments scaling is active. If you treat missing as the target value, you mask pods that might actually be hot. If you just divide by total pod count including unready ones, a workload mid-rollout (many not-yet-ready pods) looks artificially cool and never scales up when it should.
The fix: directional, conservative handling of missing and unready pods. The controller partitions the target’s pods into three buckets and computes the ratio pessimistically in whichever direction protects against a wrong decision:
- Ready pods with a metric: used normally in the sum.
- Missing-metric pods (no sample at all): set aside; their count is
missingPods. - Unready pods (running but not yet passing readiness - e.g. still warming up): set aside; counted separately.
Then:
- Compute the raw utilization ratio using only the ready-with-metric pods.
- If the raw signal says scale UP, assume missing-metric pods are using 0% (so they do not inflate the need) - this makes scale-up conservative, you will not over-scale on absent data.
- If the raw signal says scale DOWN, assume missing-metric pods are using 100% of target - this makes scale-down conservative, you will not shrink while pods you cannot see might be hot.
- Unready pods are excluded from the denominator entirely when computing whether to scale up, because they are not yet serving load and their startup-burst CPU is not representative. But they are counted as “pending capacity” so the controller does not keep adding more pods while a previous scale-up’s pods are still coming online.
- Recompute the ratio after substituting the assumed values; if the direction flips after the substitution, do not scale (the honest answer under uncertainty is “stay put”).
This asymmetry mirrors the stabilization asymmetry: under uncertainty, bias toward not shrinking and not over-growing. A pod with no data should never be the reason you remove capacity, and should never be the reason you add it either. The net effect: during a rollout or a burst of new pods, the metrics of the pods you can actually trust drive the decision, and the unknowns are assumed into whichever bucket makes the controller err on the side of stability.
4. Scaling velocity policies - bounding the rate of change
Naive approach: let the formula move the count as far as it says in one tick. If the ratio says go from 10 to 80, go to 80.
Where it breaks in both directions. A single bad metric read (metrics server returned a spike for all pods because of a scrape timing artifact) can 8x the fleet in one tick - a thundering herd of pods hitting the scheduler and the image registry and the downstream database connection pools all at once. On the down side, a transient of all-pods-idle could try to halve the fleet before stabilization even gets consulted. Even correct large jumps are often undesirable: doubling a 500-pod service instantaneously can overwhelm a database that was comfortable with 500 connections.
The fix: per-direction rate policies, applied after stabilization, before the clamp. Each HPA can declare behavior.scaleUp and behavior.scaleDown policies, each a set of (type, value, periodSeconds) rules combined by selectPolicy: Max or Min:
scaleUp:
stabilizationWindowSeconds: 0
selectPolicy: Max
policies:
- type: Percent value: 100 periodSeconds: 60 # at most double per minute
- type: Pods value: 4 periodSeconds: 60 # or +4 pods, whichever is larger
scaleDown:
stabilizationWindowSeconds: 300
selectPolicy: Max
policies:
- type: Percent value: 10 periodSeconds: 60 # shrink by at most 10% per minute
The controller computes the allowed count change for each policy over its window and takes the selected (max/min) bound, then caps the move to that. So a formula that wants 10 -> 80 with the above policy is bounded to max(double=20, +4=14) = 20 this period; next period it can go to 40, then 80 - it gets there, over ~3 minutes, without shocking everything downstream. Scale-down at 10%/min is deliberately gentle, layered on top of the stabilization window, so even a legitimate sustained drop is reclaimed smoothly rather than in a cliff. The order of operations is: formula -> stabilization (trailing max on down) -> velocity cap -> min/max clamp -> write.
API Design & Data Schema
The HPA itself is a declarative object the user writes; the “API” an interviewer cares about is the controller’s read/write contract against the metrics APIs and the scale subresource.
The HPA resource (user-facing, declarative):
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: { name: checkout, namespace: shop }
spec:
scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: checkout }
minReplicas: 4
maxReplicas: 50
metrics:
- type: Resource
resource:
name: cpu
target: { type: Utilization, averageUtilization: 60 }
- type: Pods
pods:
metric: { name: http_requests_per_second }
target: { type: AverageValue, averageValue: "1000" }
behavior:
scaleUp: { stabilizationWindowSeconds: 0, policies: [...] }
scaleDown: { stabilizationWindowSeconds: 300, policies: [...] }
status:
currentReplicas: 20
desiredReplicas: 29
currentMetrics: [ { type: Resource, resource: { name: cpu, current: { averageUtilization: 85 } } } ]
lastScaleTime: "2026-11-29T10:21:33Z"
conditions:
- { type: AbleToScale, status: "True" }
- { type: ScalingActive, status: "True" }
- { type: ScalingLimited, status: "False" }
Metric reads (controller -> metrics APIs):
| Call | Method / Path | Purpose | Returns |
|---|---|---|---|
| Resource metrics | GET /apis/metrics.k8s.io/v1beta1/namespaces/{ns}/pods?labelSelector=... | CPU/mem for all target pods | per-pod usage, pre-aggregated by metrics server |
| Pod custom metrics | GET /apis/custom.metrics.k8s.io/v1beta2/namespaces/{ns}/pods/*/{metric}?labelSelector=... | app metric per pod | per-pod value from adapter |
| Object metrics | GET /apis/custom.metrics.k8s.io/v1beta2/namespaces/{ns}/{kind}/{name}/{metric} | one metric for one object | single value |
| External metrics | GET /apis/external.metrics.k8s.io/v1beta1/namespaces/{ns}/{metric}?labelSelector=... | metric from outside cluster | single value, from cloud adapter |
Scale write (controller -> apiserver):
GET /apis/apps/v1/namespaces/{ns}/deployments/{name}/scale
-> { spec: { replicas: 20 }, status: { replicas: 20, selector: "app=checkout" }, metadata: { resourceVersion: "77421" } }
PATCH /apis/apps/v1/namespaces/{ns}/deployments/{name}/scale
body: { spec: { replicas: 29 } }
precondition: resourceVersion == "77421" # optimistic concurrency
-> 200 OK, or 409 Conflict (someone else changed it; re-read and recompute next tick)
Storage choice: strongly-consistent KV (etcd), not SQL, not a TSDB. The HPA config and status are small structured objects with a strict need for linearizable reads/writes and watch semantics - exactly what etcd (the cluster datastore) provides, and it is where every other Kubernetes object already lives. A relational DB buys nothing here (no joins, no ad-hoc queries; the access pattern is get-by-key and watch-by-type). A time-series DB is the wrong tool for config but the right tool for the metrics themselves - which is exactly why metrics live in a separate metrics pipeline (Prometheus/cloud monitoring) that the HPA queries through an adapter, and are never stored in etcd. The split is the whole point: durable config in a consistent KV store, ephemeral high-volume metrics in a TSDB, and the autoscaler reads from both but owns only the former.
The recommendation ring buffer is deliberately not persisted. It lives in the controller’s memory, keyed by HPA UID. On controller restart it is empty, which means the stabilization window restarts - the first scale-down after a restart may be delayed up to a full window, which is harmless (you briefly keep extra capacity). Persisting it would add write load and a consistency problem for zero real benefit, so we do not.
Bottlenecks & Scaling
Where it breaks first: the metrics plane, not the controller. As computed in the BoE, 600,000 pods sampled every 15s is 40,000 metric reads/sec. The single metrics server that scrapes all kubelets is the first thing to fall over - it has to pull resource samples from 15,000 kubelets and serve aggregated reads to the HPA controller.
- Fix - aggregate and cache at the metrics server, never let HPAs hit kubelets directly. The HPA reads from
metrics.k8s.io, which serves from an in-memory cache the metrics server refreshes on its own schedule (default ~15-60s scrape). One HPA reconcile = one list call returning all its pods’ metrics from cache, not N kubelet round-trips. The read amplification collapses from “pods x HPAs” to “one cached list per HPA.” - Fix - shard/replicate the metrics server. For very large clusters, run multiple metrics server replicas, each responsible for a slice of nodes (shard by node), behind the aggregated API. Scraping 15,000 kubelets is partitioned; no single replica carries all of it. Custom/external metrics are served by separate adapters that can be scaled independently and that cache aggressively because the HPA tolerates slightly stale values.
Controller scaling. A single HPA controller reconciling 30,000 HPAs every 15s is 2,000 reconciles/sec, each doing a cached metric list + cheap math + a conditional write. This is fine for one well-tuned controller process, but:
- Fix - worker pool with bounded concurrency inside the controller so slow metric calls (a laggy external adapter) do not stall the whole queue; each HPA reconcile is independent and idempotent, so they parallelize trivially.
- Fix - rate-limit and jitter the metric reads so 30,000 HPAs do not all fire their reads on the same 15s boundary (a self-inflicted thundering herd against the metrics API). Spread reconciles across the interval.
Hot external-metric sources. If 5,000 HPAs all scale on the same cloud queue’s depth, they would make 5,000 identical external-metric API calls per tick, blowing the cloud provider’s rate limit.
- Fix - dedupe and cache external-metric reads in the adapter keyed by the metric query, with a short TTL (a few seconds). 5,000 HPAs asking for the same queue depth become one upstream call per TTL. The HPA’s tolerance for stale metrics is what makes this safe.
Write conflicts on the scale target. A human runs kubectl scale while the HPA is also writing, or two controllers race.
- Fix - optimistic concurrency on every scale write (resource version precondition). A 409 is not an error to retry in a tight loop; the controller just recomputes next tick with fresh state. The HPA also respects an explicit annotation to be paused, so an operator can take manual control without a fight.
Thrash / hot workload (the core problem) under scaling. The stabilization window and velocity policies (deep dives 2 and 4) are themselves the anti-thrash fix; at fleet scale the additional risk is correlated scale-ups - a cluster-wide traffic surge makes thousands of HPAs scale up at once, flooding the scheduler and node capacity.
- Fix - velocity policies cap per-HPA surge, and cluster autoscaling (a separate system) adds nodes; the HPA’s bounded per-tick growth means the collective scale-up is a ramp, not a step, which the scheduler and registry can absorb.
Single points of failure. The controller and metrics server are both SPOFs for scaling decisions, but - and this is the important property - not for the running workloads.
- Fix - leader-elected active/standby controller (only one active to avoid double-writes; standby takes over on failure). If both are down, replica counts simply freeze at their last value: the orchestrator keeps running exactly the pods it currently has. A metrics outage or controller crash degrades to “no autoscaling,” never to “wrong scaling.” That fail-safe-to-frozen behavior is deliberately baked in by keeping the controller the only writer of autoscaling decisions and keeping its state disposable.
Wrap-Up
The trade-offs that define this design:
- Stability over optimality. The stabilization window and gentle scale-down velocity mean you routinely run a few more replicas than the instantaneous metric justifies, for minutes after load drops. We pay that over-provisioning cost on purpose to eliminate thrash, because flapping a replica set is far more expensive (cold starts, dropped connections, downstream churn) than a handful of idle pods.
- Asymmetric reaction, one-sided dampening. Fast up, slow down. The low-pass filter (trailing max over the window) is applied only to scale-down, so we never trade away overload responsiveness to buy stability - genuine sustained overload is still answered in one to two ticks.
- Fail-safe to frozen. When metrics or the controller are unavailable, replica counts freeze rather than drift. A monitoring outage can never cause a scale-to-zero or a runaway. Correctness of the last decision is preserved at the cost of adaptivity during the outage.
- Separation of concerns. The HPA owns the number and nothing else - config in a consistent KV store, metrics in a separate TSDB behind an aggregated API, pod placement in the orchestrator. Each layer scales and fails independently.
- Conservative under uncertainty. Missing and unready pod metrics are assumed into whichever bucket avoids a wrong decision, so incomplete data never drives a scale action in the risky direction.
One-line summary: a stateless periodic reconciler that recomputes desired replicas per workload from a proportional metric ratio, takes the max across metrics, dampens scale-down with a trailing-maximum stabilization window and bounded velocity while keeping scale-up fast, clamps to min/max, and reads from an aggregated, cached, shardable metrics plane so the fan-in - not the math - is what you scale.
Comments