ArchitectMind
  1. Home
  2. Java Ecosystem
  3. Book 7 · Application Architecture & Distributed Systems
  4. Volume VII
  5. Elastic Scaling
Book 7 · Volume VII — Resilience, Scalability & Distributed Data · Topic 1.4

Elastic Scaling

Metrics and autoscaling

8 min readStage 3 · Systems8 interview questions
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
Covers
Metrics; Autoscaling
On this page
  1. 1. Concept / Definition
  2. 2. Why It Exists
  3. 3. Core Concepts
  4. 4. How It Works Internally — Scaling Lag
  5. 4A. Deep Dive — Scaling Safely
  6. 5. APIs / Features / Syntax
  7. 6. Practical Examples
  8. 7. Common Problems & Mistakes
  9. 8. Performance & Production Considerations
  10. 9. Architecture & Design Considerations
  11. 10. Interview Questions & Answers

1Concept / Definition

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.

Elastic capacity tracks load
Figure 1 — Elastic capacity tracks load
TOC conceptDefinition
MetricsSignals 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
AutoscalingControl 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.

Monthly compute cost (illustrative)
Figure 2 — Monthly compute cost (illustrative)

3Core Concepts

3.1 Metrics

Metrics (TOC) for scaling
Figure 3 — Metrics (TOC) for scaling
JAVA
// Expose a business-level metric for scaling: in-flight checkout requests per pod
@Component
class InflightMetrics {
    private final 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(); }
    }
}
WorkloadRecommended metric
CPU-bound API (pricing calc)CPU utilisation ~60%
I/O-bound API (checkout)Requests or in-flight per pod
Kafka consumersConsumer lag (KEDA)
SQS workersQueue depth per worker
Batch windowsSchedule (cron) + queue
Table 2 — Metric per workload type

3.2 Autoscaling

Autoscaling (TOC) control loop
Figure 4 — Autoscaling (TOC) control loop
YAML
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata: { name: checkout }
spec:
  scaleTargetRef: { apiVersion: apps/v1, kind: Deployment, name: checkout }
  minReplicas: 6                      # survive one AZ loss at baseline
  maxReplicas: 60
  metrics:
    - type: Pods
      pods:
        metric: { name: checkout_inflight }
        target: { type: AverageValue, averageValue: "20" }
    - type: Resource
      resource: { name: cpu, target: { type: Utilization, averageUtilization: 65 } }
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 0
      policies: [{ type: Percent, value: 100, periodSeconds: 30 }]
    scaleDown:
      stabilizationWindowSeconds: 300
      policies: [{ type: Percent, value: 20, periodSeconds: 60 }]
YAML
# KEDA: scale Kafka consumers on lag (up to partition count)
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata: { name: invoice-consumer }
spec:
  scaleTargetRef: { name: invoice-consumer }
  minReplicaCount: 2
  maxReplicaCount: 24                 # = partitions
  triggers:
    - type: kafka
      metadata: { bootstrapServers: msk:9098, consumerGroup: billing-svc,
                  topic: orders.events.v1, lagThreshold: "500" }
Autoscalers on AWS / EKS
Figure 5 — Autoscalers on AWS / EKS

4How It Works Internally — Scaling Lag

Scale-out timeline during a flash sale
Figure 6 — Scale-out timeline during a flash sale
Lag componentTypicalReduce by
Metric collection15–60 sShorter scrape interval
HPA sync + decision15 s—
Node provisioning45–90 sKarpenter, warm pools, over-provisioning pods
Image pull5–30 sSmall images, caching
JVM start + warm-up10–40 sCDS/AOT cache, CRaC, readiness gating
Table 3 — Where scaling time goes
DOCKERFILE
# Faster JVM start: application class-data sharing / AOT cache (Java 25)
RUN java -XX:AOTCacheOutput=app.aot -Dspring.context.exit=onRefresh -jar app.jar
ENTRYPOINT ["java", "-XX:AOTCache=app.aot", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"]

4ADeep Dive — Scaling Safely

Autoscaling rules
Figure 7 — Autoscaling rules
RiskMitigation
Scaling app overwhelms DBConnection caps (pool × maxReplicas ≤ DB max), RDS Proxy
FlappingScale-down stabilisation, cooldowns
Known spikes (sale at 12:00)Scheduled pre-scale / KEDA cron
Scale to zero cold startKeep min ≥ 1 for latency-sensitive paths
Spot interruptionsMixed on-demand/Spot, PDBs
Runaway costmaxReplicas, budgets, alerts
Table 4 — Guardrails

5APIs / Features / Syntax

NeedTooling
Pod scalingHPA v2, KEDA
Node scalingKarpenter, Cluster Autoscaler
VMs/containersEC2 ASG target tracking, ECS service autoscaling
MetricsMicrometer, Prometheus Adapter, CloudWatch
Start-upCDS/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 50024 replicas (capped)
Table 7 — Event-driven scaling

6.5 Worked example — min replicas

3 AZs × 2Min 6
Table 8 — AZ resilience

6.6 Worked example — DB cap

Pool 10 × max 60 pods = 600Aurora max_connections 1,000 ✔
Table 9 — Protect DB

6.7 Worked example — scale-down

20%/min after 5 min stableAvoid flapping
Table 10 — Gentle

6.8 Worked example — scheduled

KEDA cron 11:45–13:00 min 40Pre-scale
Table 11 — Known events

6.9 Worked example — over-provisioning

Low-priority placeholder podsInstant node capacity
Table 12 — Headroom trick

6.10 Worked example — Spot

70% Spot for stateless workersCost ↓, PDBs protect
Table 13 — Economics

6.11 Worked example — latency metric

Scale on p95Lagging, noisy
Table 14 — Prefer leading metrics

6.12 Worked example — start time

JVM 18 s → 6 s with AOT cacheFaster scale-out
Table 15 — Start-up matters

6.13 Worked example — readiness gating

Ready only after warm-upNo cold traffic
Table 16 — Quality

6.14 Worked example — scale to zero

Nightly report workersKEDA min 0
Table 17 — Idle cost 0

6.15 Worked example — VPA

Recommend requestsRight-size pods
Table 18 — Complement HPA

6.16 Worked example — max replicas

Cap at 60Protect budget & DB
Table 19 — Guardrail

6.17 Worked example — dashboards

Desired vs current replicas, metric vs targetVisibility
Table 20 — Operations

6.18 Worked example — load test

Ramp 1× → 5× in 60 sVerify autoscaling response
Table 21 — Prove it

6.19 Worked example — ADR

DecisionRationale
HPA on in-flight + CPU; KEDA for consumers; KarpenterRight 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

ConceptAnswer
MetricsLeading, bottleneck-aligned
AutoscalingControl 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.

8Performance & Production Considerations

AspectGuideline
MetricsLeading, per workload
BoundsMin for AZ loss, max for DB/budget
SpeedFast start, node headroom
StabilityStabilisation windows
CostSpot, scale-down, VPA
Table 25 — Operational guidelines

9Architecture & Design Considerations

  • Autoscaling assumes stateless, fast-starting services.
  • Choose metrics per workload type.
  • Combine reactive and scheduled scaling.
  • Guard non-elastic dependencies.

10Interview Questions & Answers

Q1L1 · BasicConcept

What is elastic scaling?

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.

Test your knowledge on this topic →Flashcards from this topic's 8 questions, filtered by level and type.

Free question pack

Get 100 free Core Java interview questions

Subscribe for the Book 1 question pack (PDF, every answer explained) and new tutorials once a week. No spam, unsubscribe anytime. What is in the pack?

Almost done! Check your inbox and click the confirmation link. Your download link arrives as soon as you confirm.