Book 7 · Volume VII — Resilience, Scalability & Distributed Data · Topic 1.4
Elastic Scaling
Metrics and autoscaling
8 min readStage 3 · Systems8 interview questions
Written byMaheshFounder · Senior Technical Architect
Chapter
Chapter 1 — Scalability Architecture
Prerequisites
Topics 1.1–1.3
You will be able to
Choose scaling metrics that reflect each workload's real bottleneck, configure HPA, KEDA and node autoscaling with sensible targets and stabilisation, reduce scaling lag with faster start-up and pre-scaling, protect non-elastic dependencies, and balance cost against responsiveness
Elastic scaling automatically adjusts capacity to match demand — adding instances when load rises and removing them when it falls. It relies on metrics that indicate how loaded the system is and autoscaling controllers that compare those metrics with targets and change the number of pods, nodes or instances.
Figure 1 — Elastic capacity tracks load
TOC concept
Definition
Metrics
Signals that represent load or saturation — CPU, requests per instance, queue length or consumer lag, latency, custom business rates or schedules — collected continuously and chosen to correlate with the workload's actual bottleneck
Autoscaling
Control loops (HPA, KEDA, Karpenter, EC2 Auto Scaling) that compute desired capacity from metrics and targets, apply it within min/max bounds and stabilisation rules, and provision underlying nodes as needed
Table 1 — The two TOC concepts
2Why It Exists
Provisioning for peak all year wastes money; provisioning for average fails on peaks. Elastic capacity lets cost follow demand, and cloud platforms make it automatic.
Elasticity also changes how capacity planning works. Instead of predicting peak load months ahead and buying for it, teams set bounds and targets and let control loops follow demand within them. That only works when the workload is built for it: services must be stateless or keep state outside the pod, start in seconds, and tolerate instances appearing and disappearing at any time. Real demand is rarely flat. An e-commerce site may see quiet nights, a lunchtime peak and a sale that quadruples traffic within a minute, while batch and event-driven workloads can go from idle to a large backlog almost instantly. Elastic scaling turns that variability into lower cost during quiet periods while protecting latency at the peaks, provided the metrics, limits and start-up times are chosen deliberately.
Figure 2 — Monthly compute cost (illustrative)
3Core Concepts
3.1 Metrics
Figure 3 — Metrics (TOC) for scaling
JAVA
// Expose a business-level metric for scaling: in-flight checkout requests per pod@Componentclass InflightMetrics {privatefinal AtomicInteger inflight = new AtomicInteger(); InflightMetrics(MeterRegistry reg) { Gauge.builder("checkout.inflight", inflight, AtomicInteger::get).register(reg); } <T> T track(Supplier<T> call) { inflight.incrementAndGet();try { return call.get(); } finally { inflight.decrementAndGet(); } }}
Connection caps (pool × maxReplicas ≤ DB max), RDS Proxy
Flapping
Scale-down stabilisation, cooldowns
Known spikes (sale at 12:00)
Scheduled pre-scale / KEDA cron
Scale to zero cold start
Keep min ≥ 1 for latency-sensitive paths
Spot interruptions
Mixed on-demand/Spot, PDBs
Runaway cost
maxReplicas, budgets, alerts
Table 4 — Guardrails
5APIs / Features / Syntax
Need
Tooling
Pod scaling
HPA v2, KEDA
Node scaling
Karpenter, Cluster Autoscaler
VMs/containers
EC2 ASG target tracking, ECS service autoscaling
Metrics
Micrometer, Prometheus Adapter, CloudWatch
Start-up
CDS/AOT cache, CRaC, small images
Table 5 — Toolkit
6Practical Examples
6.1 Flash sale at noon
HPA alone took about 100 seconds to add capacity when traffic quadrupled at 12:00, and p99 breached for two minutes. A scheduled pre-scale to 40 pods at 11:50, Karpenter over-provisioning pods and AOT-cached JVM start-up removed the breach.
6.2 CPU was the wrong metric
Checkout is I/O-bound; CPU stayed at 35% while threads queued. Scaling on in-flight requests per pod added pods at the right time.
6.3 Worked example — HPA formula
4 pods at 90% CPU, target 60%
ceil(4 × 90/60) = 6
Table 6 — Desired replicas
6.4 Worked example — KEDA lag
Lag 12,000, threshold 500
24 replicas (capped)
Table 7 — Event-driven scaling
6.5 Worked example — min replicas
3 AZs × 2
Min 6
Table 8 — AZ resilience
6.6 Worked example — DB cap
Pool 10 × max 60 pods = 600
Aurora max_connections 1,000 ✔
Table 9 — Protect DB
6.7 Worked example — scale-down
20%/min after 5 min stable
Avoid flapping
Table 10 — Gentle
6.8 Worked example — scheduled
KEDA cron 11:45–13:00 min 40
Pre-scale
Table 11 — Known events
6.9 Worked example — over-provisioning
Low-priority placeholder pods
Instant node capacity
Table 12 — Headroom trick
6.10 Worked example — Spot
70% Spot for stateless workers
Cost ↓, PDBs protect
Table 13 — Economics
6.11 Worked example — latency metric
Scale on p95
Lagging, noisy
Table 14 — Prefer leading metrics
6.12 Worked example — start time
JVM 18 s → 6 s with AOT cache
Faster scale-out
Table 15 — Start-up matters
6.13 Worked example — readiness gating
Ready only after warm-up
No cold traffic
Table 16 — Quality
6.14 Worked example — scale to zero
Nightly report workers
KEDA min 0
Table 17 — Idle cost 0
6.15 Worked example — VPA
Recommend requests
Right-size pods
Table 18 — Complement HPA
6.16 Worked example — max replicas
Cap at 60
Protect budget & DB
Table 19 — Guardrail
6.17 Worked example — dashboards
Desired vs current replicas, metric vs target
Visibility
Table 20 — Operations
6.18 Worked example — load test
Ramp 1× → 5× in 60 s
Verify autoscaling response
Table 21 — Prove it
6.19 Worked example — ADR
Decision
Rationale
HPA on in-flight + CPU; KEDA for consumers; Karpenter
Right metrics per workload
Table 22 — Recorded
6.20 Worked example — review checklist
Check
✔
Metric matches bottleneck
✔
Min/max sensible
✔
Start-up optimised
✔
Dependencies protected
✔
Table 23 — Elastic scaling review
6.21 Worked example — interview answer
Concept
Answer
Metrics
Leading, bottleneck-aligned
Autoscaling
Control loop with bounds and lag
Table 24 — Structured answer
7Common Problems & Mistakes
CPU scaling for I/O-bound services.
Slow JVM start-up negating autoscaling.
No pre-scaling for known events.
Autoscaling into a database limit.
Flapping without stabilisation.
Scale-to-zero on latency-critical paths.
These mistakes have one thing in common: the autoscaler does exactly what it is told, and what it is told is wrong. Scaling an I/O-bound checkout on CPU waits until threads are already queued, as in the example where CPU sat at 35% during overload. Slow JVM start-up and node provisioning can add a minute or more, so purely reactive scaling arrives after the spike has already hurt users; scheduled pre-scaling and AOT caching close that gap. Scaling the application without a connection cap simply moves the bottleneck to the database, which then fails for every pod at once. Missing stabilisation makes replicas oscillate and keeps caches cold, while scale-to-zero on a latency-critical path makes the first user after a quiet period pay for a cold start.
Elastic scaling is automatically adjusting capacity to match demand: adding pods, nodes or instances when load rises and removing them when it falls. It has two parts. Metrics represent load or saturation, such as CPU, in-flight requests per pod, queue depth or consumer lag. Autoscaling controllers, such as the Kubernetes HPA, KEDA, Karpenter or EC2 Auto Scaling, compare those metrics with targets and change capacity within minimum and maximum bounds. The goal is that cost follows demand instead of being sized for peak all year, while latency stays within SLOs during spikes. It works best for stateless services that start quickly.
Q2L1 · BasicInternals
What does the HPA do?
The Horizontal Pod Autoscaler is a Kubernetes control loop that adjusts the replica count of a Deployment or StatefulSet based on metrics compared with targets. By default every 15 seconds it reads metrics through the metrics APIs: resource metrics such as CPU, pod metrics such as in-flight requests exposed through the Prometheus Adapter, or external metrics. It computes desired replicas as current replicas times current value divided by target, rounded up; in the note, four pods at 90% CPU with a 60% target gives six. With several metrics it takes the highest result, then applies the min and max bounds and behaviour policies such as scale-down stabilisation.
Q3L2 · IntermediateTricky
Why might CPU be a poor scaling metric?
Because CPU reflects load only when CPU is the bottleneck. An I/O-bound service such as checkout spends most of its time waiting on databases, payment providers and other services, so under overload its threads, connection pools or request queues saturate while CPU stays low. In the note's example, CPU sat at 35% while requests queued and latency rose, so the HPA never scaled out. Better metrics lead the real bottleneck: in-flight requests or requests per second per pod for I/O-bound APIs, consumer lag for Kafka consumers and queue depth for SQS workers. CPU remains a good metric for compute-heavy services such as pricing calculations.
Q4L2 · IntermediateDesign
How do you scale Kafka consumers?
Scale on consumer lag, usually with KEDA, and cap replicas at the partition count. KEDA's Kafka scaler reads the group's lag and divides it by the lagThreshold to compute desired replicas, so 12,000 records of lag with a threshold of 500 asks for 24 consumers. The cap matters because each partition is consumed by at most one member of a group, so consumers beyond the partition count sit idle. Set a sensible minimum to avoid cold starts, and remember that each scaling event triggers a group rebalance; cooperative rebalancing shortens the pause. If you need more parallelism than partitions, add partitions or process records concurrently inside each consumer.
Q5L3 · Senior EngineerInternals
What causes autoscaling lag?
Autoscaling lag is the sum of several delays between load rising and new capacity serving traffic. Metric collection takes 15 to 60 seconds, depending on the scrape interval, and the HPA syncs roughly every 15 seconds. If no node has room, provisioning a new one takes 45 to 90 seconds, then the image must be pulled, which takes 5 to 30 seconds. Finally the JVM starts and warms up, 10 to 40 seconds for a typical Spring Boot service, before readiness probes pass. Together that can approach two minutes, which in the note's flash sale meant a breached p99. The fixes are faster scraping, Karpenter with headroom, small images, AOT caching and pre-scaling.
Q6L3 · Senior EngineerConcept
How do you prevent flapping?
Flapping is replicas repeatedly scaling up and down as a noisy metric crosses its target, which wastes start-up work, keeps caches cold and can cause errors during the churn. The main defence is the HPA behaviour settings. A scale-down stabilisation window, for example 300 seconds, makes the HPA use the highest recommendation within that window before removing pods. Rate-limiting policies, such as removing at most 20% of pods per minute, keep scale-down gentle. Scale-up can stay fast, with no window and up to 100% growth every 30 seconds, because under-provisioning hurts users more than briefly over-provisioning. Smoother metrics and sensible targets also help.
Q7L4 · Technical ArchitectDesign
How do you protect the database when autoscaling?
Make the database limit part of the scaling design rather than an afterthought. First, cap total connections: pool size times maximum replicas must stay below the database's max_connections with headroom, as in the note's 10 times 60, or 600, against Aurora's 1,000. That makes maxReplicas a protection for the database as well as for the budget. Second, put RDS Proxy or PgBouncer in front, so many pods share fewer database connections. Third, keep pools small and connection timeouts short, so overload fails fast instead of piling up. Finally, reduce database work per request with caching and read replicas, because the database does not scale as elastically as pods.
Q8L5 · Solution ArchitectScenario
How would you prepare for a flash sale?
I would combine rehearsal, pre-scaling and protection of everything that cannot scale quickly. Weeks ahead, run a ramp load test, say from one to five times normal traffic in 60 seconds, to measure scaling lag and find the first bottleneck. Before the sale, pre-scale on a schedule, for example a KEDA cron trigger raising checkout to 40 pods at 11:45, keep node headroom with Karpenter and low-priority placeholder pods, and raise AWS service quotas. Make start-up fast with AOT caching and readiness gating. Protect dependencies with connection caps, RDS Proxy, caching and load shedding, and agree dashboards and rollback decisions with on-call before the sale starts.