Resources, Scheduling & Autoscaling: Requests/Limits, QoS, Quotas, Taints, Spread, Priorities, HPA/VPA
"When you specify the resource request for containers in a Pod, the kube-scheduler uses this information to decide which node to place the Pod on. When you specify a resource limit for a container, the kubelet enforces those limits so that the running container is not allowed to use more of that resource than the limit you set." — Kubernetes documentation, Resource Management for Pods and Containers
Summary: Two numbers per container decide almost everything on this page: the request is what the scheduler reserves and what you pay for, the limit is what the kernel enforces with CPU throttling or an OOM kill; QoS classes, eviction, quotas, placement rules, priorities and every autoscaler (HPA, VPA, KEDA, Cluster Autoscaler, Karpenter) are built on top of them. Focus: Resource requests vs resource limits (CPU millicores and CFS quota throttling, memory limits and OOMKilled with exit code 137, ephemeral-storage), QoS classes (Guaranteed, Burstable, BestEffort) and node-pressure eviction, the limits debate, LimitRange and ResourceQuota, the kube-scheduler (filtering, scoring, the scheduling framework, binpacking vs spreading), nodeSelector, node affinity, pod affinity and anti-affinity, topologySpreadConstraints, taints and tolerations, PriorityClass and preemption, pod overhead, Pending pods and the descheduler, the HorizontalPodAutoscaler (autoscaling/v2 metrics, behavior, scale to zero), the VerticalPodAutoscaler and in-place pod resize, KEDA (ScaledObject, ScaledJob, Kafka, RabbitMQ, Redis, Prometheus and cron scalers), Cluster Autoscaler vs Karpenter, cost and right-sizing, and how a Go service (GOMAXPROCS, GOMEMLIMIT, graceful scale-down) and a Laravel app (php-fpm pm.max_children, queue worker autoscaling) live inside these numbers. Learning goal: Size a container from measurements instead of guesses and predict its QoS class, its eviction rank and its bill; read a FailedScheduling event or a throttling counter and say what to change; write the affinity, spread, taint and priority rules that place a workload where it belongs; and choose and configure the right autoscaler at the Pod level and the node level without the two fighting each other.
This chapter is the fourth in the Kubernetes group. The control plane, the kubelet and how a cluster is installed are Kubernetes Architecture & Setup; Pods, probes, Deployments, Jobs, rollouts and the PodDisruptionBudget object itself are Kubernetes Workloads, whose orders-api, shop-web and shop-queue manifests this page extends with resources, placement and autoscaling; ConfigMaps, Secrets and volumes are Config, Secrets & Storage; the kernel side of cgroups v2 (cpu.max, memory.max, PSI) is Containers Under the Hood; the pids limit and other hardening controls are Container Security; reading events, kubectl top and OOMKilled triage as a workflow are Kubernetes Observability & Troubleshooting; writing a custom scheduler or controller in Go is Extending Kubernetes; instance types, spot capacity and managed node groups as cloud products are Cloud Provider Primitives. The architectural view (why autoscale, scheduling as a model) is Containers & Kubernetes and Scaling Strategies; traffic in front of the replicas is Load Balancing; estimating the numbers before you have them is Capacity Estimation and Capacity Planning & Disaster Recovery. Queue-consumer scaling as a messaging pattern is Competing Consumers & Scaling Consumers; the Go garbage collector and GOMEMLIMIT are in Pointers, the goroutine scheduler that GOMAXPROCS feeds is in Goroutines & Channels, and why more replicas can exhaust a database is Connection Pooling. Command tables are in the kubectl cheatsheet.
Kubernetes version: the page is written against v1.37 (the releases page lists 1.37.2, released 2026-10-13); feature stages are quoted from the feature-gate files of the Kubernetes website. KEDA docs 2.21, Karpenter karpenter.sh/v1, VPA from kubernetes/autoscaler master, Go 1.27.4 for the code.
Page map
| If you are looking for | Go to |
|---|---|
| The whole page in four tables | Everything in one minute |
| Why requests and limits exist at all | Why it exists |
| Versions: scheduling framework, autoscaling/v2, in-place resize, scale to zero | Where it comes from |
| What a request reserves and what a limit enforces | Requests and limits |
Millicores, cpu.max, CFS quota, throttling, cpu.stat | CPU |
| Memory limits, OOMKilled, exit code 137 | Memory |
ephemeral-storage, emptyDir sizeLimit | Ephemeral storage |
| Guaranteed, Burstable, BestEffort | QoS classes |
Node pressure, eviction thresholds, eviction order, oom_score_adj | Node-pressure eviction |
| CPU limits on or off, memory limit = request | The limits debate |
| Namespace defaults and totals | LimitRange and ResourceQuota |
| Filtering, scoring, plugins, binpacking vs spreading | The scheduler |
nodeSelector, requiredDuringScheduling..., preferredDuringScheduling... | Node affinity |
| Co-locating or separating Pods | Pod affinity and anti-affinity |
topologySpreadConstraints, maxSkew, minDomains | Topology spread |
NoSchedule, PreferNoSchedule, NoExecute, tolerationSeconds, built-in taints | Taints and tolerations |
PriorityClass, preemption, preemptionPolicy: Never | Priority and preemption |
| RuntimeClass overhead, Pod-level resources, DRA | Pod overhead and friends |
Pending Pods, FailedScheduling, descheduler | Pending Pods |
| HorizontalPodAutoscaler v2, metrics, behavior | HPA |
| VerticalPodAutoscaler modes, in-place resize | VPA |
| Event-driven scaling, scale to zero | KEDA |
| Adding and removing nodes | Cluster Autoscaler vs Karpenter |
| Bills, right-sizing, spot | Cost |
| PDBs, drains and graceful scale-down | PDB interplay |
| cgroup mapping, HPA arithmetic, knobs, error messages | Mechanics |
| Code | Go, Laravel |
| Ten classic problems and their fixes | Solving the classic problems |
| Which limits, which placement rule, which autoscaler | Choosing |
| From one node to many clusters | In architecture |
| Commands with expected output | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
Requests and limits, per resource.
| Resource | Unit | Request is used by | Limit is enforced by | What happens when usage passes the limit |
|---|---|---|---|---|
cpu | cores; 250m = 0.25 = "250 millicores" | Scheduler (fit), kernel CPU weight (share under contention), HPA utilisation | Kernel CFS bandwidth (cpu.max quota per 100 ms period) | Throttled: threads wait for the next period. Never killed |
memory | bytes; Mi, Gi (not m!) | Scheduler (fit), eviction ranking, oom_score_adj, quota | Kernel memory.max | OOM kill of a process in the container: OOMKilled, exit code 137, restart |
ephemeral-storage | bytes | Scheduler (fit), quota | Kubelet measures writable layer, logs, emptyDir | The Pod is evicted |
hugepages-2Mi etc. | bytes | Scheduler | Allocation fails | Cannot be overcommitted; request must equal limit |
Extended (nvidia.com/gpu) | integer | Scheduler | Device plugin | Whole units only |
QoS classes (from the containers' requests and limits; you never set it directly).
| Class | Rule | Eviction under node pressure | oom_score_adj |
|---|---|---|---|
| Guaranteed | Every container: CPU and memory limits set and equal to requests (or: Pod-level CPU and memory requests equal to Pod-level limits) | Last, and only if system daemons overrun their reservation | -997 |
| Burstable | Not Guaranteed, at least one CPU or memory request or limit | Before Guaranteed if usage exceeds the request | 2 to 999, lower for bigger memory requests |
| BestEffort | No CPU or memory request or limit anywhere, container or Pod level | First | 1000 |
Placement tools.
| Tool | Says | Hard or soft | Typical use |
|---|---|---|---|
nodeSelector | "Only nodes with these labels" | Hard | kubernetes.io/arch: arm64 |
| Node affinity | Same, with In, NotIn, Exists, Gt, Lt and weights | required... hard, preferred... soft (weight 1-100) | Spot vs on-demand, instance family |
| Pod affinity | "Near Pods with these labels" in a topology (node, zone) | Hard or soft | Cache next to its app |
| Pod anti-affinity | "Away from Pods with these labels" | Hard or soft | One replica per node |
topologySpreadConstraints | "Keep the count difference per domain at most maxSkew" | DoNotSchedule hard, ScheduleAnyway soft | Even spread across zones |
| Taints (on nodes) + tolerations (on Pods) | "Keep out unless you tolerate me" | NoSchedule hard, PreferNoSchedule soft, NoExecute also evicts | GPU, batch, spot pools; node problems |
| PriorityClass | "Schedule me first; evict lower priority if needed" | Preemption unless preemptionPolicy: Never | Checkout API over reports |
Autoscalers.
| Autoscaler | Changes | Reacts to | Ships with Kubernetes? |
|---|---|---|---|
HorizontalPodAutoscaler (autoscaling/v2) | Replica count | Resource, Pods, Object, External, ContainerResource metrics | Yes (controller-manager); needs metrics-server for CPU/memory |
| VerticalPodAutoscaler | Requests (and limits) | Usage history (Recommender) | No, install from kubernetes/autoscaler |
| KEDA | Replica count, 0 to N; Jobs | Built-in scalers for event sources (Kafka lag, queue length, Prometheus, cron, ...) | No, CNCF project; drives an HPA |
| Cluster Autoscaler | Nodes in node groups | Pending Pods; underused nodes | No, per cloud provider |
| Karpenter | Nodes (any fitting instance type) | Pending Pods; consolidation | No; installed per cloud provider (the karpenter.sh docs describe AWS) |
| Descheduler | Evicts Pods so they reschedule better | Policy (duplicates, utilisation, violated spread) | No, kubernetes-sigs/descheduler |
Why it exists
A node is a shared machine. Without numbers, the scheduler can only count Pods, and the first memory-hungry neighbour starves everyone else on the node. Kubernetes splits the problem in two. The request is a reservation: the scheduler adds up requests, compares them with the node's allocatable capacity and refuses a node whose reservations are full, whatever the live usage is. The limit is a ceiling: the kernel's cgroups stop a container from using more than its limit, by making it wait (CPU) or by killing it (memory). The distance between the two is overcommit: the room where a container may use idle capacity that is reserved by someone else.
Everything else on this page follows from that split. QoS classes and eviction order come from how usage compares with requests. Quotas cap the sum of requests per namespace. The scheduler's filters and scores read requests, never live usage. The HPA measures CPU "utilisation" as a percentage of the request. The cluster autoscalers add a node only when a Pod's requests fit nowhere. And cloud bills for nodes are, in practice, bills for the sum of requests, because requested capacity cannot be given to anyone else.
| Simpler choice | Richer choice | What you buy | What you pay |
|---|---|---|---|
| No requests (BestEffort) | Requests from measurements | Predictable placement, eviction last, correct HPA maths | Measuring, and paying for reserved capacity |
| Limits = requests (Guaranteed) | Limits above requests (Burstable) | Use of idle node capacity | Noisy neighbours; eviction before Guaranteed Pods |
| CPU limit | No CPU limit, request only | No throttling, use idle CPU | No hard cap per container; runtime sizing (GOMAXPROCS) by hand |
nodeSelector | Affinity, spread, taints | Zone resilience, dedicated pools | More rules to keep consistent |
| Fixed replicas | HPA / KEDA | Capacity follows load, scale to zero | Cold starts, metric pipelines |
| Fixed node groups | Cluster Autoscaler / Karpenter | Pay for what is requested | Node start-up latency, disruption on scale-down |
| Hand-set requests | VPA recommendations | Right-sized requests | Restarts (or in-place resizes) and drift from Git |
The analogy used through this page: a restaurant with a host at the door. Each party books a number of seats (the request); the host seats a party only at a table with enough unbooked seats, even if the people already sitting there have not touched their food (the scheduler reads requests, not usage). A party may spread onto empty chairs nearby while nobody else needs them (usage above the request), but there is a hard rule for each party: at most so many plates per hour (the CPU limit: you wait for the next serving) and a fixed table size (the memory limit: if you overflow it, you are removed from the table and must sit down again, an OOM kill). When the restaurant is full and the kitchen runs low, the manager asks parties to leave, starting with walk-ins who booked nothing and those using far more than they booked (eviction order). VIP bookings may bump ordinary ones (priority and preemption). Some tables are reserved for a private event and only guests with an invitation sit there (taints and tolerations); some parties ask for a window seat or to be near friends (affinity). When the queue at the door gets long, the owner opens a second room (the cluster autoscaler), and the number of waiters follows the number of diners (the HPA).
Three common misunderstandings, up front
- "The scheduler places Pods where there is free CPU." It places them where there are free requests. The docs: "although actual memory or CPU resource usage on nodes is very low, the scheduler still refuses to place a Pod on a node if the capacity check fails". A cluster at 10 % real CPU can have Pending Pods. See The scheduler.
- "A CPU limit protects my latency." A CPU limit can only hurt the container that has it: when the quota for the 100 ms period is used up, every thread of that container waits. Protection from neighbours comes from the request (CPU weight). See CPU and The limits debate.
- "HPA at 70 % CPU means 70 % of the node" or "of the limit". HPA utilisation is measured against the container's CPU request. With a 500m request, 70 % is 350m per Pod on average; a container without a CPU request gives the HPA no utilisation at all. See HPA.
Where it comes from
| When | What happened | Source |
|---|---|---|
| v1.14 | Pod priority and preemption stable | Pod priority page, feature state |
| v1.18 | taint-based eviction and tolerationSeconds behaviour stable (taint page feature state v1.18) | Taint and toleration page |
| v1.19 | Scheduling framework stable: plugins at QueueSort, PreFilter, Filter, PostFilter, Score, Reserve, Permit, Bind | Scheduling framework page |
| v1.23 | autoscaling/v2 stable: custom and external metrics, behavior | HPA page feature state |
| v1.24 | PodOverhead and NonPreemptingPriority (preemptionPolicy: Never) stable | Feature-gate files |
| v1.27 | In-place Pod resize alpha; matchLabelKeys for spread beta (default on) | Feature-gate files |
| v1.29 | Taint-based eviction moved from the node controller to a separate taint-eviction-controller | Taint and toleration page |
| v1.30 | minDomains for spread no longer behind a gate; HPAContainerMetrics (ContainerResource metrics) stable | Spread page, feature-gate file |
| v1.33 | In-place resize beta (default on); nodeAffinityPolicy / nodeTaintsPolicy stable | Feature-gate files |
| v1.34 | Dynamic Resource Allocation stable; Pod-level resources beta; matchLabelKeys merged into labelSelector explicitly | Feature-gate files, spread page |
| v1.35 | In-place Pod vertical scaling stable (locked on); numeric Gt/Lt toleration operators alpha | Feature-gate files |
| v1.37 | HPAScaleToZero beta and on by default (minReplicas: 0 with Object/External metrics); HPAConfigurableTolerance stable; MemoryQoS beta | Feature-gate files, HPA page |
| Go 1.19 | Soft memory limit: GOMEMLIMIT, runtime/debug.SetMemoryLimit | Go 1.19 release notes |
| Go 1.25 | Container-aware GOMAXPROCS: the runtime reads the cgroup CPU limit and updates periodically (containermaxprocs, updatemaxprocs) | Go 1.25 release notes, GODEBUG history |
| VPA 1.4.0 / 1.5.0 / 1.7.0 | Auto mode deprecated (1.4.0); InPlaceOrRecreate gate on by default (1.5.0) and removed (1.7.0) | VPA docs |
| Karpenter v1 | karpenter.sh/v1 NodePool API with consolidationPolicy, consolidateAfter, disruption budgets | Karpenter docs |
Two lines of work meet here. The first is the scheduler: it started as a fixed list of predicates (filters) and priorities (scoring functions), and the scheduling framework (stable in v1.19) turned both into plugins at named extension points, which is why today's knobs are plugin arguments (NodeResourcesFit with LeastAllocated, MostAllocated or RequestedToCapacityRatio). The second is elasticity: the HPA (in tree), then the VPA, Cluster Autoscaler and later Karpenter as separate projects under SIG Autoscaling or the cloud vendors, and KEDA (a CNCF project) for event-driven sources the HPA never had. In-place resize closed the gap that made the VPA disruptive, and native HPA scale to zero (v1.37) narrows the gap that made KEDA mandatory for idle queues.
The concept catalogue
Each block follows the same order: plain words, the common misunderstanding, the definition, a sequence, real scenarios, what each product or tool does, and the fix.
Resource requests and resource limits Must-know
In plain words: The request is the amount of CPU and memory you book for a container; the scheduler finds a node with that much unbooked. The limit is the most the container is allowed to use; the kernel holds it to that.
Common misunderstanding: "Requests are a minimum the container always gets and limits are what it usually uses." A request is a reservation used for placement and for sharing under contention; a container can use more than its request when the node is idle ("it's possible (and allowed) for a container to use more resource than its request"), and far less without anyone noticing, which is the waste you pay for.
Definition: Each container may set resources.requests and resources.limits for cpu, memory, ephemeral-storage, hugepages-<size> and extended resources. "If you specify a limit for a resource, but do not specify any request, and no admission-time mechanism has applied a default request for that resource, then Kubernetes copies the limit you specified and uses it as the requested value." The Pod's effective request aggregates its containers; "Because init containers run before the other containers, this is not a plain sum", and any Pod overhead is added on top. The scheduler "ensures that, for each resource type, the sum of the resource requests of the scheduled containers is less than the capacity of the node", using the node's status.allocatable, which is capacity minus kubeReserved, systemReserved and the hard eviction threshold. For cpu and memory, "the kubelet treats a limit of 0 the same as not specifying a limit at all".
Pod orders-api-7c9: requests cpu 500m, memory 256Mi; limits memory 256Mi
1 API server stores the Pod (LimitRange may add defaults, ResourceQuota counts requests)
2 scheduler: node-a allocatable cpu 1800m, requested 1500m -> 300m free < 500m: filtered out
3 scheduler: node-b allocatable cpu 3800m, requested 1200m -> fits; score; bind to node-b
4 kubelet on node-b: container runtime writes cgroup files
cpu.weight <- from the 500m request (a share, not a cap)
cpu.max <- "max 100000" (no CPU limit)
memory.max <- 268435456 (256Mi)
5 at runtime: CPU above 500m is allowed while node-b is idle; memory above 256Mi -> OOM killReal scenarios:
- A node shows 15 % CPU in the cloud console, yet new Pods stay Pending with
Insufficient cpu: requests are full because every Deployment asked for1CPU "to be safe". - A Go API without requests runs fine for months, then gets evicted first during a memory spike on its node, because it was BestEffort.
- A batch job with
memory: 400min its YAML never starts:mmeans milli, so this asks for 0.4 bytes; the author meant400Mi. - Two teams share a node pool; one team's Pods without limits use all idle CPU at night, which is fine, and all memory at month end, which is not.
| Where it is read | CPU request | CPU limit | Memory request | Memory limit |
|---|---|---|---|---|
| kube-scheduler | Fit and score | Ignored | Fit and score | Ignored |
| kubelet / runtime (Linux) | cpu.weight (share) | cpu.max quota | Eviction ranking; memory.min/memory.low only with MemoryQoS | memory.max |
| Kernel | Proportional share under contention | Throttles at quota | Nothing directly | OOM kill |
| ResourceQuota | requests.cpu | limits.cpu | requests.memory | limits.memory |
HPA Utilization | Denominator | Not used | Denominator for memory | Not used |
| Go runtime (1.25+) | Not used | Default GOMAXPROCS | Not used | Not used (set GOMEMLIMIT yourself) |
| Cloud bill (node autoscaling) | Drives node count | No | Drives node count | No |
Fix / how to use it: measure before setting (VPA in Off mode, or p95 of container_cpu_usage_seconds_total and the working set from Prometheus over a week), set requests at the steady-state p90-p95, set the memory limit equal to the memory request for most services, and use millicore and Mi/Gi units. Namespace defaults (LimitRange) keep forgotten containers out of BestEffort. The manifests for this chapter are in Go and Laravel.
CPU: millicores, CFS quota and CPU throttling Must-know
In plain words: CPU is counted in thousandths of a core. A request buys a share when the node is busy; a limit is a budget per 100 ms slice of time, and once it is spent the whole container waits for the next slice.
Common misunderstanding: "My container averages 200m and its limit is 500m, so it is never throttled." Throttling is decided per 100 ms period, not on average. A Go process with eight runnable goroutine threads can burn a 50 ms quota in about 6 ms of wall time and then stand still for 94 ms, while dashboards that average over a minute show 40 % of the limit.
Definition: "1 CPU unit is equivalent to 1 physical CPU core, or 1 virtual core"; "0.1 is equivalent to the expression 100m, which can be read as 'one hundred millicpu'. Some people say 'one hundred millicores'", and precision finer than 1m is not allowed. "CPU resource is always specified as an absolute amount of resource, never as a relative amount." The CPU limit is enforced by the kernel's CFS bandwidth control: "Within each given 'period' (microseconds), a task group is allocated up to 'quota' microseconds of CPU time ... Once all quota has been assigned any additional requests for quota will result in those threads being throttled. Throttled threads will not be able to run again until the next period when the quota is replenished." On cgroup v2 this is cpu.max ("$MAX $PERIOD ... 'max' for $MAX indicates no limit", default "max 100000"); a 500m limit is conventionally written as 50000 100000. The CPU request "typically defines a weighting": on cgroup v2, cpu.weight (default 100, range 1-10000). Throttling is visible in cpu.stat: nr_periods, nr_throttled, throttled_usec, which "only account for throttling caused by this cgroup's own bandwidth limit". Kubernetes itself says: "a cpu limit is a hard limit the kernel enforces" and "container runtimes don't terminate Pods or containers for excessive CPU usage".
limits.cpu 500m (cpu.max "50000 100000"), GOMAXPROCS 8 (node has 8 CPUs, Go 1.24 defaults)
t=0 ms burst of requests: 8 OS threads run Go code in parallel
t=6.25 ms 8 x 6.25 ms = 50 ms quota spent -> all threads throttled
t=100 ms period boundary: quota refilled; queued requests run; spent again by t=106 ms
... p99 latency +94 ms; cpu.stat nr_throttled grows every period of the burst
fix A GOMAXPROCS = 2 (Go 1.25+ default here: 0.5 rounded up to 1, but never below 2) -> 2 threads x 25 ms,
stalls of 75 ms instead of 94 ms
fix B remove the CPU limit, keep the 500m request -> no quota, share by cpu.weightReal scenarios:
- A Go service on 32-core nodes with
limits.cpu: 1and Go 1.24 runs 32 threads; under load its p99 latency jumps although CPU graphs look flat. Uber'sautomaxprocsREADME measured this on a load balancer with a 2-core quota: "Default (24)" GOMAXPROCS gave 22,191 RPS and 76.19 ms p99.9 against 44,715 RPS and 26.38 ms with GOMAXPROCS equal to the quota. - A PHP-FPM Pod with a 200m CPU limit serves a heavy Blade page that needs 400 ms of CPU: each request takes at least two seconds of wall time.
- A JVM or Node.js process at start-up (JIT, class loading) needs several cores for a few seconds; with a tight CPU limit the startup probe times out and the container restarts in a loop.
- A noisy batch job without a limit but with a small request shares CPU in proportion to requests under contention, so the latency-critical API with the bigger request still gets its share.
| Tool or setting | What it does with CPU | Notes |
|---|---|---|
| Kubernetes CPU request | Scheduling + cpu.weight | Guaranteed share under contention only |
| Kubernetes CPU limit | cpu.max quota per 100 ms period | Throttles; never kills |
cpu.max.burst (kernel) | Lets a group bank unused quota | Not exposed as a Pod field |
kubelet CPU manager static policy | Exclusive cores for Guaranteed Pods with integer CPU | Node-level setting (cpuManagerPolicy) |
Docker --cpus, --cpu-shares | Same cgroup mechanisms on one host | See Running Containers |
| Go 1.25+ runtime | Default GOMAXPROCS = min(CPUs, affinity, cpu.max rounded up), never below 2 on a multi-CPU node, updated periodically | Ignores requests; opt-out with GOMAXPROCS env |
go.uber.org/automaxprocs | Sets GOMAXPROCS from the quota at start (pre-1.25 Go) | Not needed on Go 1.25+ with a recent go line |
| PHP-FPM | One process per request; no thread pool | Concurrency = pm.max_children, not CPU |
Fix / how to use it: read cpu.stat before blaming the code (Lab step 4); for latency-sensitive services either drop the CPU limit and keep an honest request, or keep the limit and make the runtime match it (Go 1.25+ does that automatically when the module's go line is 1.25 or later, or with godebug containermaxprocs=1; see The Go angle). The kernel side of cpu.max and PSI is in Containers Under the Hood.
Memory: memory limit, OOMKilled and exit code 137 Must-know
In plain words: Memory cannot be slowed down the way CPU can. When a container needs more than its memory limit and the kernel cannot reclaim page cache, a process in it is killed; Kubernetes shows OOMKilled and restarts it.
Common misunderstanding: "The memory limit is checked when the container allocates, so allocations just fail." On Linux the allocation usually succeeds and the OOM killer acts later: "memory limits are enforced reactively. A container may use more memory than its memory limit, but if it does, it may get killed." Nor is it the kubelet that kills: it is the kernel, inside the container's cgroup, so the kubelet only reports what happened.
Definition: Memory is counted in bytes with suffixes k, M, G, T, P, E (powers of ten) or Ki, Mi, Gi, Ti, Pi, Ei (powers of two); "If you request 400m of memory, this is a request for 0.4 bytes." The memory limit becomes cgroup v2 memory.max: "If a cgroup's memory usage reaches this limit and can't be reduced, the OOM killer is invoked in the cgroup." Kubernetes: "If that process is the container's PID 1, and the container is marked as restartable, Kubernetes restarts the container." kubectl describe pod then shows Last State: Terminated, Reason: OOMKilled, Exit Code: 137 (128 + signal 9, SIGKILL) and a growing Restart Count; repeated kills lead to CrashLoopBackOff. Memory used by tmpfs emptyDir volumes counts as container memory. The memory request is "mainly used during (Kubernetes) Pod scheduling"; it matters again for eviction ranking and oom_score_adj (see Node-pressure eviction). With the MemoryQoS feature (beta in v1.37) the kubelet can also set memory.high (throttling before the hard limit) and memory.min/memory.low from requests, but "the default kubelet configuration does not enable memory throttling or memory protection".
shop-web php-fpm container, limits.memory 1Gi, pm.max_children 12, ~100 MiB per busy worker
1 traffic spike: 12 workers busy -> 12 x 100 MiB + 160 MiB master/OPcache = 1360 MiB (1.33 GiB) > 1 GiB
2 kernel: memory.max reached, reclaim fails -> OOM killer picks a php-fpm process in the cgroup
3 if it kills a child: master respawns it, the request gets a 502 from Nginx
4 if it kills the master (PID 1): container exits, Reason OOMKilled, Exit Code 137
5 kubelet restarts the container (restartPolicy Always); Restart Count 1, 2, 3 ... CrashLoopBackOff
fix pm.max_children = floor((1024 - 160) / 100) = 8, or raise request = limit to 1.5GiReal scenarios:
- A Go service with
limits.memory: 512Miand noGOMEMLIMITgrows its heap to about twice the live heap before each GC (GOGC 100), crosses 512 MiB during a batch import and is OOMKilled although the live heap is only 300 MiB. - A Laravel queue worker leaks a little memory per job; after six hours it hits its limit and is killed in the middle of a job.
queue:work --memory=and--max-jobsrestart it cleanly before that. - A sidecar log shipper without a memory limit buffers 2 GiB during an Elasticsearch outage; the node runs out and the kubelet evicts Pods that did nothing wrong.
- A Java service sizes its heap from the node's RAM because its JVM is older than container awareness, and is killed at start-up.
| Runtime | How it learns its memory budget | Your knob |
|---|---|---|
| Go 1.19+ | It does not, unless told: GOMEMLIMIT or debug.SetMemoryLimit (soft limit) | 90-95 % of limits.memory |
| PHP-FPM | Per-request memory_limit (php.ini); the pool size multiplies it | pm.max_children x RSS per worker |
| Laravel worker | queue:work --memory=128 (default 128 MB), then exits for a restart | --memory, --max-jobs, --max-time |
| Node.js | --max-old-space-size | Below the limit, leave room for buffers |
| JVM (container-aware versions) | -XX:MaxRAMPercentage of the cgroup limit | 70-75 % |
| Kernel page cache | Counted in the cgroup; reclaimed before an OOM kill | Large file I/O needs headroom |
Fix / how to use it: set the memory limit equal to the request for services (no overcommit, eviction last among Burstable peers), size worker pools from the limit (pm.max_children, Go worker pools), give Go a soft limit below the hard one, and read memory.events (oom_kill) and the container's lastState when it restarts. Triage workflows are in Kubernetes Observability & Troubleshooting.
Ephemeral storage: ephemeral-storage requests and limits Important
In plain words: Disk on the node used by a Pod (its writable layer, its logs, its emptyDir volumes) is a resource too. Request it so the scheduler counts it; limit it so one Pod cannot fill the node's disk.
Common misunderstanding: "Disk does not matter, the node has 100 GB." Image layers, every container's writable layer and every Pod's logs share that disk; when it falls below the eviction threshold (nodefs.available<10% by default), the kubelet evicts Pods, and with DiskPressure the eviction order ignores QoS.
Definition: requests.ephemeral-storage and limits.ephemeral-storage are byte quantities. Kubernetes tracks "the container's writable layer (rootfs)", "local emptyDir volumes", "the Pod's own logs (usually stored under /var/log/pods)" and system files mapped into the Pod. "If a Pod is using more ephemeral storage than you allow it to, the kubelet sets an eviction signal that triggers Pod eviction." emptyDir.sizeLimit caps one volume; memory-backed emptyDir (medium: Memory) counts against the memory limit instead.
orders-export Job: limits.ephemeral-storage 20Gi, emptyDir /tmp/export sizeLimit 20Gi
1 export writes a 25 GiB CSV into /tmp/export
2 kubelet housekeeping (every 10 s) measures emptyDir + writable layer + logs
3 usage > limit -> Pod evicted, phase Failed, reason Evicted, message names ephemeral-storage
4 Job controller creates a new Pod (backoffLimit 3); it fails the same way
fix stream to object storage in parts, or raise the limit with a matching requestReal scenarios: a debug log level left on writes 30 GiB of logs in a day; an image-processing service unpacks archives into /tmp on the writable layer; a node with a small boot disk runs out because ten Pods each keep 2 GiB of temporary files.
| Setting | Effect |
|---|---|
requests.ephemeral-storage | Scheduler fit; ResourceQuota requests.ephemeral-storage |
limits.ephemeral-storage | Pod evicted when exceeded |
emptyDir.sizeLimit | Cap on that volume |
medium: Memory | tmpfs; counted as memory, not ephemeral storage |
Node nodefs.available / imagefs.available | Hard eviction defaults 10 % / 15 % |
Fix: request what the Pod writes in steady state, limit it with headroom, and send logs to stdout at a sane level.
QoS class: Guaranteed, Burstable, BestEffort Must-know
In plain words: Kubernetes sorts every Pod into one of three classes from how its requests and limits are written. The class predicts who suffers first when a node runs short of memory.
Common misunderstanding: "I set qosClass: Guaranteed in my Pod." There is no such field to set; status.qosClass is computed. And "Guaranteed" does not mean faster: it means requests equal limits, so the Pod can never use idle capacity above its limit.
Definition: Guaranteed, with container resources: "Every Container in the Pod must have a memory limit and a memory request", "the memory limit must equal the memory request", and the same for CPU (a limit with no request counts, because the request is copied from it). With Pod-level resources (spec.resources, beta since 1.34) the rule is instead per Pod: "The Pod must have a Pod-level memory limit and memory request, and their values must be equal" and the same for CPU. Burstable: "The Pod does not meet the criteria for QoS class Guaranteed" and "At least one Container in the Pod has a memory or CPU request or limit, or the Pod has a Pod-level memory or CPU request or limit". BestEffort: "none of the Containers in the Pod have a memory limit or a memory request, and none of the Containers in the Pod have a CPU limit or a CPU request, and the Pod does not have any Pod-level memory or CPU limits or requests". The docs' summary: "When a Node runs out of resources, Kubernetes will first evict BestEffort Pods running on that Node, followed by Burstable and finally Guaranteed Pods." Without Pod-level resources, a sidecar without resources is enough to turn a would-be Guaranteed Pod into Burstable; with an equal Pod-level CPU and memory budget, a resource-less sidecar shares that budget and the Pod stays Guaranteed. With in-place resize, "The Pod's original ... QoS class ... cannot be changed by a resize."
Pod with app (cpu 500m/500m, mem 256Mi/256Mi) + log sidecar (no resources), no Pod-level resources
1 app container alone would be Guaranteed
2 sidecar has no limits -> rule "every container" fails -> Pod is Burstable
3 node memory pressure: the kubelet compares the Pod's usage with the Pod's requests; the sidecar's usage
counts against a request of 0, so the Pod is over its requests sooner and ranks in the first group
4 fix A: give the sidecar requests = limits (e.g. 20m / 64Mi) -> Pod becomes Guaranteed
fix B: set Pod-level spec.resources requests = limits (cpu 520m, memory 320Mi) -> Guaranteed; the sidecar shares itReal scenarios: the Laravel web Pod (Nginx sidecar + php-fpm) silently Burstable because Nginx has no CPU limit; a Guaranteed database Pod (needed for the static CPU manager policy and exclusive cores); a namespace where a LimitRange turns would-be BestEffort Pods into Burstable ones by injecting defaults.
| QoS class | Typical workload | Upside | Downside |
|---|---|---|---|
| Guaranteed | Databases, latency-critical APIs, anything with exclusive cores | Evicted last, oom_score_adj -997, static CPU manager eligible | No bursting above limits; CPU limit throttles |
| Burstable (memory request = limit, CPU request only) | Most stateless services | No CPU throttling, uses idle CPU, memory predictable | Not eligible for exclusive cores |
| Burstable (limits above requests) | Spiky workers, dev namespaces | Cheap overcommit | Evicted early when over requests; OOM risk for the node |
| BestEffort | Throwaway batch, experiments | Free capacity | Evicted first; scheduler gives it no reservation |
Fix: check kubectl get pod -o jsonpath='{.status.qosClass}' (expected, not run) or the qos package in Go, which reproduces the rules and is tested on the examples above; ban BestEffort in production namespaces with a scoped ResourceQuota (quotas).
Eviction and node pressure Important
In plain words: When the node itself runs low on memory, disk or process IDs, the kubelet starts removing whole Pods to save the node, starting with those that use more than they asked for.
Common misunderstanding: "The kubelet evicts by QoS class." The docs say the opposite: "The kubelet does not use the pod's QoS class to determine the eviction order. You can use the QoS class to estimate the most likely pod eviction order when reclaiming resources like memory." The ranking is by usage versus requests and priority.
Definition: The kubelet compares eviction signals (memory.available, nodefs.available, nodefs.inodesFree, imagefs.available, imagefs.inodesFree, containerfs.available, pid.available) with thresholds. Defaults on Linux: "memory.available<100Mi", "nodefs.available<10%", "imagefs.available<15%", "nodefs.inodesFree<5%", "imagefs.inodesFree<5%". Hard thresholds use "a 0s grace period (immediate shutdown)"; soft thresholds wait evictionSoftGracePeriod and cap the Pod's grace with evictionMaxPodGracePeriod. Signals map to node conditions MemoryPressure, DiskPressure, PIDPressure, and the control plane maps conditions to taints such as node.kubernetes.io/memory-pressure. After reclaiming node-level resources (dead containers, unused images), the kubelet ranks Pods by: "1. Whether the pod's resource usage exceeds requests 2. Pod Priority 3. The pod's resource usage relative to requests", which yields "BestEffort or Burstable pods where the usage exceeds requests" first and "Guaranteed pods and Burstable pods where the usage is less than requests" last. Evicted Pods end in phase Failed with reason Evicted. If the node runs out before the kubelet acts, the kernel OOM killer picks by oom_score plus oom_score_adj: Guaranteed -997, BestEffort 1000, Burstable min(max(2, 1000 - (1000 × memoryRequestBytes) / machineMemoryCapacityBytes), 999); "Unlike pod eviction, if a container is OOM killed, the kubelet can restart it". evictionPressureTransitionPeriod (default 5m) stops conditions from flapping; evictionMinimumReclaim makes each round free a minimum amount.
node 16 GiB, memory.available falls to 90Mi (< 100Mi hard threshold)
1 kubelet: MemoryPressure=True; control plane taints node.kubernetes.io/memory-pressure:NoSchedule
2 reclaim: nothing to free for memory
3 rank: report-job BestEffort usage 3 GiB > request 0 priority 1000 -> evict first
shop-web-x Burstable usage 900Mi > request 512Mi priority 10000 -> next
orders-api-y Burstable usage 200Mi < request 256Mi priority 100000 -> last group
4 evict report-job (grace 0 s for a hard threshold); memory.available 3.1 GiB -> stop
5 new BestEffort Pods are not scheduled here while the taint is presentReal scenarios: a node with many BestEffort CI runners loses them every afternoon; a Burstable PHP Pod over its request is evicted while a Guaranteed one survives; a DaemonSet log agent with no memory limit drives the node into pressure and the application Pods are evicted; a disk-pressure eviction removes a Guaranteed Pod because QoS does not apply to disk.
| Mechanism | Who acts | Unit of action | Restart? |
|---|---|---|---|
| Container memory limit | Kernel, in the container cgroup | One process | Container restarted in place |
| Node-pressure eviction | kubelet | Whole Pod | Controller creates a new Pod (maybe elsewhere) |
| Node OOM | Kernel, node-wide | Process with highest score | Container restarted |
API-initiated eviction (kubectl drain, autoscalers) | API server Eviction subresource | Whole Pod, PDB-checked | Controller creates a new Pod |
| Preemption | Scheduler | Lower-priority Pods | Controller creates a new Pod |
Taint NoExecute | taint-eviction-controller | Pods without a toleration | Controller creates a new Pod |
Fix: set kubeReserved/systemReserved so daemons do not eat Pod memory, keep production Pods at or under their requests (memory request = limit), give DaemonSets limits, and size soft thresholds above the hard ones (cluster/kubelet-config.yaml in Go).
The limits debate: CPU limits off? Memory limit = request? Important
In plain words: Many teams set no CPU limit (only a request) and set the memory limit equal to the memory request. The reason is that CPU can be shared safely without limits, while memory cannot.
Common misunderstanding: "Without CPU limits one Pod will starve all others." Under contention the kernel shares CPU in proportion to the requests' weights, so every container still gets at least its requested share; a limit only stops a container from using CPU that is otherwise idle.
Definition: Google Cloud's GKE cost-optimisation guide states the rule as: "Memory: Set the same amount of memory for the request and limit." and "CPU: For the request, specify the minimum CPU needed to ensure correct operation, according to your own SLOs. Set an unbounded CPU limit." Its reasoning: "When the CPU is contended, these Pods can be throttled down to its requests. However, because memory is an incompressible resource, when memory is exhausted, the Pod needs to be taken down." The counter-arguments are real too: CPU limits make performance tests reproducible (no free burst on an idle staging node), they give the Go 1.25+ runtime a quota to size GOMAXPROCS from, they are required for Guaranteed QoS and exclusive cores, and a ResourceQuota on limits.cpu forces every Pod to have one.
Same Deployment, three policies, on a node where neighbours are idle at night and busy by day
A cpu 500m/500m night: capped at 500m (wasted idle CPU) day: 500m, throttled on bursts
B cpu 500m/none night: bursts to 2+ cores, fast day: >= 500m share, never throttled
C cpu 500m/2000m night: up to 2 cores day: >= 500m, throttled only above 2
memory in all three: 256Mi/256Mi -> OOM only from its own growth, never because of a neighbourReal scenarios: a payments API with p99 SLOs drops CPU limits and its tail latency halves; a multi-tenant cluster keeps CPU limits on tenant namespaces because "fair" must mean "capped" there; a benchmark team insists on limits so results do not depend on neighbours.
| Policy | Pros | Cons | Fits |
|---|---|---|---|
| Memory request = limit | No overcommit, predictable OOM, eviction last among Burstable | Must measure the peak honestly | Almost every service |
| Memory limit > request | Cheaper, packs more | Node-level OOM and eviction risk | Dev, spiky batch |
| CPU request, no limit | No throttling, uses idle CPU | No per-Pod cap; must size GOMAXPROCS from the request | Latency-sensitive services on trusted clusters |
| CPU limit = request | Guaranteed QoS, exclusive cores possible, reproducible | Throttling on bursts | Databases, benchmarks, CPU-pinned workloads |
| CPU limit = 2-4x request | Bursting with a safety cap | Still throttles at the cap | Multi-tenant clusters |
Fix: pick one policy per namespace, write it into the LimitRange (default limit for memory, no default CPU limit), and make the runtime match: GOMAXPROCS from the request when there is no CPU limit (downward API in go-service/deployment.yaml), or from cpu.max when there is one.
LimitRange and ResourceQuota: default requests and namespace totals Must-know
In plain words: A LimitRange sets per-container defaults and bounds inside a namespace; a ResourceQuota caps the total a namespace may request. One fills in forgotten numbers, the other stops one team from booking the whole cluster.
Common misunderstanding: "Adding a LimitRange or quota fixes the Pods that are already running." Both act only at admission: "LimitRange validations occur only at Pod admission stage, not on running Pods", and for quotas "Neither contention nor changes to quota will affect already created resources."
Definition: LimitRange (per namespace, types Container, Pod, PersistentVolumeClaim): "the LimitRange admission controller applies default request and limit values for all Pods (and their containers) that do not set compute resource requirements" (defaultRequest, default), then checks min, max and maxLimitRequestRatio; a violation fails "with an HTTP status code 403 Forbidden". It "does not check the consistency of the default values it applies": a default limit below a request the user wrote produces an invalid Pod. With several LimitRanges in one namespace, "it is not deterministic which default value will be applied". ResourceQuota: hard totals such as requests.cpu ("Across all pods in a non-terminal state, the sum of CPU requests cannot exceed this value"), limits.memory, requests.ephemeral-storage, pods, count/deployments.apps, persistentvolumeclaims, requests.storage, services.loadbalancers; requests over the quota also fail with 403 Forbidden. "If quotas are enabled in a namespace for resource such as cpu and memory, users must specify requests or limits for those values when they define a Pod; otherwise, the quota system may reject pod creation" (a LimitRange default satisfies this). Scopes narrow what a quota counts: BestEffort, NotBestEffort, Terminating, NotTerminating, PriorityClass (via scopeSelector), CrossNamespacePodAffinity, VolumeAttributesClass.
namespace shop: ResourceQuota requests.cpu 40, used 39.6; LimitRange defaultRequest cpu 100m
1 kubectl apply Deployment shop-reports (replicas 2, no resources)
2 LimitRange admission: each container gets requests cpu 100m, memory 128Mi, limit memory 256Mi
3 quota admission: 39.6 + 0.1 = 39.7 <= 40 -> first Pod admitted
4 second Pod: 39.7 + 0.1 = 39.8 -> admitted; a third replica would also fit; a 1-CPU Pod would not
5 the ReplicaSet (not your kubectl) gets the 403; you see it as FailedCreate events on the ReplicaSetReal scenarios: a shared staging cluster where each team namespace has a quota sized to its budget; an HPA that cannot scale past 12 replicas because the quota is full (the ReplicaSet's create calls are rejected and show up as FailedCreate events); a platform team banning BestEffort Pods with a BestEffort-scoped quota of pods: "0"; capping how much of a namespace may use the high priority class.
| Object | Scope | Acts at | Typical fields |
|---|---|---|---|
| LimitRange | Namespace, per container/Pod/PVC | Admission (mutating + validating) | defaultRequest, default, min, max, maxLimitRequestRatio |
| ResourceQuota | Namespace totals | Admission (validating) | requests.cpu, limits.memory, pods, count/<resource>, scopes |
Pod-level resources | One Pod | Scheduling + cgroups | spec.resources.requests/limits (beta) |
| GKE Autopilot | Cluster mode | Admission (mutates requests) | Bills by Pod requests |
| Kyverno / OPA Gatekeeper | Policy engines | Admission | "requests required", "no CPU limit" style rules |
Fix: namespace/limitrange.yaml and namespace/resourcequota.yaml in Go give each namespace defaults, a total, a BestEffort ban and a priority slice; review kubectl describe quota (expected, not run) before raising HPA maximums.
The scheduler: filtering, scoring, the scheduling framework, binpacking vs spreading Must-know
In plain words: For each new Pod, kube-scheduler throws away nodes where it cannot run (filtering), grades the rest (scoring), picks the best and writes the choice to the API. It decides once; after that the Pod stays on that node until it dies or is evicted.
Common misunderstanding: "The scheduler moves Pods when the cluster becomes unbalanced." It never moves running Pods. Placement rules are checked only when a Pod is scheduled ("IgnoredDuringExecution"); rebalancing is the descheduler's job.
Definition: "kube-scheduler selects a node for the pod in a 2-step operation: 1. Filtering 2. Scoring." Filtering finds "feasible" nodes ("the PodFitsResources filter checks whether a candidate Node has enough available resources to meet a Pod's specific resource requests"); scoring ranks them, and "If there is more than one node with equal scores, kube-scheduler selects one of these at random." "The scheduler then notifies the API server about this decision in a process called binding." Historically filters were predicates and scoring functions were priorities; since v1.19 they are plugins of the scheduling framework: "Each attempt to schedule one Pod is split into two phases, the scheduling cycle and the binding cycle", and "Scheduling cycles are run serially, while binding cycles may run concurrently." Extension points: PreEnqueue, QueueSort, PreFilter, Filter, PostFilter (preemption), PreScore, Score, NormalizeScore, Reserve, Permit, PreBind, Bind, PostBind. Default plugins include NodeResourcesFit (with scoring strategies "LeastAllocated (default), MostAllocated and RequestedToCapacityRatio"), NodeResourcesBalancedAllocation, NodeAffinity, TaintToleration, PodTopologySpread, InterPodAffinity, ImageLocality and DefaultPreemption. Spreading (LeastAllocated, the default) prefers emptier nodes; binpacking (MostAllocated, which "scores the nodes based on the utilization of resources, favoring the ones with higher allocation") fills nodes so that others empty out and can be removed. On large clusters percentageOfNodesToScore limits how many feasible nodes are scored (adaptive default: "50% for a 100-node cluster", "10% for a 5000-node cluster", never below 5 %).
Pod orders-api (cpu 500m, zone spread DoNotSchedule, on-demand only, priority 100000); 6 nodes
1 queue: QueueSort puts it ahead of shop-batch Pods (higher priority)
2 Filter: node-1 (spot) fails NodeAffinity; node-2 tainted workload=batch fails TaintToleration
node-3 has 300m free -> NodeResourcesFit fails; node-4,5,6 feasible
3 PodTopologySpread: zones a=2, b=1, c=1 replicas; node-4 is in zone a -> skew would be 2 > 1: filtered
4 Score node-5 (zone b) and node-6 (zone c): LeastAllocated, anti-affinity weight, ImageLocality
5 node-6 wins (more free CPU, image already pulled); Reserve, Permit
6 binding cycle: Bind writes spec.nodeName=node-6; kubelet on node-6 starts the containersReal scenarios: a GPU Pod waits although GPUs are free because its node affinity names a label no GPU node has; a cluster tuned for cost uses a MostAllocated profile so the autoscaler can drain whole nodes; a 5,000-node cluster scores a sample of nodes to keep scheduling latency low; a Pod with a big image lands on nodes that already cached it (ImageLocality).
| Scheduler | Model | Where |
|---|---|---|
| kube-scheduler (default profile) | Framework plugins, LeastAllocated spreading | Every Kubernetes cluster |
| kube-scheduler (custom profile) | Same binary, other plugin args (MostAllocated), chosen per Pod with schedulerName | KubeSchedulerConfiguration |
| Scheduler plugins / secondary schedulers | Gang/co-scheduling, network-aware, batch queues | kubernetes-sigs/scheduler-plugins, Volcano, Kueue for queueing |
| Karpenter (provisioning) | Simulates scheduling to choose instance types; does not bind Pods | Node autoscaling |
| Docker Swarm / Nomad | Spread or binpack strategies per job | Other orchestrators |
Fix: keep the default profile unless you have a measured reason; add a second binpacking profile for batch (cluster/scheduler-binpacking.yaml); explain a placement with kubectl describe pod events and the Pending Pods checklist. Writing your own plugin or scheduler in Go is Extending Kubernetes.
nodeSelector and node affinity: requiredDuringScheduling, preferredDuringScheduling Must-know
In plain words: Node labels describe machines (architecture, zone, instance type, spot or on-demand). nodeSelector says "only these"; node affinity says the same with operators, alternatives and soft preferences.
Common misunderstanding: "If I relabel the node, the Pod moves away." IgnoredDuringExecution means exactly that: "if the node labels change after Kubernetes schedules the Pod, the Pod continues to run".
Definition: "nodeSelector is the simplest recommended form of node selection constraint"; it "only selects nodes with all the specified labels". Node affinity has two types: "requiredDuringSchedulingIgnoredDuringExecution: The scheduler can't schedule the Pod unless the rule is met" and "preferredDuringSchedulingIgnoredDuringExecution: The scheduler tries to find a node that meets the rule. If a matching node is not available, the scheduler still schedules the Pod." Operators: In, NotIn, Exists, DoesNotExist, Gt, Lt ("NotIn and DoesNotExist allow you to define node anti-affinity behavior"). Multiple nodeSelectorTerms are ORed, multiple matchExpressions inside a term are ANDed, and with both nodeSelector and nodeAffinity "both must be satisfied". Preferred terms carry "a weight between 1 and 100" that is added to the node's score. Well-known labels: kubernetes.io/arch, kubernetes.io/os, kubernetes.io/hostname, topology.kubernetes.io/zone, topology.kubernetes.io/region, node.kubernetes.io/instance-type, and provider labels such as Karpenter's karpenter.sh/capacity-type. For labels you rely on for isolation, the docs recommend the node-restriction.kubernetes.io/ prefix so a kubelet cannot set them on itself.
orders-api: required arch In [amd64, arm64] AND capacity-type In [on-demand]; preferred arm64 (weight 50)
1 spot nodes filtered out (required term fails)
2 remaining: 2 x amd64 on-demand, 1 x arm64 on-demand -> all feasible
3 arm64 node gets +50 in scoring; wins unless other scores outweigh it
4 later someone labels the arm64 node capacity-type=spot -> the Pod keeps running there (IgnoredDuringExecution)Real scenarios: multi-arch images rolled onto Graviton/Ampere nodes with a soft preference first; Pods pinned to one zone because their EBS volume lives there (the volume's own node affinity does this automatically); a licence-bound workload kept on specific instance types; Windows Pods kept off Linux nodes with kubernetes.io/os.
| Need | Tool |
|---|---|
| One fixed label | nodeSelector |
| "Any of these values", "not these", "exists" | requiredDuringSchedulingIgnoredDuringExecution |
| Prefer but do not require | preferredDuringSchedulingIgnoredDuringExecution with weight |
| Keep everyone else off the nodes | Taints (node affinity only attracts) |
| Exact node, bypass scheduler | nodeName (rarely right) |
Fix: prefer well-known labels, combine an attracting affinity with a repelling taint for dedicated pools (scheduling/batch-job.yaml), and remember that Karpenter and Cluster Autoscaler read the same affinities to decide what to launch.
Pod affinity and pod anti-affinity Important
In plain words: Instead of node labels, these rules look at the labels of Pods already running: "put me in the same zone as the cache" (affinity) or "never two of us on the same node" (anti-affinity).
Common misunderstanding: "Required anti-affinity per hostname is the standard way to spread replicas." It works, but it caps replicas at the number of nodes (the 11th replica of a 10-node cluster is Pending forever) and it is expensive: "Inter-pod affinity and anti-affinity require substantial amounts of processing which can slow down scheduling in large clusters significantly", and the docs "do not recommend using them in clusters larger than several hundred nodes". Topology spread is the scalable tool for even distribution.
Definition: Rules take the form "this Pod should (or, in the case of anti-affinity, should not) run in an X if that X is already running one or more Pods that meet rule Y", where X is a topology domain named by topologyKey (kubernetes.io/hostname, topology.kubernetes.io/zone) and Y is a label selector (plus optional namespaces/namespaceSelector, and matchLabelKeys/mismatchLabelKeys). Both have requiredDuringScheduling... and preferredDuringScheduling... forms, with weight on preferred terms. "Pod anti-affinity requires nodes to be consistently labeled": every node needs the topologyKey label.
redis-cache with podAffinity required to app=orders-api, topologyKey zone
1 orders-api replicas exist in zones a and b
2 first redis-cache Pod: feasible nodes are those in zones a or b only
3 orders-api scales to zero in zone b -> nothing moves (IgnoredDuringExecution)
4 next redis-cache Pod can only go to zone a; if zone a is full -> PendingReal scenarios: two replicas of a primary/replica database pair forced onto different nodes; a sidecar-like service placed in the same zone as its main service to save cross-zone traffic; a noisy batch workload kept off nodes running latency-critical APIs with preferred anti-affinity.
| Goal | Better tool |
|---|---|
| Even spread of replicas across zones/nodes | topologySpreadConstraints |
| "Never on the same node" for 2-3 replicas | Required pod anti-affinity |
| "Same zone as X" | Preferred pod affinity (required only when necessary) |
| "Keep workload class A off nodes of class B" | Taints and tolerations, or node affinity on pool labels |
Fix: use preferred anti-affinity per hostname plus a zone spread constraint (go-service/deployment.yaml), and reserve required inter-pod rules for small, critical sets.
Topology spread constraints: topologySpreadConstraints and maxSkew Must-know
In plain words: "Keep the number of my replicas roughly equal across zones (or nodes)": you say how unequal it may get (maxSkew) and whether to refuse or merely prefer.
Common misunderstanding: "Spread constraints keep Pods balanced." They are checked when a Pod is scheduled, not afterwards: "There's no guarantee that the constraints remain satisfied when Pods are removed. For example, scaling down a Deployment may result in imbalanced Pods distribution." And the scheduler only knows zones that currently have nodes, which matters when an autoscaled node group is at zero.
Definition: Fields: maxSkew (the maximum permitted difference between the number of matching Pods in a domain and the global minimum), topologyKey, whenUnsatisfiable ("DoNotSchedule (default) tells the scheduler not to schedule it"; "ScheduleAnyway tells the scheduler to still schedule it while prioritizing nodes that minimize the skew"), labelSelector, minDomains (only with DoNotSchedule; "If you do not specify minDomains, the constraint behaves as if minDomains is 1"), matchLabelKeys (for example pod-template-hash so each rollout revision is spread on its own; beta and on by default since 1.27), nodeAffinityPolicy and nodeTaintsPolicy (Honor/Ignore: whether nodes excluded by the Pod's affinity or by taints count as domains). "There can only be one topologySpreadConstraint for a given topologyKey and whenUnsatisfiable value." Cluster administrators can set default constraints for Pods without their own in the PodTopologySpread plugin configuration.
maxSkew 1, zone, DoNotSchedule, minDomains 3; zones a, b, c; current matching Pods a=2 b=2 c=1
1 new replica: candidates a -> skew 3-1=2 > 1 (rejected), b -> 2 (rejected), c -> a=2,b=2,c=2 skew 0 (ok)
2 zone c full -> no feasible node -> Pending; with ScheduleAnyway it would go to a or b with a lower score
3 zone c lost entirely: domains = 2 < minDomains 3 -> global minimum treated as 0 -> at most 1 Pod per remaining zone above it
4 scale down from 6 to 3: the ReplicaSet may delete a, a, b -> a=0 b=1 c=2 (imbalanced; descheduler can fix)Real scenarios: an API with three replicas across three zones survives a zone outage with two; a Kafka consumer group spread across nodes so one node failure triggers a small rebalance; a rollout where matchLabelKeys: [pod-template-hash] stops the new ReplicaSet from piling into one zone because the old Pods already balance the count; Karpenter launching nodes in the zone the constraint asks for (it also accepts karpenter.sh/capacity-type as a topology key).
| Constraint | Effect |
|---|---|
zone, maxSkew: 1, DoNotSchedule | Hard zone balance; Pending if a zone is full |
hostname, maxSkew: 1, ScheduleAnyway | Soft node balance, never blocks |
minDomains: 3 | Expect at least three zones; prevents packing into two when one is missing |
matchLabelKeys: [pod-template-hash] | Spread per revision during rollouts |
nodeTaintsPolicy: Honor | Tainted nodes the Pod cannot use are not counted as domains |
Fix: one hard zone constraint plus one soft hostname constraint covers most services (go-service/deployment.yaml); set minReplicas of the HPA to at least the number of zones; run the descheduler's RemovePodsViolatingTopologySpreadConstraint if scale-downs leave the spread lopsided.
Taints and tolerations: NoSchedule, PreferNoSchedule, NoExecute, tolerationSeconds Must-know
In plain words: A taint on a node says "keep out"; a toleration on a Pod says "I may enter". Taints repel; they never attract, so a dedicated pool needs a taint and an affinity.
Common misunderstanding: "Adding a toleration makes my Pod run on the tainted nodes." A toleration only removes an obstacle; the Pod may still land anywhere else. Conversely, adding a NoSchedule taint does not remove Pods already running: "Pods currently running on the node are not evicted." Only NoExecute evicts.
Definition: A taint is key=value:effect on a node (kubectl taint nodes node1 key1=value1:NoSchedule). Effects: NoSchedule ("No new Pods will be scheduled on the tainted node unless they have a matching toleration"), PreferNoSchedule ("a 'preference' or 'soft' version of NoSchedule") and NoExecute ("Pods that do not tolerate the taint are evicted immediately"; Pods that tolerate it with tolerationSeconds "remain bound for the specified amount of time"). A toleration matches by key, operator (Equal or Exists; Gt/Lt numeric comparisons are alpha since 1.35), value and effect. Built-in node.kubernetes.io taints: node.kubernetes.io/not-ready, unreachable, memory-pressure, disk-pressure, pid-pressure, network-unavailable, unschedulable; the control plane "automatically creates taints with a NoSchedule effect for node conditions", and "Kubernetes automatically adds a toleration for node.kubernetes.io/not-ready and node.kubernetes.io/unreachable with tolerationSeconds=300", so Pods stay on a failed node for five minutes before eviction. DaemonSet Pods get NoExecute tolerations for those two with no tolerationSeconds, and NoSchedule tolerations for the pressure taints. Since 1.29 taint-based eviction runs in a separate taint-eviction-controller.
node-7 stops reporting (network partition), Pod orders-api-x runs there
t=0 node controller: Ready=Unknown; taint node.kubernetes.io/unreachable:NoExecute
t=0 Pods with the default toleration (tolerationSeconds 300) stay bound
t=300 s taint-eviction-controller deletes orders-api-x; ReplicaSet creates a replacement elsewhere
(a Pod with tolerationSeconds 6000, e.g. a stateful cache, waits 100 min for the partition to heal)Real scenarios: GPU nodes tainted nvidia.com/gpu=present:NoSchedule so only GPU Pods use them; a spot pool tainted workload=batch:NoSchedule for interruptible jobs; kubectl drain cordoning a node (node.kubernetes.io/unschedulable); a control-plane node tainted node-role.kubernetes.io/control-plane:NoSchedule; Karpenter startupTaints that a CNI agent removes once the node network is ready.
| Effect | New Pods without toleration | Running Pods without toleration | Typical source |
|---|---|---|---|
NoSchedule | Not scheduled | Stay | Dedicated pools, pressure conditions, cordon |
PreferNoSchedule | Avoided if possible | Stay | Soft isolation |
NoExecute | Not scheduled | Evicted (after tolerationSeconds if tolerated) | not-ready, unreachable, manual isolation |
Fix: taint dedicated pools and add both the toleration and a node affinity to the Pods meant for them (scheduling/batch-job.yaml, cluster/karpenter-nodepools.yaml); shorten tolerationSeconds for unreachable on stateless services that should fail over faster than five minutes, and lengthen it for Pods whose restart is expensive.
PriorityClass and preemption Important
In plain words: A priority says which Pods matter more. When the cluster is full, a high-priority Pod may push lower-priority Pods off a node to take their place.
Common misunderstanding: "PodDisruptionBudgets protect my Pods from preemption." Only partly: "the scheduler tries to find victims whose PDB are not violated by preemption, but if no such victims are found, preemption will still happen" (the docs title it "PodDisruptionBudget is supported, but not guaranteed").
Definition: A PriorityClass (cluster-scoped, scheduling.k8s.io/v1) maps a name to an integer value "from -2147483648 to 1000000000 inclusive. Larger numbers are reserved for built-in PriorityClasses": system-cluster-critical (2000000000) and system-node-critical (2000001000). Pods reference it with priorityClassName. One class may set globalDefault: true; without one, Pods get priority 0. Pending Pods are ordered by priority in the scheduling queue. If no node fits, PostFilter runs preemption: it looks for a node where evicting lower-priority Pods makes room, evicts them (they get their graceful termination period) and sets nominatedNodeName on the preemptor. preemptionPolicy: Never gives a Pod queue priority without the right to evict ("will be placed in the scheduling queue ahead of lower-priority pods, but they cannot preempt other pods"). Node-pressure eviction also uses priority as its second key.
cluster full; shop-batch Pods (priority 1000) fill node-3; orders-api replica (priority 100000) Pending
1 Filter: no node fits -> PostFilter DefaultPreemption
2 candidate node-3: evicting 2 batch Pods frees enough CPU; their PDB allows it
3 scheduler deletes them gracefully (terminationGracePeriodSeconds), sets nominatedNodeName=node-3
4 once resources are free, orders-api binds to node-3 (or anywhere better that appeared meanwhile)
5 the evicted batch Pods are Pending; the node autoscaler adds a node for themReal scenarios: checkout keeps running during a capacity crunch while reports wait; overprovisioning with priority -10 pause Pods that real workloads preempt instantly (Cluster Autoscaler FAQ pattern, scheduling/overprovisioning.yaml); a ResourceQuota scoped to a priority class limits how much "critical" a namespace may claim; a misconfigured globalDefault with a high value makes every Pod critical and preemption meaningless.
| Class | Value | preemptionPolicy | Use |
|---|---|---|---|
system-node-critical | 2000001000 | PreemptLowerPriority | kube-proxy, CNI agents |
system-cluster-critical | 2000000000 | PreemptLowerPriority | CoreDNS, metrics-server |
shop-critical | 100000 | PreemptLowerPriority | Checkout, orders API |
shop-default (globalDefault) | 10000 | PreemptLowerPriority | Everything else |
shop-batch | 1000 | Never | Reports, exports |
overprovisioning | -10 | PreemptLowerPriority | Pause Pods holding headroom |
Fix: few classes, documented values, quota-scoped access to the top one, preemptionPolicy: Never for batch (priority/priorityclasses.yaml).
Pod overhead, Pod-level resources and Dynamic Resource Allocation Good to know
In plain words: Some runtimes (VM-based sandboxes like Kata Containers) cost resources beyond the containers themselves; Pod overhead adds that cost to the Pod's requests automatically. Pod-level resources let you budget a whole Pod instead of each container. DRA is the new way to request devices such as GPUs.
Common misunderstanding: "Overhead is something I add to my container requests by hand." It is set by the RuntimeClass, "at admission time according to the overhead associated with the Pod's RuntimeClass", and you should not copy it into the containers.
Definition: "A pod's overhead is considered in addition to the sum of container resource requests when scheduling a Pod. Similarly, the kubelet will include the Pod overhead when sizing the Pod cgroup" (stable since 1.24). Pod-level resources (spec.resources, beta and on by default since 1.34) set cpu, memory and hugepages for the Pod; containers without their own values share the Pod budget. Dynamic Resource Allocation (stable since 1.34) replaces "count of nvidia.com/gpu" with ResourceClaims and DeviceClasses that describe device attributes; the scheduler allocates matching devices.
RuntimeClass kata-fc: overhead cpu 250m, memory 120Mi; Pod requests 500m / 256Mi
1 admission: Pod.spec.overhead = 250m / 120Mi copied from the RuntimeClass
2 scheduler: fits if node has 750m / 376Mi free
3 ResourceQuota counts the overhead too; the Pod cgroup is sized to include it| Feature | Stage (v1.37) | Field |
|---|---|---|
| Pod overhead | Stable (1.24) | RuntimeClass.overhead.podFixed, Pod.spec.overhead |
| Pod-level resources | Beta (1.34) | Pod.spec.resources |
| DRA | Stable (1.34) | ResourceClaim, DeviceClass, spec.resourceClaims |
| Extended resources (device plugins) | Stable | requests: nvidia.com/gpu: 1 |
Pending pods, FailedScheduling events and the descheduler Important
In plain words: A Pod stays Pending until all its containers have been created, which includes the time before it has a node and the image pulls after. A Pod that no node can take stays unscheduled in that phase, and the scheduler writes a FailedScheduling event that lists, per reason, how many nodes said no. The descheduler is the opposite tool: it evicts running Pods so they can be placed better.
Common misunderstanding: "Pending always means a scheduling problem" (or the reverse, "Pending means the image is still downloading"). The phase covers both: "Pending: The pod has been accepted by the Kubernetes system, but one or more of the container images has not been created. This includes time before being scheduled as well as time spent downloading images over the network". Tell them apart by spec.nodeName and the PodScheduled condition: no node means a scheduling problem and a FailedScheduling event; a node plus containers in state Waiting means image pulls or volume setup (pod-lifecycle: Pending "includes time a Pod spends waiting to be scheduled as well as the time spent downloading container images over the network").
Definition: "If the scheduler cannot find any node where a Pod can fit, the Pod remains unscheduled until a place can be found. An Event is produced each time the scheduler fails to find a place for the Pod", for example Warning FailedScheduling 23s default-scheduler 0/42 nodes available: insufficient cpu. The docs' checklist: add nodes, terminate unneeded Pods, "Check that the Pod is not larger than all the nodes", "Check for node taints". The Pod's PodScheduled condition is False with reason Unschedulable, which is what Cluster Autoscaler and Karpenter watch. The descheduler (kubernetes-sigs/descheduler, run "as a Job, CronJob, or Deployment") evicts Pods by strategy: RemoveDuplicates, LowNodeUtilization, HighNodeUtilization, RemovePodsViolatingInterPodAntiAffinity, RemovePodsViolatingNodeAffinity, RemovePodsViolatingTopologySpreadConstraint, RemovePodsHavingTooManyRestarts, PodLifeTime; it uses the eviction API, so PDBs apply.
kubectl describe pod orders-api-6f9-abcde (expected, not run; illustrative message, the docs sample is "0/42 nodes available: insufficient cpu")
Events:
Warning FailedScheduling default-scheduler 0/9 nodes are available: 3 Insufficient cpu,
3 node(s) had untolerated taint {workload: batch}, 3 node(s) didn't match pod
topology spread constraints. preemption: 0/9 nodes are available: ...
read it as: 3 + 3 + 3 = 9; fix the biggest group first (CPU requests or capacity)| Message fragment | Cause | Fix |
|---|---|---|
Insufficient cpu / Insufficient memory | Requests do not fit allocatable | Smaller requests, bigger or more nodes, node autoscaler limits |
had untolerated taint | Taint without toleration | Add toleration, or target another pool |
didn't match Pod's node affinity/selector | Label missing | Fix labels or the rule |
didn't match pod topology spread constraints | Skew would exceed maxSkew | More zones, ScheduleAnyway, more capacity in the short zone |
didn't match pod anti-affinity rules | Required anti-affinity, not enough nodes | Preferred anti-affinity or spread |
exceed max volume count / volume node affinity conflict | Storage topology | See Config, Secrets & Storage |
pod has unbound immediate PersistentVolumeClaims | PVC not bound | StorageClass, WaitForFirstConsumer |
Fix: read the counts, fix the largest group, and check whether the node autoscaler could have helped (its own events say why it did not, for example NotTriggerScaleUp in Cluster Autoscaler).
HorizontalPodAutoscaler (autoscaling/v2) Must-know
In plain words: The HPA watches a metric, compares it with your target and changes the Deployment's replica count so that the per-replica value comes back to the target. Too busy: more Pods; idle: fewer, but slowly.
Common misunderstanding: "The HPA scales on CPU usage of the node" or "of the limit". It scales on the average per Pod of resource metrics relative to the request (Utilization), or on raw values (AverageValue, Value) of custom metrics and external metrics; and it never adds nodes. If Pods cannot be scheduled, new replicas are Pending until a node autoscaler acts.
Definition: The controller runs every 15 seconds (--horizontal-pod-autoscaler-sync-period) and computes desiredReplicas = ceil(currentReplicas × currentMetricValue / desiredMetricValue); "The control plane skips any scaling action if the ratio is sufficiently close to 1.0 (within a configurable tolerance, 0.1 by default)." Metric types in autoscaling/v2: Resource (CPU or memory per Pod, from metrics.k8s.io, served by metrics-server), ContainerResource (one container of the Pod, stable since 1.30), Pods (a per-Pod custom metric), Object (one metric of another object, e.g. an Ingress) and External (from external.metrics.k8s.io, e.g. a queue length). With several metrics, the largest desiredReplicas wins. Target utilization is "a percentage of the equivalent resource request on the containers in each Pod"; "if some of the Pod's containers do not have the relevant resource request set, CPU utilization for the Pod will not be defined and the autoscaler will not take any action for that metric". Not-ready Pods and Pods without metrics are set aside and counted conservatively (--horizontal-pod-autoscaler-initial-readiness-delay 30 s, --horizontal-pod-autoscaler-cpu-initialization-period 5 min). Behavior: scaleUp and scaleDown each have stabilizationWindowSeconds, policies (Pods or Percent with periodSeconds up to 1800), selectPolicy (Max default, Min, Disabled) and, since 1.37 stable, tolerance. The defaults: scale-down window 300 s with "a 100% of the currently running replicas" per 15 s; scale-up no window and "4 pods or a 100% of the currently running replicas may at most be added every 15 seconds". The window: "the algorithm looks into previously computed desired states, and uses the highest value from the specified interval". minReplicas maxReplicas bound the result; scale to zero: "For HorizontalPodAutoscalers that scale on custom (object) or external metrics, you can set spec.minReplicas to 0" with the HPAScaleToZero gate, beta and "enabled by default" from 1.37; "It is not available for resource metrics". Do not keep spec.replicas in the Deployment manifest you kubectl apply, or every apply resets the count.
orders-api: 4 replicas, request cpu 500m, target averageUtilization 70 (= 350m)
t=0 metrics-server: average usage 630m -> 126 % of request; ratio 126/70 = 1.8
t=0 desired = ceil(4 x 1.8) = 8; scaleUp policies (Percent 100, Pods 4 per 30 s, Max) allow +4 -> 8
t=15s new Pods not ready yet -> treated as 0 % CPU for scale-up maths; no further change
t=60s 8 ready replicas, average 330m -> 94 % of target -> within tolerance -> hold
t=10m traffic falls: average 170m (34 % of request) -> desired ceil(8 x 34/70) = 4
t=10m scaleDown stabilizationWindowSeconds 300: highest recommendation in the last 5 min is 8 -> hold
t=15m window now only contains 4s; policies Min(Percent 20 = 2, Pods 2) -> 8 -> 6 -> 4 over two minutesReal scenarios: an API that scales on CPU but whose bottleneck is the database (more replicas only add connections: see Connection Pooling); a Laravel web tier scaled on busy php-fpm workers, a better signal for I/O-bound PHP than CPU; flapping between 3 and 6 replicas every minute because the scale-down window was set to 0; an HPA that never scales because the Deployment has a sidecar without a CPU request (use ContainerResource).
| Metric source | API | Provider | Example target |
|---|---|---|---|
| CPU / memory | metrics.k8s.io (resource metrics) | metrics-server ("collecting metrics every 15 seconds"; "meant only for autoscaling purposes") | averageUtilization: 70 |
| Per-Pod app metric | custom.metrics.k8s.io | prometheus-adapter, Datadog, Google Cloud Managed Prometheus | http_requests_per_second averageValue: 150 |
| Queue, lag, SaaS metric | external.metrics.k8s.io | KEDA metrics server, cloud adapters | SQS visible messages averageValue: 30 |
| Object metric | custom.metrics.k8s.io | adapter | Ingress requests per second value: 2k |
Fix: go-service/hpa.yaml (CPU + requests per second, fast up, slow down) and laravel/web-hpa.yaml (php-fpm busy workers + ContainerResource CPU) in the code sections; the hpa Go package reproduces the formula, the tolerance, the policies and the window, with tests that use the docs' own numbers.
VerticalPodAutoscaler and in-place pod resize Important
In plain words: The VPA watches what containers really use and recommends, or applies, better requests. In-place resize lets Kubernetes change a running container's CPU and memory without recreating the Pod.
Common misunderstanding: "VPA and HPA together give the best of both." Not on the same signal: "Vertical Pod Autoscaler "should not be used with the Horizontal Pod Autoscaler (HPA) on the same resource metric (CPU or memory) at this moment"". If the HPA scales on CPU and the VPA raises the CPU request, utilisation drops and the HPA removes replicas. Combining VPA with an HPA on custom or external metrics (or VPA on memory, HPA on CPU) is fine.
Definition: VPA is a CRD from kubernetes/autoscaler, not part of core Kubernetes ("VPA must be installed separately"), and needs metrics-server. Three components, Updater Recommender Admission: "The recommender, which analyzes resource usage and provides recommendations", "The updater" which updates Pod requests "either by evicting Pods or modifying them in place", "And the VPA admission controller webhook, which applies resource recommendations to new or recreated Pods". Recommendations in status.recommendation: lowerBound, target, uncappedTarget, upperBound. Modes (updatePolicy.updateMode): Off (recommend only), Initial (only at Pod creation), Recreate ("[default]", evicts to apply), InPlaceOrRecreate (in place, falling back to eviction; feature gate on by default from VPA 1.5.0, removed in 1.7.0), InPlace (never evicts; behind a gate), and Auto, "deprecated since VPA version 1.4.0", an alias for Recreate. resourcePolicy.containerPolicies sets minAllowed, maxAllowed, controlledResources and controlledValues (RequestsAndLimits, the default, scales the limit proportionally; RequestsOnly). In-place pod resize (InPlacePodVerticalScaling: alpha 1.27, beta 1.33, stable 1.35) changes requests/limits through the Pod's /resize subresource (kubectl patch pod ... --subresource resize); resizePolicy per resource is NotRequired (default) or RestartContainer; status conditions PodResizePending (reasons Infeasible, Deferred) and PodResizeInProgress. Limits: only CPU and memory; the QoS class cannot change; memory decrease is best-effort; Windows Pods and Pods under static CPU/memory manager policies cannot resize in place; environment variables from the downward API do not update ("environment variables will not be updated unless the container restarts").
shop-queue, VPA InPlaceOrRecreate, worker request memory 256Mi, observed p95 working set 410Mi
1 Recommender (periodic): target memory 450Mi, cpu 180m; writes status.recommendation
2 Updater: current request outside [lowerBound, upperBound] -> resize
3 in place: PATCH /resize memory request 450Mi, limit 900Mi (ratio 1:2 kept, RequestsAndLimits)
4 kubelet: node has room -> PodResizeInProgress -> cgroup memory.max raised; no restart (NotRequired)
5 node full -> PodResizePending reason Deferred -> retried; if impossible, Updater evicts (PDB respected)
6 Admission webhook: replacement Pods start with 450MiReal scenarios: a fleet of 200 Deployments where VPA in Off mode produces the first honest numbers for requests (and the bill drops by a third); a Java service that needs 2 CPU for start-up and 300m after, served by VPA's CPU startup boost or by resizing after readiness; a StatefulSet that must never restart, where InPlace mode or manual resizes are acceptable but Recreate is not.
| Mode | Applies at creation | Changes running Pods | Disruption |
|---|---|---|---|
Off | No | No | None (read status.recommendation) |
Initial | Yes | No | None |
Recreate (default; Auto is its deprecated alias) | Yes | Evicts | Restart, PDB-limited |
InPlaceOrRecreate | Yes | In place, else evicts | Usually none |
InPlace | Yes | In place only, retries | None |
Fix: start every service with VPA Off (go-service/vpa.yaml), copy the target into Git after a week; use InPlaceOrRecreate for workers scaled on external metrics (laravel/queue-vpa.yaml). GKE's guide sums up the trade: "If your Pod resources are too small, your application can either be throttled or it can fail due to out-of-memory errors. If your resources are too large, you have waste and, therefore, larger bills."
KEDA: ScaledObject, ScaledJob, triggers and scalers Important
In plain words: KEDA scales a workload on events outside Kubernetes (messages in a queue, consumer lag, a Prometheus query, a schedule) and can take it all the way to zero replicas and back.
Common misunderstanding: "KEDA replaces the HPA." It drives one: "keda-operator watches KEDA resources like your ScaledObjects and manages the full HPA lifecycle", serving the metrics through external.metrics.k8s.io; KEDA itself handles only the 0 ↔ 1 step ("Zero-to-one and one-to-zero scaling is handled directly by the keda-operator"). Never add a second HPA for a target that has a ScaledObject.
Definition: A ScaledObject targets a Deployment, StatefulSet or any /scale resource. Fields and defaults: pollingInterval ("Default: 30 seconds"), cooldownPeriod ("The period to wait after the last trigger reported active before scaling the resource back to 0, in seconds. By default, it’s 300 (5 minutes)"), initialCooldownPeriod, minReplicaCount (default 0), maxReplicaCount (default 100), idleReplicaCount, fallback (failureThreshold, replicas), advanced.horizontalPodAutoscalerConfig.behavior (passed to the HPA) and triggers. Each trigger has a scaling value (target per replica, used by the HPA for 1 ↔ N) and an activation value (0 ↔ 1): "Activation only occurs when this value is greater than the set value", and "If the minimum replicas is >= 1, the scaler is always active and the activation value will be ignored." A ScaledJob creates Kubernetes Jobs instead of scaling a Deployment (jobTargetRef, maxReplicaCount, history limits), good for long tasks that must not be killed by a scale-down. Credentials come from a TriggerAuthentication. Scalers used on this page: Kafka lag scaler (type: kafka, lagThreshold, activationLagThreshold; "if maxReplicaCount is set more than number of partitions, the scaler won’t scale up to target maxReplicaCount" unless allowIdleConsumers), RabbitMQ scaler (type: rabbitmq, mode: QueueLength or MessageRate, value, queueName), Redis lists (type: redis, listName, listLength), Prometheus scaler (type: prometheus, serverAddress, query, threshold, activationThreshold) and the cron scaler (type: cron, timezone, start, end, desiredReplicas; "Start and end should not be the same").
shop-queue ScaledObject: redis listLength 20, minReplicaCount 1, pollingInterval 10
t=0 list shop-database-queues:default has 0 jobs -> 1 replica (the floor)
t=0+ checkout dispatches 130 jobs (LLEN 130)
t=10s HPA (created by KEDA) sees external metric 130 / target 20 -> desired ceil(1 x 6.5) = 7
t=2m list drained to 0; HPA scales down after its stabilization window (180 s here) -> back to 1
why 1 with minReplicaCount 0 and an empty list: a job dispatched with later() or released with backoff
sits in the :delayed sorted set; it is moved onto the list only by a worker's pop() (RedisQueue::migrate).
Zero workers -> nobody migrates it -> LLEN stays 0 -> KEDA never activates -> the job is stranded.
note :delayed and :reserved are not in LLEN either way: a worker busy with a 10-minute job is not "load",
so terminationGracePeriodSeconds must cover the jobReal scenarios: Laravel queue workers that idle at one replica at night and burst to 20 after a newsletter (zero only for queues that never use delays, backoff or retry_after recovery); a Go Kafka consumer scaled on lag but capped at the partition count; a nightly report fleet held at 10 replicas from 06:00 to 20:00 by a cron trigger and at zero otherwise; video transcoding as a ScaledJob so a scale-down never kills a half-done transcode.
| Need | KEDA | Native HPA (v1.37) |
|---|---|---|
| Scale on CPU / memory | cpu/memory triggers (no zero) | Yes |
| Scale on queue length / lag | Built-in scalers, no adapter | Needs an external metrics adapter |
| Scale to zero | Yes, with any event trigger (not with only cpu/memory triggers) | Beta: minReplicas: 0 with Object/External metrics |
| One Job per batch of events | ScaledJob | No |
| Schedules | Cron scaler | No (CronJob that patches replicas) |
| Fallback when the source is down | fallback.replicas | Keeps last state |
Fix: laravel/queue-scaledobject.yaml (Redis list + cron), go-service/projector-scaledobject.yaml (Kafka lag) and go-service/thumbnails-scaledjob.yaml (RabbitMQ, ScaledJob) in the code sections.
Cluster Autoscaler vs Karpenter: NodePool, consolidation, spot nodes Must-know
In plain words: Pod autoscalers create Pods; node autoscalers create machines when Pods do not fit and remove machines that are not needed. Cluster Autoscaler resizes predefined node groups; Karpenter picks an instance type per batch of Pending Pods.
Common misunderstanding: "The cluster autoscaler adds nodes when CPU is high." Neither tool looks at CPU usage. Cluster Autoscaler: "The main purpose of Cluster Autoscaler is to get pending pods a place to run", and its FAQ answers "No" to using CPU-based node group autoscalers alongside it. Karpenter likewise works from Pods "that the Kubernetes scheduler has marked unschedulable" and their requests.
Definition: Cluster Autoscaler (kubernetes/autoscaler) "checks for any unschedulable pods every 10 seconds (configurable by --scan-interval flag)", simulates whether a template node of each node group would fit them, and chooses a group with an expander (random, most-pods, least-waste (the default), price, priority, grpc). Scale-down: a node is a candidate when the sum of its Pods' requests is below 50 % of allocatable (--scale-down-utilization-threshold) and all its Pods can move elsewhere; "If a node is unneeded for more than 10 minutes, it will be terminated" (--scale-down-unneeded-time), one non-empty node at a time, empty nodes in bulk. Pods with restrictive PDBs, local storage, kube-system Pods without a PDB, or cluster-autoscaler.kubernetes.io/safe-to-evict: "false" block removal. Karpenter (karpenter.sh/v1) uses NodePools (constraints: requirements on instance category, family, size, architecture, zone, karpenter.sh/capacity-type with spot, on-demand, reserved; taints, startupTaints, expireAfter, terminationGracePeriod, limits, weight) and a provider NodeClass (EC2NodeClass on AWS). It launches a NodeClaim for an instance type that fits the Pending Pods, and consolidation (consolidationPolicy: WhenEmpty, WhenEmptyOrUnderutilized or Balanced; consolidateAfter) deletes or replaces nodes: "Empty Node Consolidation", "Multi Node Consolidation", "Single Node Consolidation". Disruption budgets ("Karpenter will respect the minimum of the currently active budgets") limit how many nodes it may disrupt, with optional cron schedule + duration; "Scale operations bypass node disruption budgets but respect PodDisruptionBudgets". With spot nodes, "If a NodePool is compatible with multiple capacity types, Karpenter will prioritize reserved capacity, followed by spot, then finally on-demand", and with interruption handling enabled it drains a node on the 2-minute spot interruption notice. karpenter.sh/do-not-disrupt: "true" on a Pod blocks voluntary disruption of its node.
12 Pending Pods (shop-queue, 200m / 256Mi each) after a KEDA scale-up
Cluster Autoscaler Karpenter
t=0 Pods Unschedulable t=0 Pods Unschedulable
t=10s scan: node group m6i.large would fit 6 t=1s batch window collects all 12
least-waste -> +2 nodes in group "general" solve: one c7g.xlarge (spot) fits all 12
t=2m nodes Ready, Pods bound t=1m NodeClaim launched, node Ready, Pods bound
... load gone, 10 min unneeded, < 50 % requests ... consolidateAfter 5m, WhenEmptyOrUnderutilized
t=+15m drain one node (eviction API, PDBs), delete t=+6m replace or delete node (budgets, PDBs)Real scenarios: a cluster on Cluster Autoscaler with five node groups (general, memory, GPU, spot, arm64) and a priority expander that tries spot first; the same cluster on Karpenter with two NodePools that cover hundreds of instance types; a deploy window where disruption budgets set nodes: "0" so consolidation does not reshuffle Pods during a release; an expireAfter: 720h policy that recycles every node monthly for patching.
| Cluster Autoscaler | Karpenter | |
|---|---|---|
| Unit | Node groups (ASG, MIG, VMSS) of identical nodes | NodeClaims from NodePools, any fitting instance |
| Trigger | Unschedulable Pods, scan every 10 s | Unschedulable Pods, batched |
| Choosing capacity | Expanders (least-waste default) | Price- and fit-aware selection over many types |
| Scale-down | Unneeded > 10 min, utilisation < 50 % | Consolidation (empty, multi-node, single-node, replace) |
| Rate limits | --max-empty-bulk-delete, one non-empty node at a time | Disruption budgets per NodePool, schedules |
| Spot | Separate node groups | karpenter.sh/capacity-type requirement, interruption handling |
| Providers | Most clouds, Cluster API | AWS (the karpenter.sh docs); other providers exist |
| Managed equivalents | GKE cluster autoscaler, AKS, EKS managed node groups | EKS Auto Mode, AKS node auto-provisioning (general knowledge) |
Fix: cluster/karpenter-nodepools.yaml (general pool with spot and on-demand, a tainted spot batch pool, budgets); for Cluster Autoscaler, keep node groups homogeneous and set PDBs on kube-system workloads so nodes can drain. The cloud side (instance types, IAM for the autoscaler, managed node groups) is Cloud Provider Primitives and is usually provisioned with Terraform.
Cost: right-sizing and why requests drive cost Important
In plain words: You pay for nodes, and you need as many nodes as it takes to hold everyone's requests. So a request is a purchase order: unused requested CPU is paid for and blocks others.
Common misunderstanding: "We only pay for what we use." With node autoscaling, requests drive cost: a node cannot be removed while the requests on it cannot move, and a Pending Pod buys a new node because of its requests, not its usage. Some managed modes bill Pod requests directly: in GKE Autopilot, "Your bill is based on the effective resource request of the Pod".
Definition: Right-sizing means setting requests close to real steady-state usage (p90-p95 over a representative week) and removing idle replicas; together with binpacking and node autoscaling it converts the saving into fewer nodes. Waste = requested − used, summed over Pods, plus node fragmentation (allocatable that no Pending Pod can use). Spot nodes cost less but can be reclaimed at short notice (AWS's EKS best-practices guide: "For Spot interruptions with 2 minute notice, Karpenter quickly starts a new node so pods can be moved before the instance is reclaimed"), so they suit interruptible, replicated or batch workloads.
40 Deployments x 3 replicas, each requests 1 CPU / 2Gi, real p95 220m / 600Mi
before: 120 CPU requested -> 16 x 8-vCPU nodes (after system reserve) -> paid for 128 vCPU, used ~26
VPA Off for 7 days -> new requests 300m / 768Mi
after: 36 CPU requested -> 5-6 nodes; Karpenter consolidates the rest within consolidateAfter
plus: batch moved to a spot NodePool; overnight KEDA scale-to-zero for event consumers without delayed work (Kafka projector)| Lever | Saves | Risk |
|---|---|---|
Right-size requests (VPA Off, then Git) | The biggest share in most clusters | Throttling or OOM if set below real peaks |
| Memory request = limit | Prevents node OOM incidents | Needs honest peak measurement |
| HPA / KEDA min replicas lower, scale to zero | Idle capacity | Cold starts |
| Binpacking profile + consolidation | Fragmentation | More disruption |
| Spot NodePool for batch and stateless | Instance price | Interruptions; needs PDBs and graceful shutdown |
| arm64 nodes for multi-arch images | Price per core (provider-dependent) | Image and dependency support |
| ResourceQuota per team | Runaway growth | Teams blocked at the cap |
Fix: treat requests as code reviewed against measurements; show each team its requested-vs-used ratio; cost tooling (OpenCost, Kubecost, cloud cost explorers) allocates the bill by requests, which is why it moves when you right-size.
PodDisruptionBudget interplay and graceful scale-down Important
In plain words: A PDB says how many replicas may be down at once for voluntary reasons (node drains, consolidation, VPA evictions). Graceful scale-down is the application's half: when a Pod is chosen to go, it finishes its work within the grace period.
Common misunderstanding: "A PDB stops the HPA from scaling down too fast." It does not: the HPA lowers replicas and the ReplicaSet deletes Pods directly, and "deleting deployments or pods bypasses Pod Disruption Budgets". PDBs govern evictions: "API-initiated evictions respect your configured PodDisruptionBudgets and terminationGracePeriodSeconds"; a blocked eviction returns 429 Too Many Requests.
Definition: The PDB object (minAvailable or maxUnavailable, unhealthyPodEvictionPolicy) is defined in Kubernetes Workloads. Its interplay with this chapter: Cluster Autoscaler will not remove a node whose Pods have "restrictive PodDisruptionBudget"; Karpenter evicts "with the Kubernetes Eviction API to respect PDBs" until terminationGracePeriod forces it; the VPA updater evicts within PDBs; preemption respects PDBs only best-effort; node-pressure eviction ignores them. On scale-down the ReplicaSet picks victims: "Pending (and unschedulable) pods are scaled down first", then by controller.kubernetes.io/pod-deletion-cost, then "Pods on nodes with more replicas come before pods on nodes with fewer replicas", then the newest. Graceful scale-down for the app: stop taking new work on SIGTERM, finish or hand back in-flight work, exit before terminationGracePeriodSeconds.
Karpenter consolidates node-4 (2 orders-api, 1 shop-queue); PDBs: orders-api maxUnavailable 1, shop-queue minAvailable 1 (of 3)
1 node-4 tainted karpenter.sh/disrupted:NoSchedule; replacement capacity checked first
2 evict orders-api-a -> allowed (1 unavailable) -> SIGTERM, readiness off, drain, exit
3 evict orders-api-b -> 429 until orders-api-a's replacement is Ready elsewhere -> retry -> allowed
4 evict shop-queue-c -> allowed; worker stops fetching, finishes its job (consumer.Run drain budget), exits 0
5 node empty -> instance terminated| Disruption | Respects PDB? | Respects grace period? |
|---|---|---|
| HPA / KEDA scale-down (ReplicaSet deletes) | No | Yes |
kubectl drain, Cluster Autoscaler, Karpenter consolidation | Yes (eviction API) | Yes (Karpenter caps at NodePool terminationGracePeriod) |
VPA Recreate / InPlaceOrRecreate fallback | Yes | Yes |
| Preemption | Best effort | Yes |
| Node-pressure eviction (hard threshold) | No | No (0 s) |
| Spot interruption | No (2-minute notice) | Only what fits in the notice |
Fix: a PDB for every replicated service (maxUnavailable: 1), minReplicas ≥ 2 so the PDB can ever be satisfied, and an application that drains on SIGTERM: the consumer Go package and Laravel's worker signal handling below.
Mechanics
From YAML to cgroup files
On a Linux node with cgroup v2, the kubelet passes requests and limits to the container runtime (containerd or CRI-O), which writes them into the container's cgroup. The Pod also gets a cgroup of its own, and QoS classes get parent cgroups (kubepods, kubepods/burstable, kubepods/besteffort).
| Pod spec | cgroup v2 file | Kernel behaviour | How to read it from inside the container |
|---|---|---|---|
requests.cpu | cpu.weight (default 100, range 1-10000) | Proportional share when CPUs are contended | cat /sys/fs/cgroup/cpu.weight |
limits.cpu | cpu.max ($MAX $PERIOD, default max 100000) | CFS bandwidth: throttle after $MAX µs per $PERIOD | cat /sys/fs/cgroup/cpu.max, cpu.stat |
no limits.cpu | cpu.max = max 100000 | No throttling | Go 1.25+ then defaults GOMAXPROCS to the CPU count |
limits.memory | memory.max | OOM killer in the cgroup when it cannot reclaim | memory.max, memory.current, memory.events (oom_kill) |
requests.memory | none by default; memory.min / memory.low with MemoryQoS TieredReservation | Protection from reclaim | memory.min, memory.low |
MemoryQoS memoryThrottlingFactor | memory.high = requests + factor × (limits − requests) | Throttles allocation before the hard limit | memory.high |
kubelet podPidsLimit | pids.max | fork fails with EAGAIN | pids.current, pids.max |
limits.ephemeral-storage | none (kubelet measures) | Pod eviction | df on emptyDir mounts |
| QoS class | oom_score_adj per process | Node OOM victim order | cat /proc/1/oom_score_adj |
The arithmetic for the most common CPU case, from the cgroup Go package: FromMilliCPU(500).String() is "50000 100000" and ParseCPUMax("50000 100000").CPUs() is 0.5; ParseCPUStat turns nr_periods 12000 and nr_throttled 4800 into a throttle ratio of 0.4, meaning 40 % of 100 ms periods hit the quota.
Node allocatable and the capacity check
allocatable = capacity - kubeReserved - systemReserved - hard eviction threshold
kubectl describe nodes e2e-test-node-pool-4lw4 (sample output from the Kubernetes docs)
Capacity: cpu: 2 memory: 7679792Ki pods: 110
Allocatable: cpu: 1800m memory: 7474992Ki pods: 110
Allocated resources:
CPU Requests CPU Limits Memory Requests Memory Limits
680m (34%) 400m (20%) 920Mi (11%) 1070Mi (13%)
-> "if a Pod requests more than 1.120 CPUs or more than 6.23Gi of memory, that Pod will not fit on the node"Limits can add up to more than 100 % ("Total limits may be over 100 percent, i.e., overcommitted"); requests cannot, because the scheduler refuses the node. That is the whole meaning of "requests are reservations".
The HPA algorithm, step by step
inputs: currentReplicas 6 (5 Ready, 1 not yet Ready), target CPU 70 % of request, target rps 150/Pod
1 per-Pod CPU % of request (metrics-server): 95, 90, 100, 85, 80, (unready: ignored for now)
2 ready average = 90 % -> ratio 90/70 = 1.29 > 1 + 0.1 -> scale-up candidate
3 unready Pod assumed 0 % for a scale-up: average over 6 = 75 % -> ratio 1.07 -> within tolerance
-> the "would the result reverse direction or fall inside tolerance?" check says: no scale on CPU
4 rps metric (custom.metrics.k8s.io): average 240/Pod -> ratio 1.6 -> desired ceil(6 x 1.6) = 10
5 largest desired across metrics = 10; scaleUp policies (Percent 100 / Pods 4, per 30 s, Max) -> +4 allowed -> 10
6 clamp to [minReplicas 3, maxReplicas 30] -> 10; record 10 in the stabilization history
7 write Deployment scale subresource replicas=10; ReplicaSet creates 4 Pods; scheduler places themThe scale-down direction is the same formula, then the window (highest recommendation in stabilizationWindowSeconds), then the scale-down policies. The hpa Go package's tests use the docs' own numbers: 200m against 100m doubles, 50m halves, and the 80 → 10 example with Pods 4 and Percent 10 policies removes 8, then 8 (7.2 rounded up), then 4 at a time below 40 replicas.
Knobs
| Knob | Where | Default | Notes |
|---|---|---|---|
--horizontal-pod-autoscaler-sync-period | kube-controller-manager | 15s | How often every HPA is evaluated |
--horizontal-pod-autoscaler-tolerance | kube-controller-manager | 0.1 | Per-HPA behavior.*.tolerance since 1.37 stable |
--horizontal-pod-autoscaler-downscale-stabilization | kube-controller-manager | 5m | Default scale-down window |
--horizontal-pod-autoscaler-initial-readiness-delay | kube-controller-manager | 30s | Unready Pods during start-up |
--horizontal-pod-autoscaler-cpu-initialization-period | kube-controller-manager | 5m | CPU samples ignored after start |
behavior.scaleDown.stabilizationWindowSeconds | HPA | 300 | Up to 3600 |
behavior.*.policies[].periodSeconds | HPA | 15 | Max 1800 |
evictionHard | kubelet | memory.available<100Mi, nodefs.available<10%, imagefs.available<15%, inodes <5% | Setting one disables the others' defaults unless MergeDefaultEvictionSettings |
evictionPressureTransitionPeriod | kubelet | 5m | Condition flap protection |
housekeeping-interval | kubelet | 10s | Eviction evaluation interval |
memoryThrottlingFactor / memoryReservationPolicy | kubelet (MemoryQoS) | nil / None | memory.high, memory.min/low |
cpuManagerPolicy | kubelet | none | static: exclusive cores for Guaranteed integer-CPU Pods |
percentageOfNodesToScore | kube-scheduler | adaptive (50 % at 100 nodes, 10 % at 5000, min 5 %) | Large clusters |
NodeResourcesFit.scoringStrategy.type | kube-scheduler | LeastAllocated | MostAllocated for binpacking |
--scan-interval | Cluster Autoscaler | 10s | Pending Pod check |
--scale-down-unneeded-time | Cluster Autoscaler | 10m | Node idle time before removal |
--scale-down-utilization-threshold | Cluster Autoscaler | 0.5 | Requests / allocatable |
--expander | Cluster Autoscaler | least-waste | priority,least-waste chains |
consolidationPolicy / consolidateAfter | Karpenter NodePool | WhenEmptyOrUnderutilized in examples / 0s | Never disables |
pollingInterval / cooldownPeriod | KEDA ScaledObject | 30 / 300 | Seconds |
minReplicaCount / maxReplicaCount | KEDA ScaledObject | 0 / 100 | idleReplicaCount below min |
updateMode | VPA | Recreate | Off, Initial, InPlaceOrRecreate, InPlace |
tolerationSeconds (auto-added) | Pod | 300 for not-ready/unreachable | Per-Pod override |
GOMAXPROCS | Go runtime | CPUs, or cpu.max rounded up and at least 2 (Go 1.25+, containermaxprocs=1) | Env var disables auto-updates |
GOMEMLIMIT | Go runtime | off (math.MaxInt64) | Soft; 5-10 % headroom below memory.max |
pm.max_children | php-fpm pool | mandatory | Concurrency and memory ceiling per Pod |
queue:work --memory / --timeout | Laravel worker | 128 MB / 60 s | --timeout below retry_after |
Error messages and statuses you will actually see
| Message or status | Meaning | Fix |
|---|---|---|
FailedScheduling ... 0/42 nodes available: insufficient cpu | Requests do not fit allocatable anywhere | Smaller requests, more nodes, check node autoscaler limits |
... node(s) had untolerated taint {...} | Taints without tolerations | Toleration + affinity, or other pool |
... didn't match pod topology spread constraints | maxSkew would be exceeded | Capacity in the short zone, ScheduleAnyway |
Reason: OOMKilled, Exit Code: 137 | Container passed memory.max | Raise request = limit, fix leak, size pools, GOMEMLIMIT |
Pod status Failed, reason Evicted, message naming memory | Node-pressure eviction | Requests closer to usage; reservations; limits on DaemonSets |
| Pod evicted, message naming ephemeral storage | ephemeral-storage limit | Stream to object storage, raise the limit |
403 Forbidden with a message explaining the violated LimitRange constraint | LimitRange max | Smaller request or change the LimitRange |
403 Forbidden with "a message explaining the constraint that would have been violated" (quota) | ResourceQuota full | Free quota or raise it |
| Pod rejected because a compute quota exists and the Pod sets no requests/limits | Quota requires values | Set resources or a LimitRange default |
HPA condition ScalingActive not true; no CPU utilisation | No metrics or no CPU request | Install metrics-server; set CPU requests; ContainerResource |
HPA condition ScalingLimited true | maxReplicas reached | Raise the max or fix the bottleneck |
NotTriggerScaleUp ... pod didn't trigger scale-up (it wouldn't fit if a new node is added) | No node group could hold the Pod | Bigger instance types, fix affinity/taints |
429 Too Many Requests on eviction | PDB blocks the eviction | Wait, add replicas, or relax the PDB |
PodResizePending reason Infeasible / Deferred | In-place resize impossible / not yet possible | Smaller resize, more room on the node |
Sources for the table: FailedScheduling, Insufficient cpu, OOMKilled/137 (resource management page); Failed phase and reason Evicted (node-pressure eviction page, Pod API status.reason "e.g. 'Evicted'"); 403 Forbidden with an explanatory message (LimitRange and ResourceQuota pages); ScalingActive/ScalingLimited (HPA walkthrough); NotTriggerScaleUp (Cluster Autoscaler FAQ); 429 (API-initiated eviction); PodResizePending (resize task). The page deliberately does not quote the exact message wording where no saved page shows it.
Go
The Go side is five small packages in one module (academy/kubernetes-resources-scheduling-autoscaling): qos and hpa reproduce the documented rules so they can be tested without a cluster, cgroup parses the files a container sees, runtimecfg sizes the Go runtime from them, and consumer is the graceful scale-down loop a queue worker needs. The manifests are the scheduling and autoscaling half of the orders-api service from Kubernetes Workloads.
Before
A Deployment and HPA that apply cleanly and fail in production in six ways (each comment says how):
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api
spec:
replicas: 3 # (1) fights the HPA: every `kubectl apply` resets the count
selector:
matchLabels: {app: orders-api}
template:
metadata:
labels: {app: orders-api}
spec:
containers:
- name: api
image: ghcr.io/acme/orders-api:1.4.2
resources:
limits:
cpu: 250m # (2) requests copied from limits: Guaranteed, but throttled at 25 ms/100 ms
memory: 128Mi # (3) Go heap grows to ~2x live heap before GC; no GOMEMLIMIT -> OOMKilled
# (4) Go 1.24 module on 16-core nodes: GOMAXPROCS=16 against a 0.25-CPU quota
# (5) no spread, no anti-affinity: all replicas can land on one node in one zone
---
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: orders-api
spec:
scaleTargetRef: {apiVersion: apps/v1, kind: Deployment, name: orders-api}
minReplicas: 1 # (6) one replica: no PDB can protect it, one zone outage is total
maxReplicas: 50
metrics:
- type: Resource
resource:
name: cpu
target: {type: Utilization, averageUtilization: 90} # throttling starts long before 90 %After
The runtime side: read cpu.max and memory.max, set GOMEMLIMIT to 90 % of the hard limit unless the environment already sets it, and report what the runtime chose.
// Package cgroup parses the cgroup v2 interface files that explain CPU
// throttling and OOM kills inside a container (Linux kernel
// admin-guide/cgroup-v2): cpu.max, cpu.stat, memory.max and memory.events.
// The functions take the file contents, so they are testable anywhere.
package cgroup
import (
"bufio"
"fmt"
"strconv"
"strings"
)
// DefaultPeriodUsec is the CFS bandwidth period the kernel uses by default
// (cpu.cfs_period_us=100ms; cpu.max defaults to "max 100000").
const DefaultPeriodUsec = 100000
// CPUMax is the parsed content of cpu.max: "$MAX $PERIOD".
type CPUMax struct {
QuotaUsec int64 // -1 when $MAX is "max" (no limit)
PeriodUsec int64
}
// ParseCPUMax parses "max 100000" or "50000 100000".
func ParseCPUMax(s string) (CPUMax, error) {
f := strings.Fields(s)
if len(f) == 0 || len(f) > 2 {
return CPUMax{}, fmt.Errorf("cpu.max: unexpected %q", s)
}
m := CPUMax{QuotaUsec: -1, PeriodUsec: DefaultPeriodUsec}
if len(f) == 2 {
p, err := strconv.ParseInt(f[1], 10, 64)
if err != nil || p <= 0 {
return CPUMax{}, fmt.Errorf("cpu.max: bad period %q", f[1])
}
m.PeriodUsec = p
}
if f[0] != "max" {
q, err := strconv.ParseInt(f[0], 10, 64)
if err != nil || q <= 0 {
return CPUMax{}, fmt.Errorf("cpu.max: bad quota %q", f[0])
}
m.QuotaUsec = q
}
return m, nil
}
// CPUs returns the limit in CPUs (quota / period), or 0 when unlimited.
func (m CPUMax) CPUs() float64 {
if m.QuotaUsec < 0 {
return 0
}
return float64(m.QuotaUsec) / float64(m.PeriodUsec)
}
// FromMilliCPU is the conventional conversion of a Kubernetes CPU limit to a
// CFS quota with the default 100 ms period: 500m -> "50000 100000".
func FromMilliCPU(milli int64) CPUMax {
return CPUMax{QuotaUsec: milli * DefaultPeriodUsec / 1000, PeriodUsec: DefaultPeriodUsec}
}
// String renders the value the way cpu.max shows it.
func (m CPUMax) String() string {
if m.QuotaUsec < 0 {
return fmt.Sprintf("max %d", m.PeriodUsec)
}
return fmt.Sprintf("%d %d", m.QuotaUsec, m.PeriodUsec)
}
// ParseFlatKeyed parses "key value" lines (cpu.stat, memory.events).
func ParseFlatKeyed(s string) (map[string]int64, error) {
out := map[string]int64{}
sc := bufio.NewScanner(strings.NewReader(s))
for sc.Scan() {
f := strings.Fields(sc.Text())
if len(f) == 0 {
continue
}
if len(f) != 2 {
return nil, fmt.Errorf("unexpected line %q", sc.Text())
}
v, err := strconv.ParseInt(f[1], 10, 64)
if err != nil {
return nil, fmt.Errorf("key %s: %w", f[0], err)
}
out[f[0]] = v
}
return out, sc.Err()
}
// Throttling summarises cpu.stat.
type Throttling struct {
Periods, Throttled int64
ThrottledUsec int64
}
// Ratio is the share of enforcement periods in which the cgroup hit its quota.
func (t Throttling) Ratio() float64 {
if t.Periods == 0 {
return 0
}
return float64(t.Throttled) / float64(t.Periods)
}
// ParseCPUStat extracts nr_periods, nr_throttled and throttled_usec.
func ParseCPUStat(s string) (Throttling, error) {
m, err := ParseFlatKeyed(s)
if err != nil {
return Throttling{}, err
}
return Throttling{Periods: m["nr_periods"], Throttled: m["nr_throttled"], ThrottledUsec: m["throttled_usec"]}, nil
}
// ParseMemoryMax returns the hard limit in bytes, or -1 for "max".
func ParseMemoryMax(s string) (int64, error) {
s = strings.TrimSpace(s)
if s == "max" {
return -1, nil
}
v, err := strconv.ParseInt(s, 10, 64)
if err != nil || v <= 0 {
return 0, fmt.Errorf("memory.max: unexpected %q", s)
}
return v, nil
}// Package runtimecfg sizes the Go runtime to the container it runs in.
//
// - GOMAXPROCS: since Go 1.25 the runtime derives the default from the cgroup
// CPU limit (cpu.max) and keeps it updated, when containermaxprocs and
// updatemaxprocs are on (this module's go.mod opts in). Kubernetes CPU
// requests are not considered by the runtime.
// - GOMEMLIMIT (Go 1.19): a soft limit. The GC guide's rule of thumb for a
// container is to leave 5-10% headroom below the hard limit, so Plan uses
// 90% of memory.max unless GOMEMLIMIT is already set in the environment.
package runtimecfg
import (
"errors"
"io/fs"
"math"
"runtime"
"runtime/debug"
"academy/kubernetes-resources-scheduling-autoscaling/cgroup"
)
// Paths of the cgroup v2 files as seen from inside a container (relative to
// "/", so an os.DirFS("/") or an fstest.MapFS can be passed).
const (
CPUMaxPath = "sys/fs/cgroup/cpu.max"
MemoryMaxPath = "sys/fs/cgroup/memory.max"
)
// Headroom is the fraction of the container memory limit given to GOMEMLIMIT.
const Headroom = 0.90
// Plan is what the process found and what it decided.
type Plan struct {
CPULimit float64 // CPUs from cpu.max, 0 = no limit or not found
MemoryMax int64 // bytes from memory.max, -1 = "max", 0 = not found
MemoryLimit int64 // the GOMEMLIMIT to apply, 0 = leave unchanged
MemoryLimitSrc string // "env", "cgroup", or "none"
}
// Build reads the cgroup files from fsys. envGOMEMLIMIT is the value of the
// GOMEMLIMIT environment variable ("" when unset).
func Build(fsys fs.FS, envGOMEMLIMIT string) (Plan, error) {
p := Plan{MemoryLimitSrc: "none"}
if b, err := fs.ReadFile(fsys, CPUMaxPath); err == nil {
m, err := cgroup.ParseCPUMax(string(b))
if err != nil {
return p, err
}
p.CPULimit = m.CPUs()
} else if !errors.Is(err, fs.ErrNotExist) {
return p, err
}
if b, err := fs.ReadFile(fsys, MemoryMaxPath); err == nil {
v, err := cgroup.ParseMemoryMax(string(b))
if err != nil {
return p, err
}
p.MemoryMax = v
} else if !errors.Is(err, fs.ErrNotExist) {
return p, err
}
switch {
case envGOMEMLIMIT != "":
// The runtime already parsed it at start-up; respect the operator.
p.MemoryLimitSrc = "env"
case p.MemoryMax > 0:
p.MemoryLimit = int64(math.Floor(float64(p.MemoryMax) * Headroom))
p.MemoryLimitSrc = "cgroup"
}
return p, nil
}
// Apply sets the soft memory limit when the plan has one and returns the
// effective values (a negative input to SetMemoryLimit only reads it).
func Apply(p Plan) (gomaxprocs int, memLimit int64) {
if p.MemoryLimit > 0 {
debug.SetMemoryLimit(p.MemoryLimit)
}
return runtime.GOMAXPROCS(0), debug.SetMemoryLimit(-1)
}// Command limits prints what the Go runtime sees of its container and applies
// GOMEMLIMIT = 90% of memory.max when the environment does not set it.
// Run it as the first thing in main() of a service, or on its own in a Pod to
// check a manifest: on a laptop (no cgroup files) it reports "none".
package main
import (
"fmt"
"os"
"runtime"
"academy/kubernetes-resources-scheduling-autoscaling/runtimecfg"
)
func main() {
plan, err := runtimecfg.Build(os.DirFS("/"), os.Getenv("GOMEMLIMIT"))
if err != nil {
fmt.Fprintln(os.Stderr, "cgroup:", err)
os.Exit(1)
}
procs, mem := runtimecfg.Apply(plan)
fmt.Printf("NumCPU=%d GOMAXPROCS=%d cpu.max=%.2f CPUs (0 = no limit)\n",
runtime.NumCPU(), procs, plan.CPULimit)
fmt.Printf("memory.max=%d (-1 = max, 0 = not found) GOMEMLIMIT=%d source=%s\n",
plan.MemoryMax, mem, plan.MemoryLimitSrc)
}The module opts in to container-aware GOMAXPROCS explicitly, because its go 1.24 line would otherwise give Go 1.24 defaults even when built with a newer toolchain:
module academy/kubernetes-resources-scheduling-autoscaling
go 1.24
// The go line above makes a newer toolchain default to Go 1.24 GODEBUG
// behaviour, which predates container-aware GOMAXPROCS (Go 1.25). Opt in
// explicitly so the binary reads the cgroup CPU limit and follows changes.
godebug (
containermaxprocs=1
updatemaxprocs=1
)Graceful scale-down for a queue consumer: stop fetching on SIGTERM, give the in-flight message a bounded drain budget, never acknowledge unfinished work:
// Package consumer shows graceful scale-down for a queue worker: when the
// autoscaler removes a replica, the Pod receives SIGTERM, the worker stops
// taking new messages at once and gets a bounded budget to finish the one it
// holds. The budget must fit inside terminationGracePeriodSeconds; anything
// unfinished is redelivered by the broker because it was never acknowledged.
package consumer
import (
"context"
"errors"
"time"
)
// Message is one unit of work with its acknowledgement.
type Message struct {
ID string
Ack func() error
}
// Fetch blocks until a message is available or ctx is done.
type Fetch func(ctx context.Context) (Message, error)
// Handle processes one message. It receives a context that is NOT cancelled
// by SIGTERM, only by the drain budget.
type Handle func(ctx context.Context, m Message) error
// Stats is what Run reports when it returns.
type Stats struct {
Processed int
}
// Run loops until ctx is cancelled (signal.NotifyContext on SIGTERM in main).
// The message in flight at cancellation gets up to drain to complete.
func Run(ctx context.Context, fetch Fetch, handle Handle, drain time.Duration) (Stats, error) {
var st Stats
for {
m, err := fetch(ctx)
if err != nil {
if ctx.Err() != nil {
return st, nil // stopped while waiting: nothing in flight
}
return st, err
}
// Detach from the stop signal, then bound the work: start the drain
// clock only once a stop has been requested.
work, cancel := context.WithCancel(context.WithoutCancel(ctx))
stop := context.AfterFunc(ctx, func() {
time.AfterFunc(drain, cancel)
})
err = handle(work, m)
stop()
cancel()
if err != nil {
if ctx.Err() != nil && errors.Is(err, context.Canceled) {
return st, context.DeadlineExceeded // drain budget exhausted, not acked
}
return st, err
}
if err := m.Ack(); err != nil {
return st, err
}
st.Processed++
if ctx.Err() != nil {
return st, nil // finished the in-flight message, take no more
}
}
}package consumer
import (
"context"
"errors"
"sync/atomic"
"testing"
"time"
)
// queue hands out messages from a channel, like a broker client would.
func queue(ch <-chan Message) Fetch {
return func(ctx context.Context) (Message, error) {
select {
case m := <-ch:
return m, nil
case <-ctx.Done():
return Message{}, ctx.Err()
}
}
}
func msg(id string, acked *atomic.Int32) Message {
return Message{ID: id, Ack: func() error { acked.Add(1); return nil }}
}
func TestStopFinishesInFlightMessage(t *testing.T) {
var acked atomic.Int32
ch := make(chan Message, 3)
ch <- msg("a", &acked)
ch <- msg("b", &acked)
ch <- msg("c", &acked)
ctx, stop := context.WithCancel(context.Background())
started := make(chan struct{}, 3)
handle := func(ctx context.Context, m Message) error {
started <- struct{}{}
if m.ID == "b" {
stop() // SIGTERM arrives while "b" is being processed
select {
case <-time.After(50 * time.Millisecond): // the work completes
case <-ctx.Done():
return ctx.Err()
}
}
return nil
}
st, err := Run(ctx, queue(ch), handle, time.Second)
if err != nil {
t.Fatal(err)
}
if st.Processed != 2 || acked.Load() != 2 || len(ch) != 1 {
t.Fatalf("processed %d acked %d left %d; want 2, 2, 1 (c stays queued)", st.Processed, acked.Load(), len(ch))
}
}
func TestDrainBudgetExceeded(t *testing.T) {
var acked atomic.Int32
ch := make(chan Message, 1)
ch <- msg("slow", &acked)
ctx, stop := context.WithCancel(context.Background())
handle := func(ctx context.Context, m Message) error {
stop()
<-ctx.Done() // a job that never finishes on its own
return ctx.Err()
}
t0 := time.Now()
_, err := Run(ctx, queue(ch), handle, 100*time.Millisecond)
if !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("err %v, want DeadlineExceeded", err)
}
if acked.Load() != 0 {
t.Fatal("unfinished message must not be acked (the broker redelivers it)")
}
if d := time.Since(t0); d < 100*time.Millisecond || d > time.Second {
t.Fatalf("drain took %v", d)
}
}
func TestIdleStop(t *testing.T) {
ctx, stop := context.WithCancel(context.Background())
time.AfterFunc(20*time.Millisecond, stop)
st, err := Run(ctx, queue(make(chan Message)), func(context.Context, Message) error { return nil }, time.Second)
if err != nil || st.Processed != 0 {
t.Fatalf("idle stop: %+v %v", st, err)
}
}The rules as code, tested on the docs' examples (QoS classification, oom_score_adj, the HPA formula, policies and stabilization window):
// Package qos reproduces two rules from the Kubernetes documentation so they
// can be tested without a cluster:
//
// - how a Pod's QoS class is derived from its containers' requests and
// limits (concepts/workloads/pods/pod-qos), and
// - which oom_score_adj the kubelet writes for each class
// (concepts/scheduling-eviction/node-pressure-eviction).
//
// Quantities are plain integers: CPU in millicores, memory in bytes.
package qos
// Class is a Pod QoS class.
type Class string
const (
Guaranteed Class = "Guaranteed"
Burstable Class = "Burstable"
BestEffort Class = "BestEffort"
)
// Resources holds the CPU (millicores) and memory (bytes) values of one
// requests or limits map. Zero means "not set".
type Resources struct {
CPUMilli int64
MemBytes int64
}
// Container is the part of a container spec that the QoS rules read.
type Container struct {
Name string
Requests Resources
Limits Resources
}
// effectiveRequests applies the API defaulting rule: "If you specify a limit
// for a resource, but do not specify any request ... Kubernetes copies the
// limit you specified and uses it as the requested value".
func effectiveRequests(c Container) Resources {
r := c.Requests
if r.CPUMilli == 0 && c.Limits.CPUMilli > 0 {
r.CPUMilli = c.Limits.CPUMilli
}
if r.MemBytes == 0 && c.Limits.MemBytes > 0 {
r.MemBytes = c.Limits.MemBytes
}
return r
}
// Classify returns the QoS class of a Pod made of these containers
// (init and regular containers alike). Pod-level resources are not modelled.
func Classify(containers []Container) Class {
guaranteed := len(containers) > 0
setAny := false
for _, c := range containers {
req := effectiveRequests(c)
lim := c.Limits
if req.CPUMilli > 0 || req.MemBytes > 0 || lim.CPUMilli > 0 || lim.MemBytes > 0 {
setAny = true
}
// Guaranteed: every container has CPU and memory limits and requests,
// all greater than zero, with limit == request for both.
if lim.CPUMilli == 0 || lim.MemBytes == 0 ||
req.CPUMilli != lim.CPUMilli || req.MemBytes != lim.MemBytes {
guaranteed = false
}
}
switch {
case guaranteed:
return Guaranteed
case setAny:
return Burstable
default:
return BestEffort
}
}
// OOMScoreAdj returns the oom_score_adj the kubelet sets for a container,
// following the table in the node-pressure eviction page:
//
// Guaranteed -997
// BestEffort 1000
// Burstable min(max(2, 1000 - (1000*memoryRequestBytes)/machineMemoryCapacityBytes), 999)
func OOMScoreAdj(class Class, memRequestBytes, machineMemBytes int64) int64 {
switch class {
case Guaranteed:
return -997
case BestEffort:
return 1000
}
if machineMemBytes <= 0 {
return 999
}
adj := 1000 - (1000*memRequestBytes)/machineMemBytes
if adj < 2 {
adj = 2
}
if adj > 999 {
adj = 999
}
return adj
}// Package hpa is a small, testable model of the HorizontalPodAutoscaler
// arithmetic documented in concepts/workloads/autoscaling/horizontal-pod-autoscale:
//
// desiredReplicas = ceil(currentReplicas * currentMetricValue / desiredMetricValue)
//
// with the tolerance band (0.1 by default), the scaling policies of
// spec.behavior (Pods / Percent, selectPolicy Max / Min) and the
// stabilization window. It is a teaching model, not the controller: it
// ignores unready Pods, missing metrics and the per-period replica history.
package hpa
import (
"math"
"time"
)
// DefaultTolerance is the cluster-wide default (--horizontal-pod-autoscaler-tolerance).
const DefaultTolerance = 0.1
// DesiredReplicas applies the core formula. If the ratio is within the
// tolerance of 1.0, the current count is kept.
func DesiredReplicas(current int32, currentValue, targetValue, tolerance float64) int32 {
if targetValue <= 0 || current <= 0 {
return current
}
ratio := currentValue / targetValue
if math.Abs(ratio-1.0) <= tolerance {
return current
}
return int32(math.Ceil(float64(current) * ratio))
}
// PolicyType is the type of a scaling policy.
type PolicyType string
const (
Pods PolicyType = "Pods"
Percent PolicyType = "Percent"
)
// Policy is one entry of behavior.scaleUp.policies or behavior.scaleDown.policies.
type Policy struct {
Type PolicyType
Value int32
}
// change returns how many replicas one policy allows to add or remove now.
// Percent rounds up: "10% of the pods is 7.2 but the number is rounded up to 8".
func change(current int32, p Policy) int32 {
if p.Type == Pods {
return p.Value
}
return int32(math.Ceil(float64(current) * float64(p.Value) / 100))
}
// allowed picks the biggest change (selectPolicy: Max, the default) or the
// smallest (selectPolicy: Min).
func allowed(current int32, policies []Policy, selectMin bool) int32 {
best := int32(-1)
for _, p := range policies {
c := change(current, p)
if best < 0 || (!selectMin && c > best) || (selectMin && c < best) {
best = c
}
}
if best < 0 {
return 0
}
return best
}
// DefaultScaleUp and DefaultScaleDown are the documented default behaviour.
var (
DefaultScaleUp = []Policy{{Percent, 100}, {Pods, 4}} // every 15 s, selectPolicy Max
DefaultScaleDown = []Policy{{Percent, 100}} // every 15 s
)
// Limit moves from current towards desired, bounded by the policies of the
// direction it moves in and by minReplicas / maxReplicas.
func Limit(current, desired, minReplicas, maxReplicas int32, up, down []Policy, selectMin bool) int32 {
next := desired
switch {
case desired > current:
if ceiling := current + allowed(current, up, selectMin); next > ceiling {
next = ceiling
}
case desired < current:
if floor := current - allowed(current, down, selectMin); next < floor {
next = floor
}
}
if next < minReplicas {
next = minReplicas
}
if next > maxReplicas {
next = maxReplicas
}
return next
}
type sample struct {
at time.Time
desired int32
}
// Stabilizer implements the scale-down stabilization window: "the algorithm
// looks into previously computed desired states, and uses the highest value
// from the specified interval".
type Stabilizer struct {
Window time.Duration // behavior.scaleDown.stabilizationWindowSeconds (default 300 s)
history []sample
}
// Recommend records the newly computed desired count and returns the
// stabilized one (the maximum over the window).
func (s *Stabilizer) Recommend(now time.Time, desired int32) int32 {
s.history = append(s.history, sample{now, desired})
keep := s.history[:0]
best := desired
for _, h := range s.history {
if now.Sub(h.at) > s.Window {
continue
}
keep = append(keep, h)
if h.desired > best {
best = h.desired
}
}
s.history = keep
return best
}package hpa
import (
"testing"
"time"
)
func TestDesiredReplicasDocsExamples(t *testing.T) {
// "if the current metric value is 200m, and the desired value is 100m,
// the number of replicas will be doubled"; 50m halves it.
if got := DesiredReplicas(4, 200, 100, DefaultTolerance); got != 8 {
t.Fatalf("200m/100m: got %d, want 8", got)
}
if got := DesiredReplicas(4, 50, 100, DefaultTolerance); got != 2 {
t.Fatalf("50m/100m: got %d, want 2", got)
}
// Within the 10 % band: no action.
if got := DesiredReplicas(10, 108, 100, DefaultTolerance); got != 10 {
t.Fatalf("ratio 1.08: got %d, want 10", got)
}
// Just outside the band, and ceil rounds up: 10 * 1.11 = 11.1 -> 12.
if got := DesiredReplicas(10, 111, 100, DefaultTolerance); got != 12 {
t.Fatalf("ratio 1.11: got %d, want 12", got)
}
// A 5 % scale-up tolerance (behavior.scaleUp.tolerance) reacts earlier.
if got := DesiredReplicas(10, 108, 100, 0.05); got != 11 {
t.Fatalf("ratio 1.08 with 0.05: got %d, want 11", got)
}
}
func TestScaleDownPoliciesDocsExample(t *testing.T) {
// Pods 4 / 60 s and Percent 10 / 60 s, selectPolicy Max, 80 -> 10:
// first step removes 8, then 72 -> 64 (7.2 rounded up to 8), and below
// 40 replicas the Pods policy (4) wins.
down := []Policy{{Pods, 4}, {Percent, 10}}
steps := []struct{ from, want int32 }{{80, 72}, {72, 64}, {40, 36}, {36, 32}}
for _, s := range steps {
if got := Limit(s.from, 10, 1, 100, DefaultScaleUp, down, false); got != s.want {
t.Errorf("from %d: got %d, want %d", s.from, got, s.want)
}
}
// selectPolicy Min picks the smaller change: 80 -> 76.
if got := Limit(80, 10, 1, 100, DefaultScaleUp, down, true); got != 76 {
t.Errorf("Min from 80: got %d, want 76", got)
}
}
func TestDefaultScaleUp(t *testing.T) {
// Default: add 100 % or 4 Pods per 15 s, whichever is more.
if got := Limit(1, 50, 1, 100, DefaultScaleUp, DefaultScaleDown, false); got != 5 {
t.Errorf("from 1: got %d, want 5", got)
}
if got := Limit(10, 50, 1, 100, DefaultScaleUp, DefaultScaleDown, false); got != 20 {
t.Errorf("from 10: got %d, want 20", got)
}
// maxReplicas wins over policies.
if got := Limit(10, 50, 1, 12, DefaultScaleUp, DefaultScaleDown, false); got != 12 {
t.Errorf("maxReplicas: got %d, want 12", got)
}
}
func TestStabilizationWindow(t *testing.T) {
s := &Stabilizer{Window: 300 * time.Second}
t0 := time.Unix(0, 0)
if got := s.Recommend(t0, 10); got != 10 {
t.Fatalf("t0: got %d", got)
}
// Load drops: the raw recommendation is 4 but the window still holds 10.
if got := s.Recommend(t0.Add(60*time.Second), 4); got != 10 {
t.Fatalf("t60: got %d, want 10", got)
}
if got := s.Recommend(t0.Add(240*time.Second), 4); got != 10 {
t.Fatalf("t240: got %d, want 10", got)
}
// Once the 10 is older than 300 s, the highest value left is 4.
if got := s.Recommend(t0.Add(301*time.Second), 4); got != 4 {
t.Fatalf("t301: got %d, want 4", got)
}
}The manifests: orders-api with resources, priority, affinity and spread; its HPA; a recommendation-only VPA; a Kafka-lag ScaledObject for the Go projector; a RabbitMQ ScaledJob:
# orders-api (the Go service of the workloads chapter) with the fields this
# chapter owns: resources, priority, placement and spread. Probes, rollout
# strategy and termination are in the workloads chapter's manifest.
# No `replicas:` line: the HorizontalPodAutoscaler in hpa.yaml owns the count.
#
# Sizing (from a week of VPA "Off" recommendations, see vpa.yaml):
# memory: request == limit (memory is not compressible; no surprise OOM from
# a neighbour, and the limit is what GOMEMLIMIT is derived from)
# cpu: request only, no limit (no CFS throttling; idle CPU on the node is
# usable). The Pod is therefore Burstable, not Guaranteed.
apiVersion: apps/v1
kind: Deployment
metadata:
name: orders-api
namespace: shop
labels:
app.kubernetes.io/name: orders-api
app.kubernetes.io/part-of: shop
spec:
selector:
matchLabels:
app.kubernetes.io/name: orders-api
template:
metadata:
labels:
app.kubernetes.io/name: orders-api
app.kubernetes.io/part-of: shop
spec:
priorityClassName: shop-critical
terminationGracePeriodSeconds: 30
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: kubernetes.io/arch
operator: In
values: ["amd64", "arm64"] # the image is a multi-arch index
- key: karpenter.sh/capacity-type
operator: In
values: ["on-demand"] # user-facing API: no spot
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 50
preference:
matchExpressions:
- key: kubernetes.io/arch
operator: In
values: ["arm64"] # cheaper per core where offered
podAntiAffinity:
# Soft: prefer not to share a node with another orders-api replica.
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
podAffinityTerm:
topologyKey: kubernetes.io/hostname
labelSelector:
matchLabels:
app.kubernetes.io/name: orders-api
topologySpreadConstraints:
# Hard across zones: losing one zone loses at most ~1/3 of replicas.
- maxSkew: 1
topologyKey: topology.kubernetes.io/zone
whenUnsatisfiable: DoNotSchedule
minDomains: 3
labelSelector:
matchLabels:
app.kubernetes.io/name: orders-api
matchLabelKeys: ["pod-template-hash"] # spread each rollout revision on its own
nodeTaintsPolicy: Honor # do not count nodes the Pod cannot tolerate
# Soft across nodes.
- maxSkew: 1
topologyKey: kubernetes.io/hostname
whenUnsatisfiable: ScheduleAnyway
labelSelector:
matchLabels:
app.kubernetes.io/name: orders-api
containers:
- name: api
image: ghcr.io/acme/orders-api:1.4.2
ports:
- name: http
containerPort: 8080
env:
# No CPU limit means no cgroup quota for the Go runtime to read, so
# size GOMAXPROCS from the request (exposed rounded up: 500m -> 1).
# With a CPU limit instead, delete this and let Go 1.25+ read cpu.max.
- name: GOMAXPROCS
valueFrom:
resourceFieldRef:
containerName: api
resource: requests.cpu
divisor: "1"
# GOMEMLIMIT is left unset: the binary sets 90% of memory.max at
# start (runtimecfg package). Exposing limits.memory here would give
# 100% of the limit and no headroom.
resources:
requests:
cpu: 500m
memory: 256Mi
ephemeral-storage: 256Mi # logs + writable layer; evicted if it exceeds the limit
limits:
memory: 256Mi
ephemeral-storage: 1Gi# Scales orders-api between 3 and 30 replicas on two signals; the HPA takes the
# largest replica count any metric asks for.
# 1. CPU utilisation, measured against the CPU *request* (500m): 70% means
# an average of 350m per Pod. Needs metrics-server (metrics.k8s.io).
# 2. Requests per second per Pod, a custom metric served by a metrics adapter
# (for example prometheus-adapter) under custom.metrics.k8s.io.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: orders-api
namespace: shop
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: orders-api
minReplicas: 3 # one per zone, matches minDomains in the Deployment
maxReplicas: 30
metrics:
- type: Resource
resource:
name: cpu
target:
type: Utilization
averageUtilization: 70
- type: Pods
pods:
metric:
name: http_requests_per_second
target:
type: AverageValue
averageValue: "150"
behavior:
scaleUp:
stabilizationWindowSeconds: 0 # react at once (the default)
selectPolicy: Max
policies:
- type: Percent
value: 100 # at most double ...
periodSeconds: 30
- type: Pods
value: 4 # ... or +4 Pods, whichever is more, per 30 s
periodSeconds: 30
scaleDown:
stabilizationWindowSeconds: 300 # use the highest recommendation of the last 5 min
selectPolicy: Min
policies:
- type: Percent
value: 20 # remove at most 20% ...
periodSeconds: 60
- type: Pods
value: 2 # ... or 2 Pods, whichever is fewer, per minute
periodSeconds: 60# Recommendation-only VPA for orders-api. The HPA above scales on CPU, and
# VPA must not act on the same resource metric, so updateMode is "Off": read
# the numbers (kubectl describe vpa orders-api) and change the Deployment by
# hand or in Git. Requires the VPA components and metrics-server.
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: orders-api
namespace: shop
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: orders-api
updatePolicy:
updateMode: "Off"
resourcePolicy:
containerPolicies:
- containerName: api
minAllowed:
cpu: 100m
memory: 128Mi
maxAllowed:
cpu: "2"
memory: 1Gi
controlledResources: ["cpu", "memory"]# orders-projector: a Go Kafka consumer (consumer package of this chapter) in
# consumer group "orders-projector" on topic "orders". KEDA creates and owns an
# HPA named keda-hpa-orders-projector; do not add another HPA for this Deployment.
# Lag per replica target 500 messages; never more replicas than partitions
# (allowIdleConsumers: false is the default and is written out here).
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: orders-projector
namespace: shop
spec:
scaleTargetRef:
name: orders-projector # Deployment, apps/v1 by default
pollingInterval: 15 # seconds between trigger checks (default 30)
cooldownPeriod: 300 # idle time before scaling back to zero (default 300)
minReplicaCount: 0 # scale to zero when the topic has no lag
maxReplicaCount: 12 # the topic has 12 partitions
fallback:
failureThreshold: 3 # Kafka unreachable 3 times in a row ...
replicas: 4 # ... hold 4 replicas instead of guessing
advanced:
horizontalPodAutoscalerConfig:
behavior:
scaleDown:
stabilizationWindowSeconds: 120
triggers:
- type: kafka
metadata:
bootstrapServers: kafka-bootstrap.messaging.svc:9092
consumerGroup: orders-projector
topic: orders
lagThreshold: "500"
activationLagThreshold: "10" # wake from zero only above 10 messages
offsetResetPolicy: latest
allowIdleConsumers: "false"# A ScaledJob runs one Kubernetes Job per batch of messages instead of scaling
# a long-lived Deployment: good for long, uneven work (image or PDF rendering)
# where killing a busy replica on scale-down would waste minutes of work.
# Each Job's Pod processes messages until the queue is empty, then exits 0.
apiVersion: keda.sh/v1alpha1
kind: ScaledJob
metadata:
name: thumbnails
namespace: shop
spec:
jobTargetRef:
backoffLimit: 2
activeDeadlineSeconds: 3600
template:
spec:
restartPolicy: Never
priorityClassName: shop-batch
tolerations:
- key: workload
operator: Equal
value: batch
effect: NoSchedule
containers:
- name: worker
image: ghcr.io/acme/thumbnails:2.1.0
args: ["--exit-when-empty"]
resources:
requests:
cpu: "1"
memory: 1Gi
limits:
memory: 1Gi
pollingInterval: 20
maxReplicaCount: 20 # at most 20 Jobs running at once
successfulJobsHistoryLimit: 5
failedJobsHistoryLimit: 5
triggers:
- type: rabbitmq
metadata:
protocol: amqp
queueName: thumbnails
mode: QueueLength
value: "50" # one Job per 50 waiting messages
authenticationRef:
name: rabbitmq-shop
---
# The connection string lives in a Secret; KEDA reads it through this object.
apiVersion: keda.sh/v1alpha1
kind: TriggerAuthentication
metadata:
name: rabbitmq-shop
namespace: shop
spec:
secretTargetRef:
- parameter: host
name: rabbitmq-shop # Secret with key "host": amqp://user:pass@rabbitmq.messaging.svc:5672/shop
key: hostNamespace guard rails, priorities and the QoS examples:
# Namespace guard rails for "shop" (admission-time only: existing Pods are not
# changed when this object is created or edited).
# - default / defaultRequest: filled into containers that omit them, so a
# Pod without resources is not BestEffort by accident.
# - min / max: a container outside the range is rejected with 403 Forbidden.
# - maxLimitRequestRatio: limit may be at most 4x the request (bounds overcommit).
# Defaults are not checked for consistency: a default limit below a request the
# user wrote makes the Pod unschedulable, so keep default >= defaultRequest and
# max >= any request you expect.
apiVersion: v1
kind: LimitRange
metadata:
name: shop-defaults
namespace: shop
spec:
limits:
- type: Container
defaultRequest:
cpu: 100m
memory: 128Mi
default: # the default *limit*
memory: 256Mi # no default CPU limit on purpose (see "limits debate")
min:
cpu: 10m
memory: 32Mi
max:
cpu: "4"
memory: 4Gi
maxLimitRequestRatio:
memory: "4"
- type: Pod
max:
memory: 8Gi
- type: PersistentVolumeClaim
min:
storage: 1Gi
max:
storage: 100Gi# Totals for the whole "shop" namespace. Quota counts requests and limits of
# Pods in a non-terminal state, not their live usage. Once a compute quota
# exists, every new Pod must state requests/limits for the quota'd resources
# (the LimitRange defaults above satisfy that).
apiVersion: v1
kind: ResourceQuota
metadata:
name: shop-compute
namespace: shop
spec:
hard:
requests.cpu: "40"
requests.memory: 80Gi
limits.memory: 120Gi
requests.ephemeral-storage: 200Gi
limits.ephemeral-storage: 400Gi
pods: "300"
count/deployments.apps: "40"
count/jobs.batch: "100"
persistentvolumeclaims: "20"
requests.storage: 1Ti
services.loadbalancers: "2"
---
# A second quota with a scope: BestEffort Pods (no requests at all) are capped
# at zero, so nobody can bypass the compute quota with resource-less Pods.
apiVersion: v1
kind: ResourceQuota
metadata:
name: shop-no-besteffort
namespace: shop
spec:
hard:
pods: "0"
scopes:
- BestEffort
---
# Only a small slice of the namespace may use the high priority class.
apiVersion: v1
kind: ResourceQuota
metadata:
name: shop-critical-slice
namespace: shop
spec:
hard:
requests.cpu: "8"
requests.memory: 16Gi
pods: "30"
scopeSelector:
matchExpressions:
- scopeName: PriorityClass
operator: In
values: ["shop-critical"]# User priority values must be <= 1000000000; larger values are reserved for
# system-cluster-critical (2000000000) and system-node-critical (2000001000).
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: shop-critical
value: 100000
globalDefault: false
description: "Checkout and order APIs: may preempt batch work when the cluster is full."
---
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: shop-default
value: 10000
globalDefault: true # only one PriorityClass in the cluster may set this
description: "Everything that does not ask for another class."
---
# Batch jobs queue ahead of default work but never evict anyone to get a seat.
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: shop-batch
value: 1000
preemptionPolicy: Never
globalDefault: false
description: "Reports and exports: wait for free capacity, never preempt."# Three Pods, three QoS classes. `kubectl get pod <name> -o jsonpath='{.status.qosClass}'`
# prints the class (expected, not run).
apiVersion: v1
kind: Pod
metadata:
name: qos-guaranteed
namespace: shop
spec:
containers:
- name: app
image: ghcr.io/acme/orders-api:1.4.2
resources: # every container: requests == limits for CPU and memory
requests:
cpu: 500m
memory: 256Mi
limits:
cpu: 500m
memory: 256Mi
---
apiVersion: v1
kind: Pod
metadata:
name: qos-burstable
namespace: shop
spec:
containers:
- name: app
image: ghcr.io/acme/orders-api:1.4.2
resources: # memory request == limit, CPU request without limit
requests:
cpu: 250m
memory: 256Mi
limits:
memory: 256Mi
---
# In namespace "shop" this Pod is first given LimitRange defaults (and would
# become Burstable); the BestEffort-scoped quota would reject it anyway. It is
# shown in "sandbox", a namespace without either.
apiVersion: v1
kind: Pod
metadata:
name: qos-besteffort
namespace: sandbox
spec:
containers:
- name: app
image: ghcr.io/acme/orders-api:1.4.2Cluster-level configuration (usually owned by the platform team, applied through Terraform, Helm or Argo CD):
# Two Karpenter NodePools (karpenter.sh/v1) on AWS. Both reference an
# EC2NodeClass named "default" (AMI, subnets, security groups, IAM role),
# which is provider configuration and usually created with Terraform.
#
# general: on-demand and spot, arm64 and amd64, consolidates when nodes are
# empty or underutilised, never more than 10% of nodes at once and
# not at all during the Tuesday release window.
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
name: general
spec:
template:
metadata:
labels:
workload: general
spec:
nodeClassRef:
group: karpenter.k8s.aws
kind: EC2NodeClass
name: default
expireAfter: 720h # replace nodes after 30 days (patching, drift)
terminationGracePeriod: 24h # hard ceiling for a drain blocked by PDBs
requirements:
- key: karpenter.sh/capacity-type
operator: In
values: ["on-demand", "spot"]
- key: kubernetes.io/arch
operator: In
values: ["arm64", "amd64"]
- key: karpenter.k8s.aws/instance-category
operator: In
values: ["c", "m", "r"]
- key: karpenter.k8s.aws/instance-generation
operator: Gt
values: ["5"]
disruption:
consolidationPolicy: WhenEmptyOrUnderutilized
consolidateAfter: 5m
budgets:
- nodes: "10%"
- schedule: "0 9 * * tue"
duration: 4h
nodes: "0"
limits:
cpu: "400"
memory: 1600Gi
weight: 10
---
# batch: spot only, tainted so only Pods that tolerate workload=batch land
# here; consolidation only of empty nodes so running exports are not moved.
apiVersion: karpenter.sh/v1
kind: NodePool
metadata:
name: batch
spec:
template:
metadata:
labels:
workload: batch
spec:
nodeClassRef:
group: karpenter.k8s.aws
kind: EC2NodeClass
name: default
taints:
- key: workload
value: batch
effect: NoSchedule
expireAfter: 168h
requirements:
- key: karpenter.sh/capacity-type
operator: In
values: ["spot"]
- key: karpenter.k8s.aws/instance-category
operator: In
values: ["c", "m"]
- key: karpenter.k8s.aws/instance-cpu
operator: In
values: ["4", "8", "16"]
disruption:
consolidationPolicy: WhenEmpty
consolidateAfter: 2m
limits:
cpu: "200"# Node-side knobs that decide when the kubelet evicts Pods (node-pressure
# eviction) and how much of the machine Pods may request at all:
# allocatable = capacity - kubeReserved - systemReserved - hard eviction threshold
# Usually set through the node image or the managed node group, not by hand.
apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
kubeReserved:
cpu: 200m
memory: 512Mi
ephemeral-storage: 1Gi
systemReserved:
cpu: 100m
memory: 256Mi
evictionHard: # no grace period: Pods are killed at once
memory.available: "200Mi"
nodefs.available: "10%"
imagefs.available: "15%"
nodefs.inodesFree: "5%"
pid.available: "5%"
evictionSoft: # must hold for the grace period before evicting
memory.available: "500Mi"
evictionSoftGracePeriod:
memory.available: "1m30s"
evictionMaxPodGracePeriod: 60 # cap on terminationGracePeriodSeconds for soft evictions
evictionMinimumReclaim:
memory.available: "100Mi"
evictionPressureTransitionPeriod: 5m# A second kube-scheduler profile that packs Pods onto the fullest nodes
# (MostAllocated) instead of the default spreading (LeastAllocated), so
# whole nodes empty out and the cluster autoscaler can remove them. Pods opt
# in with `schedulerName: bin-packing-scheduler`.
apiVersion: kubescheduler.config.k8s.io/v1
kind: KubeSchedulerConfiguration
profiles:
- schedulerName: default-scheduler
- schedulerName: bin-packing-scheduler
pluginConfig:
- name: NodeResourcesFit
args:
scoringStrategy:
type: MostAllocated
resources:
- name: cpu
weight: 1
- name: memory
weight: 1# Headroom for fast scale-up (Cluster Autoscaler FAQ pattern; works the same
# with Karpenter). Pause Pods hold 2 x (1 CPU, 2Gi) of requests at priority
# -10. When a real Pod is Pending, the scheduler preempts a pause Pod at once;
# the evicted pause Pod is now Pending and makes the autoscaler add a node in
# the background, so the next spike again finds a warm slot.
apiVersion: scheduling.k8s.io/v1
kind: PriorityClass
metadata:
name: overprovisioning
value: -10
globalDefault: false
description: "Placeholder Pods that any real workload may preempt."
---
apiVersion: apps/v1
kind: Deployment
metadata:
name: overprovisioning
namespace: kube-system
spec:
replicas: 2
selector:
matchLabels:
app.kubernetes.io/name: overprovisioning
template:
metadata:
labels:
app.kubernetes.io/name: overprovisioning
spec:
priorityClassName: overprovisioning
terminationGracePeriodSeconds: 0
containers:
- name: reserve
image: registry.k8s.io/pause:3.10
resources:
requests:
cpu: "1"
memory: 2GiThe offline checker that every manifest above passes (YAML parse, field names against the saved API references, and 34 rules such as "an autoscaled Deployment has no replicas", "no target has both an HPA and a ScaledObject", "a VPA does not act on the resource its HPA scales on", "minDomains only with DoNotSchedule"):
#!/usr/bin/env ruby
# Offline checks for this chapter's manifests (no cluster, no kubectl):
# 1. every file parses as YAML;
# 2. every field name appears in the saved reference pages (Kubernetes API,
# kubelet and scheduler config, VPA API, KEDA spec and scalers, Karpenter);
# 3. the rules an API server, an admission webhook or the autoscalers would
# reject or silently misbehave on, checked by hand.
# Usage: ruby check-manifests.rb <sources-dir> <manifest files...>
require 'yaml'
src, *files = ARGV
corpus = Dir[File.join(src, '{api-,keda-,karpenter-,vpa-,resource-quotas,limit-range,node-pressure,taints}*.txt')].map { |f| File.read(f) }.join("\n")
FREE = %w[labels annotations matchLabels nodeSelector].freeze
$errors = []
def err(f, m); $errors << "#{f}: #{m}"; end
def keys(node, out)
case node
when Hash
node.each do |k, v|
out << k.to_s
keys(v, out) unless FREE.include?(k.to_s)
end
when Array then node.each { |v| keys(v, out) }
end
end
def qty(v)
return nil if v.nil?
s = v.to_s
units = { 'm' => 0.001, 'Ki' => 2**10, 'Mi' => 2**20, 'Gi' => 2**30, 'Ti' => 2**40, 'k' => 1e3, 'M' => 1e6, 'G' => 1e9 }
units.each { |u, mul| return s.chomp(u).to_f * mul if s.end_with?(u) && s.chomp(u) =~ /\A[0-9.]+\z/ }
s =~ /\A[0-9.]+\z/ ? s.to_f : (raise "bad quantity #{s}")
end
def pod_spec(d)
case d['kind']
when 'Deployment', 'StatefulSet', 'DaemonSet', 'Job' then d.dig('spec', 'template', 'spec')
when 'Pod' then d['spec']
when 'ScaledJob' then d.dig('spec', 'jobTargetRef', 'template', 'spec')
end
end
def qos(ps)
cs = (ps['containers'] || []) + (ps['initContainers'] || [])
any = false; guaranteed = !cs.empty?
cs.each do |c|
lim = c.dig('resources', 'limits') || {}
req = (c.dig('resources', 'requests') || {}).dup
%w[cpu memory].each { |r| req[r] ||= lim[r] }
any ||= %w[cpu memory].any? { |r| req[r] || lim[r] }
guaranteed &&= %w[cpu memory].all? { |r| lim[r] && qty(req[r]) == qty(lim[r]) }
end
guaranteed ? 'Guaranteed' : (any ? 'Burstable' : 'BestEffort')
end
docs = files.flat_map { |f| YAML.load_stream(File.read(f)).compact.map { |d| [f, d] } }
by = ->(kind) { docs.select { |_, d| d['kind'] == kind } }
target = ->(d) { d.dig('spec', 'scaleTargetRef', 'name') || d.dig('spec', 'targetRef', 'name') }
docs.each do |f, d|
found = []; keys(d, found)
found.uniq.each { |k| err(f, "field '#{k}' not in saved references") unless corpus.include?(k) }
spec = d['spec'] || {}
ps = pod_spec(d)
name = d.dig('metadata', 'name')
if ps
((ps['containers'] || []) + (ps['initContainers'] || [])).each do |c|
req = c.dig('resources', 'requests') || {}; lim = c.dig('resources', 'limits') || {}
lim.each { |r, v| err(f, "#{c['name']}: request #{r} > limit") if req[r] && qty(req[r]) > qty(v) }
end
(ps['tolerations'] || []).each do |t|
err(f, "bad toleration effect #{t['effect']}") if t['effect'] && !%w[NoSchedule PreferNoSchedule NoExecute].include?(t['effect'])
err(f, 'tolerationSeconds needs effect NoExecute') if t['tolerationSeconds'] && t['effect'] != 'NoExecute'
err(f, 'operator Exists must not have a value') if t['operator'] == 'Exists' && t['value']
end
seen = {}
(ps['topologySpreadConstraints'] || []).each do |c|
k = [c['topologyKey'], c['whenUnsatisfiable'] || 'DoNotSchedule']
err(f, "duplicate spread constraint #{k}") if seen[k]; seen[k] = true
err(f, 'maxSkew must be > 0') unless c['maxSkew'].to_i > 0
err(f, 'minDomains needs DoNotSchedule') if c['minDomains'] && c['whenUnsatisfiable'] == 'ScheduleAnyway'
sel = (c.dig('labelSelector', 'matchLabels') || {}).keys
err(f, 'matchLabelKeys needs a labelSelector') if c['matchLabelKeys'] && c['labelSelector'].nil?
(c['matchLabelKeys'] || []).each { |mk| err(f, "matchLabelKeys key #{mk} also in labelSelector") if sel.include?(mk) }
end
pa = ps.dig('affinity', 'nodeAffinity', 'preferredDuringSchedulingIgnoredDuringExecution') || []
pa += ps.dig('affinity', 'podAntiAffinity', 'preferredDuringSchedulingIgnoredDuringExecution') || []
pa.each { |p| err(f, "affinity weight #{p['weight']} outside 1..100") unless (1..100).cover?(p['weight'].to_i) }
if d['kind'] == 'Pod' && name.start_with?('qos-')
want = name.sub('qos-', '').sub('besteffort', 'BestEffort').sub('burstable', 'Burstable').sub('guaranteed', 'Guaranteed')
got = qos(ps)
err(f, "#{name}: QoS #{got}, name says #{want}") unless got == want
end
end
case d['kind']
when 'Deployment'
sel = spec.dig('selector', 'matchLabels') || {}
lab = d.dig('spec', 'template', 'metadata', 'labels') || {}
err(f, 'selector not a subset of template labels') unless sel.all? { |k, v| lab[k] == v }
when 'HorizontalPodAutoscaler'
err(f, 'minReplicas > maxReplicas') if spec['minReplicas'].to_i > spec['maxReplicas'].to_i
if spec['minReplicas'] == 0
ok = (spec['metrics'] || []).any? { |m| %w[Object External].include?(m['type']) }
err(f, 'minReplicas 0 needs an Object or External metric') unless ok
end
%w[scaleUp scaleDown].each do |dir|
b = spec.dig('behavior', dir) || {}
err(f, "#{dir} stabilizationWindowSeconds > 3600") if b['stabilizationWindowSeconds'].to_i > 3600
(b['policies'] || []).each { |p| err(f, "#{dir} periodSeconds > 1800") if p['periodSeconds'].to_i > 1800 }
end
when 'ScaledObject', 'ScaledJob'
mn = spec['minReplicaCount'] || 0; mx = spec['maxReplicaCount'] || 100
err(f, 'minReplicaCount > maxReplicaCount') if mn > mx
err(f, 'idleReplicaCount must be < minReplicaCount') if spec['idleReplicaCount'] && spec['idleReplicaCount'] >= mn
(spec['triggers'] || []).each do |t|
md = t['metadata'] || {}
err(f, 'cron start == end') if t['type'] == 'cron' && md['start'] == md['end']
err(f, "#{t['type']} trigger: numeric metadata must be quoted strings") if md.values.any? { |v| v.is_a?(Numeric) }
end
when 'PriorityClass'
err(f, "#{name}: value > 1000000000 is reserved") if d['value'].to_i > 1_000_000_000
err(f, "bad preemptionPolicy #{d['preemptionPolicy']}") if d['preemptionPolicy'] && !%w[Never PreemptLowerPriority].include?(d['preemptionPolicy'])
when 'LimitRange'
(spec['limits'] || []).each do |l|
(l['default'] || {}).each { |r, v| err(f, "default #{r} < defaultRequest") if l.dig('defaultRequest', r) && qty(v) < qty(l['defaultRequest'][r]) }
%w[default defaultRequest].each do |k|
(l[k] || {}).each do |r, v|
err(f, "#{k} #{r} below min") if l.dig('min', r) && qty(v) < qty(l['min'][r])
err(f, "#{k} #{r} above max") if l.dig('max', r) && qty(v) > qty(l['max'][r])
end
end
end
when 'NodePool'
dis = spec['disruption'] || {}
err(f, "bad consolidationPolicy #{dis['consolidationPolicy']}") if dis['consolidationPolicy'] && !%w[WhenEmpty WhenEmptyOrUnderutilized Balanced].include?(dis['consolidationPolicy'])
(dis['budgets'] || []).each { |b| err(f, 'budget schedule and duration must be set together') if b.key?('schedule') ^ b.key?('duration') }
err(f, 'weight cannot be set with replicas') if spec['weight'] && spec['replicas']
when 'KubeletConfiguration'
(d['evictionSoft'] || {}).each_key { |k| err(f, "evictionSoft #{k} has no grace period") unless (d['evictionSoftGracePeriod'] || {}).key?(k) }
end
end
# Cross-object rules.
priorities = by.('PriorityClass').map { |_, d| d }
err('PriorityClass', 'more than one globalDefault') if priorities.count { |d| d['globalDefault'] } > 1
known_pc = priorities.map { |d| d.dig('metadata', 'name') } + %w[system-cluster-critical system-node-critical]
docs.each do |f, d|
pcn = pod_spec(d)&.dig('priorityClassName')
err(f, "unknown priorityClassName #{pcn}") if pcn && !known_pc.include?(pcn)
end
hpa_targets = by.('HorizontalPodAutoscaler').map { |_, d| target.(d) }
so_targets = by.('ScaledObject').map { |_, d| target.(d) }
(hpa_targets & so_targets).each { |t| err('autoscaling', "#{t} has both an HPA and a ScaledObject") }
by.('Deployment').each do |f, d|
n = d.dig('metadata', 'name')
err(f, "#{n} is autoscaled but sets spec.replicas") if (hpa_targets + so_targets).include?(n) && d['spec'].key?('replicas')
end
by.('VerticalPodAutoscaler').each do |f, v|
t = target.(v)
h = by.('HorizontalPodAutoscaler').map(&:last).find { |x| target.(x) == t }
next unless h
res = (h.dig('spec', 'metrics') || []).flat_map { |m| [m.dig('resource', 'name'), m.dig('containerResource', 'name')] }.compact
ctl = v.dig('spec', 'resourcePolicy', 'containerPolicies')&.flat_map { |c| c['controlledResources'] || %w[cpu memory] } || %w[cpu memory]
mode = v.dig('spec', 'updatePolicy', 'updateMode') || 'Recreate'
err(f, "VPA #{t} acts on #{res & ctl} that HPA #{t} scales on (updateMode #{mode})") if !(res & ctl).empty? && mode != 'Off'
end
puts "#{files.size} files, #{docs.size} objects"
if $errors.empty? then puts 'manifests ok' else puts $errors; exit 1 endThe Go angle
- GOMAXPROCS. Go 1.25 release notes: "On Linux, the runtime considers the CPU bandwidth limit of the cgroup containing the process, if any. If the CPU bandwidth limit is lower than the number of logical CPUs available, GOMAXPROCS will default to the lower limit", and "The Go runtime does not consider the 'CPU requests' option." It also "periodically updates GOMAXPROCS if the number of logical CPUs available or the cgroup CPU bandwidth limit change", which matters for in-place resize. Both behaviours "are automatically disabled if GOMAXPROCS is set manually via the GOMAXPROCS environment variable or a call to runtime.GOMAXPROCS". The
runtimedoc comment adds the details: the limit is "the cgroup CPU quota / period", the runtime "will never set GOMAXPROCS less than 2 unless the logical CPU count or CPU affinity mask count are below 2", and "If the cgroup CPU throughput limit is not a whole number, the Go runtime rounds up to the next whole number" (solimits.cpu: 500mand1both give 2,2500mgives 3); updates happen "up to once per second". - The
goline decides the defaults. GODEBUG defaults are "amended to match the Go version listed in go.mod". A module that saysgo 1.24, built with Go 1.27, getscontainermaxprocs=0,updatemaxprocs=0in itsDefaultGODEBUG(Lab step 2 shows the build info); thegodebugblock in this module'sgo.modturns both on. Before Go 1.25,go.uber.org/automaxprocs("Automatically setGOMAXPROCSto match Linux container CPU quota") did the same job with a blank import. - No CPU limit, then size by hand. With only a CPU request there is no quota to read and the runtime uses every CPU of the node; the Deployment exposes
requests.cpuasGOMAXPROCSthrough the downward API. Pick one model per service and keep the manifest and the runtime consistent. - GOMEMLIMIT. Go 1.19 added "a soft memory limit" (
GOMEMLIMIT,runtime/debug.SetMemoryLimit). The GC guide: for "a web service into containers with a fixed amount of available memory ... a good rule of thumb is to leave an additional 5-10% of headroom to account for memory sources the Go runtime is unaware of", and "Don't set a memory limit to avoid out-of-memory conditions when a program is already close to its environment's memory limits". The limit is soft: the GC caps itself at "roughly 50%" of CPU, so a too-low limit slows the program instead of stalling it. Exposinglimits.memorythrough the downward API sets 100 % of the limit, with no headroom;runtimecfgsets 90 %. - Graceful scale-down. On SIGTERM (via
signal.NotifyContext),consumer.Runstops fetching at once and gives the in-flight messagedraintime on a context detached withcontext.WithoutCancel; unfinished messages are not acknowledged, so Kafka, RabbitMQ or SQS redeliver them.drainplus shutdown must stay belowterminationGracePeriodSeconds. HTTP draining (readiness off,Server.Shutdown) is in Kubernetes Workloads and OS, Processes & Signals. - Worker pools follow the limits. Size pools of goroutines that do CPU work from
runtime.GOMAXPROCS(0), notruntime.NumCPU(), and in-memory batch sizes from the memory limit; patterns in Worker Pools & Pipelines. The GC and its knobs are in Pointers; profiling the real usage before setting requests is Profiling & Debugging. - client-go. Controllers that read these objects use
k8s.io/api/autoscaling/v2andk8s.io/api/core/v1(ResourceRequirements,resource.Quantity); writing such a controller is Extending Kubernetes.
Laravel
Before
The common starting point: a php-fpm pool sized for a VM, inside a container with a quarter of that memory, and a fixed number of queue workers.
; www.conf copied from a 4 GB VM
pm = dynamic
pm.max_children = 50 ; 50 x ~100 MiB = 5 GiB in a container limited to 512Mi
pm.start_servers = 10
pm.min_spare_servers = 5
pm.max_spare_servers = 15
; no pm.max_requests: slow leaks grow forever# shop-queue fixed at 10 replicas: idle all night, behind on Black Friday
spec:
replicas: 10
template:
spec:
containers:
- name: worker
command: ["php", "artisan", "queue:work"] # --timeout 60 vs a 90 s job: killed and retried
resources: {} # BestEffort: first to be evictedAfter
The pool is computed from the container limit:
; /usr/local/etc/php-fpm.d/zz-pool.conf in the shop-app image.
; Size the pool from the container memory limit, not from the node:
; php-fpm container limits.memory = 1Gi (1024 MiB)
; master + OPcache shared memory ~ 160 MiB (opcache.memory_consumption 128 + master)
; measured RSS per busy worker (p95) ~ 100 MiB
; pm.max_children = floor((1024 - 160) / 100) = 8
; More children than that does not add throughput inside a 1Gi limit: the
; ninth busy worker is what triggers OOMKilled (exit code 137).
[www]
pm = static
pm.max_children = 8
; Recycle workers to cap slow leaks in extensions or libraries.
pm.max_requests = 500
; Expose pool status for the exporter behind the HPA metric (not via Nginx).
pm.status_path = /fpm-status
; A hard stop for a single runaway request, below the Pod's grace period.
request_terminate_timeout = 30s
; For pm = dynamic instead (smaller idle footprint, slower to react):
; pm = dynamic
; pm.max_children = 8
; pm.start_servers = 3
; pm.min_spare_servers = 2
; pm.max_spare_servers = 4Queue workers scale on the Redis list Laravel uses, from one worker (not zero: the comment explains why delayed jobs need a running worker), with a higher floor during business hours:
# shop-queue: `php artisan queue:work redis --queue=default` (workloads chapter).
# Laravel's Redis queue keeps pending jobs in a Redis LIST named
# <REDIS_PREFIX>queues:<queue> e.g. "shop-database-queues:default"
# (REDIS_PREFIX defaults to slug(APP_NAME) + "-database-"). Delayed and
# reserved jobs live in the sorted sets ...:delayed and ...:reserved, which
# the list length below does not count.
# Target: 20 waiting jobs per worker Pod, between 1 and 20 workers.
# Why not zero: due delayed jobs (later(), retry backoff) and expired
# reservations are moved back onto the list only by a worker's pop()
# (RedisQueue::migrate). With zero workers nothing performs that move, the
# list stays empty and those jobs are stranded until some other job arrives.
# Scale to zero only for queues that never use delays, backoff or retry_after
# recovery, or keep one worker (as here) so migration always runs.
apiVersion: keda.sh/v1alpha1
kind: ScaledObject
metadata:
name: shop-queue
namespace: shop
spec:
scaleTargetRef:
name: shop-queue
pollingInterval: 10
minReplicaCount: 1 # keep one worker: it migrates due :delayed / expired :reserved jobs
maxReplicaCount: 20 # also bounded by DB connections: 20 x 1 = 20 (see connection pooling)
advanced:
horizontalPodAutoscalerConfig:
behavior:
scaleDown:
stabilizationWindowSeconds: 180
policies:
- type: Pods
value: 2
periodSeconds: 60
triggers:
- type: redis
metadata:
hostFromEnv: REDIS_HOST # read from the worker container's env (shop-env Secret)
portFromEnv: REDIS_PORT
listName: shop-database-queues:default
listLength: "20"
databaseIndex: "0"
authenticationRef:
name: shop-redis
# Peak hours: keep at least 2 workers warm from 08:00 to 20:00 Tehran time.
- type: cron
metadata:
timezone: Asia/Tehran
start: 0 8 * * *
end: 0 20 * * *
desiredReplicas: "2"
---
apiVersion: keda.sh/v1alpha1
kind: TriggerAuthentication
metadata:
name: shop-redis
namespace: shop
spec:
secretTargetRef:
- parameter: password
name: shop-env # the Secret the app already uses
key: REDIS_PASSWORDTheir requests follow real usage, in place where possible:
# Right-size the queue workers' memory automatically. KEDA's HPA scales
# shop-queue on an *external* metric (Redis list length), so a VPA acting on
# CPU and memory does not fight it. InPlaceOrRecreate resizes running Pods
# where the node allows it and falls back to eviction otherwise; with a
# PodDisruptionBudget the eviction path respects the budget.
apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: shop-queue
namespace: shop
spec:
targetRef:
apiVersion: apps/v1
kind: Deployment
name: shop-queue
updatePolicy:
updateMode: "InPlaceOrRecreate"
resourcePolicy:
containerPolicies:
- containerName: worker
minAllowed:
cpu: 100m
memory: 192Mi
maxAllowed:
cpu: "1"
memory: 1Gi
controlledResources: ["cpu", "memory"]
controlledValues: RequestsAndLimits # keep the request:limit ratio of the Pod specThe web tier scales on busy php-fpm workers and on the php-fpm container's CPU only:
# shop-web (Nginx sidecar + php-fpm in one Pod). php-fpm serves at most
# pm.max_children requests at once per Pod, so "busy workers" is a better
# scaling signal than CPU for I/O-bound PHP; CPU stays as a second metric.
# phpfpm_active_processes comes from a php-fpm exporter through a custom
# metrics adapter. With pm.max_children = 8 (php-fpm-pool.conf), target 6.
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
name: shop-web
namespace: shop
spec:
scaleTargetRef:
apiVersion: apps/v1
kind: Deployment
name: shop-web
minReplicas: 2
maxReplicas: 20
metrics:
- type: Pods
pods:
metric:
name: phpfpm_active_processes
target:
type: AverageValue
averageValue: "6"
- type: ContainerResource # CPU of the php-fpm container only, not the Nginx sidecar
containerResource:
name: cpu
container: php-fpm
target:
type: Utilization
averageUtilization: 75
behavior:
scaleDown:
stabilizationWindowSeconds: 600 # PHP traffic is spiky; shrink slowlyBatch work goes to the spot pool, never preempts and is not consolidated away mid-run:
# A nightly export that must run on the tainted spot pool (karpenter-nodepools.yaml):
# - the toleration lets it onto nodes tainted workload=batch:NoSchedule;
# - the required node affinity keeps it OFF the general pool (a toleration
# alone only permits, it does not attract);
# - shop-batch priority never preempts anyone (preemptionPolicy: Never);
# - karpenter.sh/do-not-disrupt stops voluntary consolidation of its node
# while it runs (spot interruption can still take the node).
apiVersion: batch/v1
kind: Job
metadata:
name: orders-export
namespace: shop
spec:
backoffLimit: 3
activeDeadlineSeconds: 7200
ttlSecondsAfterFinished: 86400
template:
metadata:
annotations:
karpenter.sh/do-not-disrupt: "true"
spec:
restartPolicy: Never
priorityClassName: shop-batch
tolerations:
- key: workload
operator: Equal
value: batch
effect: NoSchedule
affinity:
nodeAffinity:
requiredDuringSchedulingIgnoredDuringExecution:
nodeSelectorTerms:
- matchExpressions:
- key: workload
operator: In
values: ["batch"]
containers:
- name: export
image: ghcr.io/acme/shop-app:1.8.0
command: ["php", "artisan", "orders:export", "--since=yesterday"]
resources:
requests:
cpu: "2"
memory: 2Gi
ephemeral-storage: 10Gi # the CSV is written to emptyDir before upload
limits:
memory: 2Gi
ephemeral-storage: 20Gi
volumeMounts:
- name: scratch
mountPath: /tmp/export
volumes:
- name: scratch
emptyDir:
sizeLimit: 20GiThe Laravel angle
pm.max_childrenis the memory budget. The PHP manual:pm.max_children"sets the limit on the number of simultaneous requests that will be served"; forstaticit is "The number of child processes", fordynamic/ondemandthe maximum. Size it asfloor((limits.memory − master and OPcache) / memory per worker), with memory per worker measured as RSS at p95 under real traffic (ps -o rssin the container, or the exporter).pm.max_requests("useful to work around memory leaks in 3rd party libraries", default 0) recycles workers.- static, dynamic or ondemand. In a container whose memory is reserved anyway,
pm = staticgives predictable memory and no spawn latency;ondemand("idle processes are killed afterpm.process_idle_timeout", default 10s) suits rarely used admin Pods;dynamicsits between. The HPA adds Pods when workers are busy; php-fpm itself never adds more thanpm.max_children. - Laravel's Redis queue keys. Pending jobs are a Redis list
queues:<name>(the framework'sgetQueuereturns'queues:'.$queue), behind the connection prefixREDIS_PREFIX(defaultslug(APP_NAME)+-database-); delayed and reserved jobs are the sorted sets:delayedand:reserved, so a KEDA Redis list trigger measures waiting work only. Due delayed jobs and expired reservations move back to the list only inside a worker'spop()(RedisQueue::migraterunsmigrateExpiredJobson:delayedand, withretry_after, on:reserved), which is whyshop-queuekeepsminReplicaCount: 1. RabbitMQ needs a third-party driver (vladimir-yuldashev/laravel-queue-rabbitmq); KEDA's RabbitMQ scaler then reads the queue length from the broker. - Timeouts chain to the grace period. Laravel: "The
--timeoutvalue should always be at least several seconds shorter than yourretry_afterconfiguration value", and the worker on "SIGQUIT,SIGTERM, orSIGINTwhile processing a job ... will finish its current job before exiting". So two separate relations hold:--timeout<retry_after(Laravel's rule; 90 < 120 in the workloads chapter), andterminationGracePeriodSeconds≥ the job timeout plus a margin for shutdown (90 + 20 = 110 there), so the worker can finish the current job after SIGTERM.retry_afterand the grace period are not related to each other.--memory(default 128 MB) and--max-jobslet the worker exit before the cgroup kills it. - Long jobs and scale-down. A job can react to the stop signal with the
Interruptiblecontract and hand the rest back to the queue, so a KEDA scale-down costs seconds, not the whole job:
<?php
namespace App\Jobs;
use App\Models\Export;
use Illuminate\Contracts\Queue\Interruptible;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
class ExportOrders implements ShouldQueue, Interruptible
{
use Queueable;
public int $timeout = 90; // below retry_after (120); the Pod grace period (110) covers it with margin
protected bool $shouldStop = false;
public function __construct(public Export $export) {}
public function handle(): void
{
foreach ($this->export->pendingChunks() as $chunk) {
if ($this->shouldStop) {
// Scale-down or node drain: save progress and requeue the rest.
$this->export->saveProgress();
$this->release(5);
return;
}
$this->export->writeChunk($chunk);
}
$this->export->markDone();
}
public function interrupted(int $signal): void
{
$this->shouldStop = true;
}
}- Horizon autoscaling vs KEDA. Horizon scales worker processes inside one Pod between
minProcessesandmaxProcesses(balanceauto,autoScalingStrategytime,sizeorlog, "a maximum of one new process will be created or destroyed every three seconds" withbalanceMaxShift1 andbalanceCooldown3). On Kubernetes that hides load from the HPA and makes memory per Pod variable; prefer onequeue:workper container and scale Pods with KEDA, or give a Horizon Pod a fixed process count and size its limit formaxProcesses. Queue scaling as a pattern is Competing Consumers and Laravel's internals are in Laravel Queue Internals. - Database connections. Every php-fpm child and every worker can hold a database connection: 20 web Pods × 8 children + 20 workers = 180 connections. Put PgBouncer or RDS Proxy in front and cap
maxReplicasto what the database can take (Connection Pooling). - Octane. With Octane (Swoole, RoadRunner, FrankenPHP) one Pod holds long-lived workers (
--workers), so CPU per Pod scales with them; set the worker count from the CPU request and the memory limit from workers × RSS, exactly as for php-fpm.
Solving the classic problems
| Problem | Solution | How | Advantage | Cost / limit |
|---|---|---|---|---|
| p99 latency spikes, CPU graphs flat | Remove CPU throttling | Drop the CPU limit or match GOMAXPROCS to it; read cpu.stat | Tail latency back to normal | No hard CPU cap per Pod |
| OOMKilled after deploys or imports | Memory request = limit from measured peak; runtime budget | GOMEMLIMIT 90 %, pm.max_children from the limit, --memory | Predictable memory, no node OOM | Higher requests, higher bill |
| Pods Pending, cluster "half empty" | Right-size requests | VPA Off, p95 usage, then Git | Fewer nodes, faster scheduling | Measurement work; re-check after releases |
| Evicted Pods during node pressure | Stay within requests; reserve for daemons | Memory request = limit, kubeReserved/systemReserved, DaemonSet limits | Eviction becomes rare and predictable | Less overcommit |
| One zone outage takes the service down | Spread and enough replicas | Zone topologySpreadConstraints, minDomains, HPA minReplicas ≥ zones | Survives a zone loss | Cross-zone traffic cost |
| HPA flaps up and down | Behavior tuning | stabilizationWindowSeconds, selectPolicy: Min for scale-down, tolerance | Stable replica count | Slower reaction to real drops |
| Queue backlog at peaks, idle workers at night | Event-driven scaling | KEDA ScaledObject on list length / lag; minReplicaCount: 0 for Kafka-style consumers, 1 for Laravel Redis queues with delayed jobs; cron floor | Pay for work, not for idling | Cold start; metric source must be up (fallback) |
| Scale-up waits minutes for nodes | Headroom and faster provisioning | Overprovisioning pause Pods (priority -10), Karpenter | Pods start in seconds | Paying for the headroom |
| Batch work disturbs the API | Separate pool and priority | Tainted spot NodePool, toleration + affinity, preemptionPolicy: Never | Isolation and cheaper batch | Spot interruptions |
| Scale-down kills in-flight work | Graceful scale-down | SIGTERM handling, drain budget < grace, Interruptible jobs, ScaledJob | No lost or duplicated work | Longer termination |
p99 latency spikes with flat CPU graphs
Look at cpu.stat (Lab step 4) or the container_cpu_cfs_throttled_periods_total metric that cAdvisor exports (general knowledge). If the throttled share is more than a few percent, either drop limits.cpu (keep the request honest, set GOMAXPROCS from the request) or keep the limit and make the process fit inside it: Go 1.25+ with a recent go line or the godebug opt-in, fewer php-fpm children, smaller thread pools. The automaxprocs table is the evidence to show a sceptical team.
OOMKilled after deploys or imports
Find who grew: kubectl describe pod (lastState.terminated.reason), memory.events, then a heap profile. For Go, set GOMEMLIMIT below the limit so the GC works harder before the kernel kills; for PHP-FPM, recompute pm.max_children; for Laravel workers, --memory below the limit and --max-jobs. Then set the request equal to the new limit so the scheduler reserves it.
Pods Pending while the cluster is half empty
The cluster is full of requests. Run VPA in Off mode for a week (or query p95 usage), lower requests that are far above usage, and check the FailedScheduling breakdown: taints and affinity often explain the rest. Binpacking plus consolidation then returns the freed capacity as fewer nodes.
Evictions under node pressure
Reserve memory for the system (kubeReserved, systemReserved), give every DaemonSet requests and limits, set memory requests equal to limits for production Pods, and put BestEffort and over-request workloads on their own nodes. If evictions continue, evictionSoft with a grace period gives Pods a chance to shut down cleanly before the hard threshold.
One zone outage takes the service down
Add a zone spread constraint with whenUnsatisfiable: DoNotSchedule and minDomains equal to the number of zones, keep minReplicas at least that number, add a PDB with maxUnavailable: 1, and check that the node autoscaler can create nodes in every zone (a node group per zone for Cluster Autoscaler; zone requirements in a Karpenter NodePool).
HPA flapping
Keep the default 300 s scale-down window or longer, scale down with selectPolicy: Min and small policies, and make sure the metric is per-Pod average, not a total that jumps when Pods come and go. For CPU, start-up spikes are what --horizontal-pod-autoscaler-cpu-initialization-period and readiness exist for; a startup probe keeps new Pods unready while they warm up.
Queue backlog at peaks
Scale workers on the queue, not on CPU: KEDA's Redis, RabbitMQ, Kafka or SQS scalers, a target per replica derived from job duration (a worker that handles 2 jobs per second with a 10 s target lag needs one replica per 20 waiting jobs), maxReplicaCount bounded by partitions and database connections, a cron trigger for predictable peaks, and fallback replicas for when the broker metrics are unreachable.
Scale-up waits for nodes
Node start-up takes minutes (instance boot, kubelet registration, image pull). Overprovision with low-priority pause Pods so real Pods preempt them instantly, pre-pull large images with a DaemonSet, keep images small (Images & Dockerfiles), and prefer Karpenter's direct instance selection over node groups when instance variety matters.
Batch work disturbs the API
Taint a batch pool, give batch Pods the toleration and a required node affinity for it, lower their priority with preemptionPolicy: Never, and use ResourceQuota per namespace so a burst of Jobs cannot eat the cluster. Spot capacity suits this pool; long jobs carry karpenter.sh/do-not-disrupt: "true" or checkpoint.
Scale-down kills in-flight work
Make SIGTERM mean "finish and leave": the Go consumer package, Laravel's worker signal handling and Interruptible jobs; set terminationGracePeriodSeconds above the longest job you let finish; use ScaledJob for work longer than a few minutes; and lower controller.kubernetes.io/pod-deletion-cost on Pods that are idle if your worker can report it.
Choosing
Which requests and limits
| Workload | CPU request | CPU limit | Memory request / limit | QoS | Reason |
|---|---|---|---|---|---|
| Latency-sensitive Go/PHP API | p95 usage | None (or = request if the team needs Guaranteed) | p99 peak + headroom, equal | Burstable | No throttling; memory predictable |
| Database, Redis, Kafka broker | Integer cores | = request | Equal | Guaranteed | Evicted last; static CPU manager possible |
| Queue workers | Per-worker average | None or 2-4x | Equal | Burstable | Scale on queue length, not CPU |
| Batch / CI | Average | Optional | Limit ≥ request | Burstable | Cheap capacity on a tainted pool |
| Sidecars (Nginx, log agents) | Small, measured | Small | Equal | Keeps the Pod's class | Without Pod-level resources, a resource-less sidecar downgrades the Pod |
| Dev namespaces | LimitRange defaults | LimitRange default | Defaults, limit > request | Burstable | Overcommit is fine there |
Which placement rule
| Need | Use | Not |
|---|---|---|
| Replicas across zones | topologySpreadConstraints (zone, DoNotSchedule) | Required pod anti-affinity |
| One replica per node, small set | Required pod anti-affinity (hostname) | Spread with maxSkew 0 (invalid) |
| Dedicated nodes (GPU, batch, tenant) | Taint + toleration + node affinity | Toleration alone |
| Prefer cheaper nodes | Preferred node affinity with weight | nodeSelector (hard) |
| Keep near a dependency | Preferred pod affinity (zone) | Required pod affinity across a big cluster |
| Critical over batch | PriorityClass, batch with preemptionPolicy: Never | Overprovisioning the whole cluster |
Which autoscaler
| Situation | Pod level | Node level | Why |
|---|---|---|---|
| Stateless HTTP API | HPA on CPU + requests per second | Cluster Autoscaler or Karpenter | Load shows in CPU and request rate |
| Queue or stream consumers | KEDA (list length, lag); scale to zero for Kafka-style consumers, floor of 1 for Laravel Redis queues | Karpenter (spot for batch) | Work waiting is the signal |
| Long, uneven jobs | KEDA ScaledJob | Karpenter, spot pool | No killing of busy replicas |
| Hard-to-scale-out service (single writer) | VPA (InPlaceOrRecreate) | Fixed or autoscaled pool | Only vertical growth helps |
| Unknown sizing | VPA Off first | Any | Measure before automating |
| Predictable daily peaks | KEDA cron trigger or HPA + scheduled minReplicas change | Overprovisioning before the peak | Start before the load arrives |
| Many instance types / spot | Any | Karpenter | Instance flexibility and consolidation |
| Many clouds, Cluster API | Any | Cluster Autoscaler | Broad provider support |
Which scoring strategy
| Goal | Strategy | Notes |
|---|---|---|
| Resilience, even load (default) | LeastAllocated spreading | Leaves room on every node |
| Cost, removable nodes | MostAllocated binpacking profile | Pair with consolidation and PDBs |
| Custom curves | RequestedToCapacityRatio | Shape per resource |
In architecture: from a single process to a distributed system
Requests and limits are the contract between an application and the platform: the application promises to fit, the platform promises a place and a share. Each step below adds a layer of automation on top of the same two numbers.
Monolith: one Deployment on a small cluster
A Laravel monolith (shop-web with an Nginx sidecar and php-fpm, shop-queue, a scheduler) on a three-node managed cluster. The simplest correct setup: requests and limits on every container including the sidecar, pm.max_children computed from the php-fpm limit, memory request = limit, a LimitRange so nothing is BestEffort, a zone or node spread for shop-web, a PDB, and an HPA with minReplicas: 2. The node count can stay fixed at this size; the first autoscaler worth adding is KEDA for the queue, because queue load is the spikiest.
Modular monolith: several workloads, one namespace budget
The same codebase now runs web, three queue types (emails, exports, webhooks) and a Go PDF renderer. Each queue gets its own worker Deployment and ScaledObject (different job durations mean different targets), exports move to a ScaledJob on a tainted batch pool, and a ResourceQuota on the namespace makes the sum visible: if the quota says 40 CPU, the HPA and KEDA maxima together must fit inside it. PriorityClasses decide who waits when the quota or the cluster is full: web over webhooks over exports.
Microservices: many teams, one cluster
Twenty services, each with its own namespace, LimitRange, ResourceQuota and PriorityClass access. The platform team owns the node layer (Karpenter NodePools, kubelet reservations, scheduler profiles) through Terraform and Argo CD; teams own requests, HPAs and ScaledObjects in their Helm values. A request flow under a sale:
1 checkout traffic x4: orders-api HPA (CPU + rps) 6 -> 14 replicas; 5 Pending
2 overprovisioning pause Pods preempted at once: 4 of 5 Pending Pods start in seconds
3 Karpenter sees the pause Pods + 1 api Pod Pending: launches 2 on-demand nodes (api requires on-demand)
4 orders-events topic lag grows: KEDA scales orders-projector 2 -> 12 (12 partitions, no idle consumers)
5 exports queue grows: ScaledJob starts Jobs on the spot batch pool; shop-batch priority never preempts
6 sale ends: HPA windows hold for 5 min, then step down; Karpenter consolidates within budgets and PDBsCost reporting per team uses requests (OpenCost or the cloud's allocation), so right-sizing becomes each team's own lever; a policy engine (Kyverno or OPA Gatekeeper) rejects Deployments without requests or with HPA-managed replicas in Git, and the same rules run earlier as a CI step (GitHub Actions or GitLab CI) that renders the Helm chart and runs an offline checker like check-manifests.rb before Argo CD syncs. The architectural reasoning about elasticity is in Scaling Strategies.
Distributed data: stateful workloads, zones and regions
Databases and brokers on Kubernetes (operators, StatefulSets) want the opposite of stateless services: Guaranteed QoS with integer CPUs, required anti-affinity per node, zone spread matched to the replication topology, volumes whose node affinity pins Pods to a zone, a high PriorityClass, PDBs that allow one member down, and no aggressive consolidation (karpenter.sh/do-not-disrupt or a dedicated NodePool with WhenEmpty). Autoscaling is mostly vertical (VPA recommendations, in-place resize where the engine can use more memory without restart) and capacity-planned (Capacity Planning & Disaster Recovery). Across regions, each cluster autoscales on its own; the global layer is DNS and load balancing (Load Balancing), and failover capacity is either pre-provisioned (overprovisioning, higher minReplicas) or accepted as a scale-up delay in the recovery-time objective.
Scaling path: 1x, 10x, 100x
| Scale | Pods | Nodes | Governance |
|---|---|---|---|
| 1x (one team, a few services) | Requests on everything, HPA on CPU, KEDA for queues | Fixed node group or Cluster Autoscaler | LimitRange defaults, one PDB per service |
| 10x (several teams) | HPA on app metrics, VPA Off reports, ScaledJobs for batch | Karpenter with general + batch NodePools, spot for batch | ResourceQuota per namespace, PriorityClasses, cost by requests |
| 100x (many clusters) | Standard Helm library chart with sizing presets, in-place resize automation | Binpacking profiles, consolidation budgets, overprovisioning per zone | Policy engine for resource rules, scheduled right-sizing reviews, capacity planning per region |
Lab
Label: every kubectl, helm and in-cluster command below is expected, not run: there is no Kubernetes in this build environment (AUTHORING cost rule), and kubectl was not invoked, not even client-side. Their outputs are either copied from the Kubernetes docs (marked) or shapes with placeholders, never invented numbers. Steps marked ran on the host were executed on macOS (Go 1.27.4, darwin/arm64) and show real output, saved in pipeline/sources/kubernetes-resources-scheduling-autoscaling/lab-host-output.txt.
1. Test the rules without a cluster (ran on the host)
cd docs/snippets/platform/kubernetes-resources-scheduling-autoscaling/go
gofmt -l . ; go vet ./... ; go test -race -count=1 ./...
# ok academy/kubernetes-resources-scheduling-autoscaling/cgroup 1.253s
# ok academy/kubernetes-resources-scheduling-autoscaling/consumer 1.434s
# ok academy/kubernetes-resources-scheduling-autoscaling/hpa 1.254s
# ok academy/kubernetes-resources-scheduling-autoscaling/qos 1.252s
# ok academy/kubernetes-resources-scheduling-autoscaling/runtimecfg 1.256s
cd ../manifests && ruby check-manifests.rb ../../../../../pipeline/sources/kubernetes-resources-scheduling-autoscaling $(find . -name '*.yaml' | sort)
# 17 files, 27 objects
# manifests ok
cd ../go # step 2 runs in go/2. What the go line does to GOMAXPROCS (ran on the host)
go build -o limits ./cmd/limits && ./limits
# NumCPU=12 GOMAXPROCS=12 cpu.max=0.00 CPUs (0 = no limit)
# memory.max=0 (-1 = max, 0 = not found) GOMEMLIMIT=9223372036854775807 source=none
GOMEMLIMIT=400MiB ./limits
# memory.max=0 (-1 = max, 0 = not found) GOMEMLIMIT=419430400 source=env
go version -m limits | grep DefaultGODEBUG
# go 1.24 + godebug block: DefaultGODEBUG=containermaxprocs=1,...,updatemaxprocs=1,...
# go 1.24 without it: DefaultGODEBUG=containermaxprocs=0,...,updatemaxprocs=0,...
# go 1.25 without it: (neither setting listed: the Go 1.25+ defaults apply, both on)
cd .. # steps 3-7 run from the chapter snippet root (manifests/ is a subdirectory)On macOS there is no cgroup, so the binary reports "none"; inside a Pod with limits.cpu: "2" and limits.memory: 512Mi the expected output is GOMAXPROCS=2 cpu.max=2.00 and GOMEMLIMIT=483183820 source=cgroup (90 % of 536870912).
3. Requests, QoS and the capacity check (expected, not run)
kubectl create namespace shop && kubectl create namespace sandbox
kubectl apply -f manifests/namespace/ -f manifests/priority/ -f manifests/qos/
kubectl get pods -n shop -o custom-columns=NAME:.metadata.name,QOS:.status.qosClass
# NAME QOS
# qos-guaranteed Guaranteed
# qos-burstable Burstable
kubectl get pod qos-besteffort -n sandbox -o jsonpath='{.status.qosClass}' # BestEffort
kubectl describe quota -n shop # Used vs Hard for requests.cpu, limits.memory, pods ...
kubectl describe nodes | grep -A6 "Allocated resources" # requests and limits as % of allocatable4. See CPU throttling from inside a container (expected, not run)
kubectl run burn -n sandbox --image=busybox:1.37 --restart=Never \
--overrides='{"spec":{"containers":[{"name":"burn","image":"busybox:1.37","command":["sh","-c","for i in 1 2 3 4; do (while :; do :; done) & done; sleep 60"],"resources":{"limits":{"cpu":"500m","memory":"64Mi"}}}]}}'
kubectl exec -n sandbox burn -- cat /sys/fs/cgroup/cpu.max # 50000 100000
kubectl exec -n sandbox burn -- cat /sys/fs/cgroup/cpu.stat # nr_periods N, nr_throttled close to N
kubectl top pod -n sandbox burn # ~500m: capped, four busy loops5. OOMKilled and exit code 137 (expected, not run; describe output shape from the docs)
kubectl apply -n sandbox -f - <<'EOF'
apiVersion: v1
kind: Pod
metadata: {name: memhog}
spec:
containers:
- name: hog
image: python:3.13-slim
command: ["python", "-c", "b = bytearray(200 * 1024 * 1024); import time; time.sleep(600)"]
resources: {requests: {memory: 64Mi}, limits: {memory: 128Mi}}
EOF
kubectl describe pod -n sandbox memhog | grep -A4 "Last State"
# Last State: Terminated
# Reason: OOMKilled
# Exit Code: 1376. HPA and KEDA behaviour (expected, not run)
kubectl apply -f manifests/go-service/deployment.yaml -f manifests/go-service/hpa.yaml
kubectl get hpa orders-api -n shop --watch
# NAME REFERENCE TARGETS MINPODS MAXPODS REPLICAS
# orders-api Deployment/orders-api cpu: <x>%/70%, <y>/150 3 30 <n>
kubectl describe hpa orders-api -n shop # Conditions: AbleToScale, ScalingActive, ScalingLimited
helm repo add kedacore https://kedacore.github.io/charts && helm install keda kedacore/keda -n keda --create-namespace
# prerequisites for the queue part: a Redis, the app Secret, the worker Deployment (from the workloads chapter)
kubectl run redis -n shop --image=redis:7.4 --port 6379 -- redis-server --requirepass demo
kubectl expose pod redis -n shop --port 6379
kubectl create secret generic shop-env -n shop \
--from-literal=REDIS_HOST=redis.shop.svc.cluster.local --from-literal=REDIS_PORT=6379 \
--from-literal=REDIS_PASSWORD=demo --from-literal=APP_KEY=base64:<generated> --from-literal=APP_NAME=shop
kubectl apply -n shop -f ../kubernetes-workloads/manifests/laravel/queue-worker-deployment.yaml
kubectl apply -f manifests/laravel/queue-scaledobject.yaml
kubectl get scaledobject,hpa -n shop # KEDA's HPA is named keda-hpa-shop-queue; MINPODS 1
# 200 entries on the list Laravel reads (from inside the Redis Pod, so host/port/password are right)
kubectl exec -n shop redis -- sh -c 'for i in $(seq 1 200); do redis-cli -a demo --no-auth-warning LPUSH shop-database-queues:default "{\"job\":\"demo\"}" >/dev/null; done'
kubectl get deploy shop-queue -n shop --watch # 1 -> up to ceil(200/20) = 10 while the list is long, back to 1 after it drains
# (the demo payloads are not real Laravel jobs: the workers fail them, which is enough to watch the scaling)7. A FailedScheduling event and the node autoscaler's answer (expected, not run)
kubectl run toobig -n sandbox --image=busybox:1.37 --restart=Never --overrides='{"spec":{"containers":[{"name":"t","image":"busybox:1.37","command":["sleep","3600"],"resources":{"requests":{"cpu":"64"}}}]}}'
kubectl get events -n sandbox --field-selector reason=FailedScheduling
# Warning FailedScheduling pod/toobig 0/<n> nodes are available: <n> Insufficient cpu. ...
kubectl get events -n sandbox --field-selector reason=NotTriggerScaleUp # Cluster Autoscaler
# Normal NotTriggerScaleUp pod didn't trigger scale-up (it wouldn't fit if a new node is added)Common misconceptions
| Belief | Reality |
|---|---|
| The scheduler looks at real CPU and memory usage | It compares requests with allocatable; usage is ignored for placement |
| A CPU limit protects my latency | It can only throttle the container that has it; the request protects your share |
| Exceeding the CPU limit kills the container | CPU is throttled, never killed; only memory and ephemeral storage lead to kills or evictions |
memory: 500m means 500 MB | m is milli: 0.5 bytes; use Mi or M |
| The kubelet evicts by QoS class | It ranks by usage over requests, then priority, then usage relative to requests; QoS only predicts it |
| Guaranteed Pods are never evicted | They go last, and only when system daemons overrun their reservation or for disk/PID pressure |
| A toleration attracts Pods to tainted nodes | It only permits; add node affinity to attract |
A NoSchedule taint removes running Pods | Only NoExecute evicts |
| Spread constraints keep Pods balanced forever | They are checked at scheduling; scale-down can unbalance; the descheduler rebalances |
| HPA 70 % means 70 % of the node or of the limit | 70 % of the container's CPU request, averaged over Pods |
| A PDB slows down HPA scale-down | HPA scale-down deletes Pods; PDBs only govern evictions (drains, consolidation, VPA) |
| VPA and HPA on CPU work well together | Not on the same metric; use VPA Off or HPA on custom/external metrics |
| Scale to zero always needs KEDA | Since v1.37 the native HPA can (beta, on by default) with Object or External metrics; KEDA still adds scalers, activation and ScaledJobs |
| The cluster autoscaler reacts to high CPU | It reacts to Pending Pods (and removes nodes by requests below 50 %) |
| Go reads its memory limit from the container | It does not; set GOMEMLIMIT (Go 1.25 reads the CPU limit, not the request) |
| More php-fpm children means more throughput | Inside a memory limit, children beyond the budget only cause OOM kills |
| A LimitRange fixes existing Pods | Admission only; running Pods keep their values |
Cheat sheet
| Topic | Remember |
|---|---|
| Requests | Reservation: scheduling, CPU weight, eviction rank, HPA denominator, the bill |
| Limits | Ceiling: CPU throttled (cpu.max per 100 ms), memory killed (memory.max, OOMKilled, 137) |
| Units | 250m CPU = 0.25 core; memory Mi/Gi, never m |
| Default policy | Memory request = limit; CPU request honest, limit off unless you need Guaranteed or caps |
| QoS | Guaranteed: all requests = limits; BestEffort: nothing set; else Burstable; sidecars count |
| Eviction | Hard defaults memory.available<100Mi, nodefs<10%, imagefs<15%; usage over requests goes first |
| Throttling | cpu.stat nr_throttled / nr_periods; match GOMAXPROCS to the limit or drop the limit |
| Namespaces | LimitRange = defaults and bounds; ResourceQuota = totals; both admission-time, 403 on violation |
| Scheduler | Filter (requests, affinity, taints, spread) then Score (LeastAllocated default, MostAllocated = binpacking) |
| Placement | Spread for even distribution, anti-affinity for small sets, taint + toleration + affinity for pools |
| Taints | NoSchedule (new Pods), PreferNoSchedule (soft), NoExecute (evicts; tolerationSeconds, default 300 s for not-ready/unreachable) |
| Priority | PriorityClass up to 1e9; preemption via PostFilter; preemptionPolicy: Never for batch |
| HPA | ceil(current × metric / target), tolerance 0.1, scale-down window 300 s, every 15 s; no replicas in Git |
| VPA | Recommender, Updater, Admission; default Recreate; Off first; in-place resize stable 1.35 |
| KEDA | ScaledObject drives an HPA; activation 0 ↔ 1; pollingInterval 30, cooldownPeriod 300; ScaledJob for long work |
| Nodes | Cluster Autoscaler: node groups, scan 10 s, unneeded 10 min; Karpenter: NodePools, consolidation, budgets |
| Go | Go 1.25+ GOMAXPROCS from cpu.max (check the go line); GOMEMLIMIT ≈ 90 % of the limit; drain on SIGTERM |
| Laravel | pm.max_children = memory budget / RSS per worker; KEDA on queues:<name> with a floor of 1; --timeout < retry_after; grace ≥ timeout + margin |
Self-check: questions & answers
- Must-know asked in almost every interview
- Important frequent; expected at senior level
- Good to know extra depth that sets you apart
1 — A node shows 15 % CPU usage, yet a new Pod requesting 1 CPU stays Pending with Insufficient cpu. Explain and give two fixes. Must-know
Answer
Answer: The scheduler compares the sum of requests with the node's allocatable capacity, not live usage; the node's requests are full even though the containers use little. Fix it by right-sizing the requests that are far above usage (VPA in Off mode or p95 metrics), or by adding capacity (a node autoscaler acts on exactly this Pending Pod). See The scheduler and Cost.
2 — What is the difference between hitting the CPU limit and hitting the memory limit? Must-know
Answer
Answer: CPU is compressible: at the CPU limit the kernel's CFS bandwidth control throttles the container until the next 100 ms period (cpu.max), and cpu.stat counts nr_throttled; nothing is killed. Memory is not: past memory.max, when the kernel cannot reclaim, the OOM killer kills a process in the container, which shows OOMKilled with exit code 137 and is restarted per restartPolicy. See CPU and Memory.
3 — Which QoS class does a Pod get if its app container has requests equal to limits but its sidecar has no resources, and why does it matter? Must-know
Answer
Answer: Burstable, if the Pod has no Pod-level resources: Guaranteed then requires every container to have CPU and memory limits equal to requests. (With a Pod-level spec.resources budget whose CPU and memory requests equal its limits, the Pod is Guaranteed and the sidecar shares the budget.) It matters because Burstable Pods whose usage exceeds requests are evicted before Guaranteed ones under node pressure, get a higher oom_score_adj, and cannot use the static CPU manager. Give the sidecar small requests equal to limits. See QoS classes.
4 — Your HPA targets 70 % CPU but never scales. The Pods are busy. What do you check? Must-know
Answer
Answer: Utilisation is a percentage of the CPU request; if any container in the Pod (often a sidecar) has no CPU request, CPU utilisation is undefined and the HPA takes no action for that metric. Also check that metrics-server serves metrics.k8s.io (ScalingActive condition) and that maxReplicas or a ResourceQuota is not the cap. Fix with requests on every container or a ContainerResource metric. See HPA.
5 — Why do many teams run without CPU limits but with memory limit equal to request? Important
Answer
Answer: Under contention the kernel shares CPU by request weight, so a container without a limit still gets its share and can use idle CPU without throttling; GKE's guide says "Set an unbounded CPU limit". Memory is incompressible, so overcommitting it risks node OOM and early eviction; equal request and limit makes OOM a container's own problem. The cost: no per-Pod CPU cap and GOMAXPROCS must be sized from the request. See The limits debate.
6 — A Go service with limits.cpu: "1" on 32-core nodes has bad p99 latency under load. What is happening and what changes in Go 1.25? Important
Answer
Answer: Before Go 1.25, GOMAXPROCS defaults to the node's 32 CPUs, so up to 32 threads burn the 100 ms quota in a few milliseconds and then all wait: CFS throttling. Go 1.25 defaults GOMAXPROCS to the cgroup CPU limit rounded up (never below 2, so 2 here) and updates it, but only when the module's go line is 1.25+ (or godebug containermaxprocs=1) and GOMAXPROCS is not set in the environment. Alternatives: automaxprocs, or drop the CPU limit. See The Go angle.
7 — How do you dedicate a spot node pool to batch jobs so nothing else lands there and the jobs land nowhere else? Important
Answer
Answer: Taint the pool (workload=batch:NoSchedule) so only Pods with a matching toleration are allowed; give the batch Pods that toleration and a required node affinity for the pool's label, because a toleration permits but does not attract. Add a low PriorityClass with preemptionPolicy: Never, and with Karpenter define it as its own NodePool with karpenter.sh/capacity-type: spot. See Taints.
8 — What does maxSkew: 1 with whenUnsatisfiable: DoNotSchedule on topology.kubernetes.io/zone guarantee, and what does it not? Important
Answer
Answer: At scheduling time, a new matching Pod may only go to a zone where the count difference to the least-loaded eligible zone stays at most 1; if no such node exists the Pod is Pending. It does not rebalance after scale-down or failures ("no guarantee that the constraints remain satisfied when Pods are removed"), and zones with no nodes are unknown unless minDomains says how many to expect. See Topology spread.
9 — Why should a VPA not run in Recreate mode on a Deployment whose HPA scales on CPU? Important
Answer
Answer: Both would act on the same signal: the VPA raises CPU requests, which lowers utilisation (usage divided by request), so the HPA removes replicas, which raises usage per Pod, and so on. The VPA docs say it "should not be used with the Horizontal Pod Autoscaler (HPA) on the same resource metric (CPU or memory)". Use VPA Off for recommendations, or scale the HPA on custom/external metrics. See VPA.
10 — How does KEDA scale a Laravel Redis queue worker, and why is scaling it to zero risky? Must-know
Answer
Answer: The keda-operator polls the trigger (LLEN of <prefix>queues:default) every pollingInterval, and the HPA it created scales 1 → N on the external metric (list length / listLength); with minReplicaCount: 0 the operator itself handles 0 ↔ 1 by the activation value and cooldownPeriod. Delayed jobs (later(), retry backoff) and expired reservations live in the :delayed and :reserved sorted sets and are moved back onto the list only by a worker's pop(), so with zero workers they are stranded while the list looks empty. Keep minReplicaCount: 1 for such queues; running jobs are not "load" either, so the grace period must cover them. See KEDA.
11 — Cluster Autoscaler or Karpenter: how do they decide to add and remove nodes? Good to know
Answer
Answer: Both add nodes for unschedulable Pods, not for CPU usage. Cluster Autoscaler scans every 10 s, simulates template nodes of predefined node groups and picks a group with an expander (least-waste by default); it removes a node whose requests are below 50 % of allocatable and whose Pods can move, after 10 minutes. Karpenter chooses an instance type per batch of Pending Pods from NodePool requirements and removes or replaces nodes through consolidation, within disruption budgets and PDBs. See Cluster Autoscaler vs Karpenter.
12 — How do you size pm.max_children for a php-fpm container with a 1Gi memory limit? Must-know
Answer
Answer: Measure the RSS of a busy worker at p95 (say 100 MiB) and the fixed cost of the master and OPcache shared memory (say 160 MiB), then floor((1024 − 160) / 100) = 8. pm.max_children "sets the limit on the number of simultaneous requests that will be served", so more children only add OOM kills, not throughput; scale throughput with more Pods (HPA on busy workers). See The Laravel angle.
13 — Does a PodDisruptionBudget protect against HPA scale-down, node drains and preemption? Good to know
Answer
Answer: Drains and node-autoscaler consolidation use the eviction API, which respects PDBs (a blocked eviction gets 429). HPA scale-down deletes Pods through the ReplicaSet and bypasses PDBs; preemption respects them only best-effort; node-pressure eviction ignores them. Graceful SIGTERM handling is what protects work in every case. See PDB interplay.
Glossary
| Term | Meaning |
|---|---|
| Resource requests | Per-container amounts the scheduler reserves; CPU share under contention; quota and HPA base |
| Resource limits | Per-container ceilings enforced by the kernel (CPU throttling, memory OOM kill) |
| CPU millicores | 1000m = 1 CPU (core or vCPU); 250m = a quarter core; minimum precision 1m |
| CFS quota | Linux CFS bandwidth control: $MAX µs of CPU per $PERIOD (default 100 ms), cpu.max |
| CPU throttling | Threads of a cgroup wait for the next period after using the quota |
| cpu.stat nr_throttled | Count of periods in which the cgroup hit its quota (with nr_periods, throttled_usec) |
cpu.weight | cgroup v2 proportional CPU share, set from the CPU request |
| Memory limit | memory.max of the container cgroup; exceeding it invokes the OOM killer |
| OOMKilled | Container termination reason when the kernel OOM killer killed it |
| Exit code 137 | 128 + 9 (SIGKILL): the usual exit code of an OOM-killed container |
| ephemeral-storage | Node-local disk used by writable layers, logs and emptyDir; requestable and limitable |
| QoS class | Guaranteed, Burstable or BestEffort, computed from requests and limits |
| Guaranteed | Every container has CPU and memory limits equal to requests, or the Pod-level budget does |
| Burstable | Some requests or limits, not Guaranteed |
| BestEffort | No CPU or memory requests or limits at all (container or Pod level) |
| Eviction | Termination of a whole Pod by the kubelet (node pressure) or through the Eviction API |
| Node pressure | MemoryPressure, DiskPressure or PIDPressure condition from eviction signals |
| Eviction signal / threshold | Measured value (memory.available ...) and the level that triggers eviction |
oom_score_adj | Per-process kernel OOM bias the kubelet sets from QoS (-997 to 1000) |
| Allocatable | Node capacity minus reservations and the hard eviction threshold; what Pods may request |
| LimitRange | Namespace object with per-container defaults, min, max and ratio, applied at admission |
| Default requests | defaultRequest values a LimitRange injects into containers that set none |
| ResourceQuota | Namespace totals for requests, limits, object counts and storage |
| Quota scope | Filter on what a quota counts (BestEffort, NotBestEffort, PriorityClass, Terminating ...) |
| Scheduler (kube-scheduler) | Control-plane component that assigns Pods to nodes |
| Filtering | Removing infeasible nodes (formerly "predicates") |
| Scoring | Ranking feasible nodes (formerly "priorities") |
| Scheduling framework | Plugin architecture with extension points from QueueSort to PostBind (stable 1.19) |
| Binpacking | Scoring for fuller nodes (MostAllocated) so others empty out |
| Spreading | Scoring for emptier nodes (LeastAllocated, the default) |
| nodeSelector | Hard match on node labels |
| Node affinity | Expressive node-label rules, hard or soft with weights |
| requiredDuringScheduling | requiredDuringSchedulingIgnoredDuringExecution: hard rule at scheduling time |
| preferredDuringScheduling | preferredDuringSchedulingIgnoredDuringExecution: soft rule with weight 1-100 |
| Pod affinity | Schedule near Pods matching a selector within a topology domain |
| Pod anti-affinity | Schedule away from Pods matching a selector |
| topologySpreadConstraints | Rules that bound the replica count difference across topology domains |
| maxSkew | Maximum allowed difference between a domain's matching Pods and the global minimum |
minDomains | Minimum number of eligible domains the spread constraint expects |
| Taints | Node marks key=value:effect that repel Pods |
| Tolerations | Pod fields that allow scheduling onto (or staying on) tainted nodes |
| NoSchedule | Taint effect: new Pods without toleration are not scheduled |
| PreferNoSchedule | Soft taint effect: the scheduler tries to avoid the node |
| NoExecute | Taint effect: running Pods without toleration are evicted |
| tolerationSeconds | How long a Pod tolerating a NoExecute taint stays bound |
| node.kubernetes.io taints | Built-in taints such as not-ready, unreachable, memory-pressure, disk-pressure, unschedulable |
| PriorityClass | Cluster object mapping a name to a scheduling priority value |
| Preemption | Evicting lower-priority Pods so a higher-priority Pod fits |
preemptionPolicy | PreemptLowerPriority (default) or Never |
| Pod overhead | Extra resources from the RuntimeClass, added to the Pod's requests |
| Pod-level resources | spec.resources budget for a whole Pod (beta 1.34) |
| Dynamic Resource Allocation | Device requests with ResourceClaims and DeviceClasses (stable 1.34) |
| Pending pods | Phase before all containers are created: unscheduled Pods (no node passed filtering) and scheduled Pods still pulling images |
| FailedScheduling events | Scheduler events listing why each group of nodes was rejected |
| Descheduler | Add-on that evicts Pods so they can be rescheduled better |
| HorizontalPodAutoscaler | Controller and API that set replica counts from metrics |
| autoscaling/v2 | The HPA API version with multiple metric types and behavior (stable 1.23) |
| metrics-server | Cluster add-on serving metrics.k8s.io CPU/memory, collected every 15 s |
| Resource metrics | CPU and memory per Pod/container from metrics.k8s.io |
| Custom metrics | Per-object metrics from custom.metrics.k8s.io (adapters) |
| External metrics | Metrics not tied to Kubernetes objects from external.metrics.k8s.io |
| Target utilization | HPA target as a percentage of the request |
| stabilizationWindowSeconds | Window over which the HPA keeps the highest (down) recommendation |
| scaleUp scaleDown behavior | Per-direction HPA policies, windows, selectPolicy and tolerance |
| minReplicas maxReplicas | HPA bounds on the replica count |
| Scale to zero | Running zero replicas while idle (KEDA, or native HPA beta in 1.37 with Object/External metrics) |
| KEDA | Kubernetes Event-driven Autoscaling, a CNCF project driving HPAs from event sources |
| ScaledObject | KEDA object scaling a Deployment or other /scale target |
| ScaledJob | KEDA object creating Jobs per batch of events |
| Triggers | KEDA scaler definitions in a ScaledObject or ScaledJob |
| Activation | KEDA threshold for the 0 ↔ 1 decision, separate from the scaling target |
| Kafka lag scaler | KEDA kafka trigger on consumer group lag, capped at partitions by default |
| RabbitMQ scaler | KEDA rabbitmq trigger on queue length or message rate |
| Prometheus scaler | KEDA prometheus trigger on a PromQL query |
| Cron scaler | KEDA cron trigger with start, end and desired replicas |
| TriggerAuthentication | KEDA object that maps Secrets to scaler parameters |
| VerticalPodAutoscaler | CRD and controllers that recommend or apply requests |
| Updater Recommender Admission | The three VPA components: apply, compute, inject |
| In-place pod resize | Changing a running container's CPU/memory via the /resize subresource (stable 1.35) |
resizePolicy | Per-resource NotRequired or RestartContainer for in-place resize |
| Cluster Autoscaler | Node autoscaler that resizes node groups for Pending Pods |
| Expander | Cluster Autoscaler strategy for choosing a node group |
| Karpenter | Node autoscaler that launches fitting instances from NodePools |
| NodePool | Karpenter object with node requirements, taints, limits and disruption settings |
| NodeClaim | Karpenter's request for one node |
| Consolidation | Karpenter removal or replacement of empty or underused nodes |
| Disruption budget (Karpenter) | Limit on nodes Karpenter may disrupt at once, optionally scheduled |
| Spot nodes | Discounted, reclaimable cloud capacity |
| Overprovisioning | Low-priority placeholder Pods that keep headroom for fast scale-up |
| Right-sizing | Setting requests to measured usage |
| Requests drive cost | Node autoscaling buys capacity for requests, so requests set the bill |
| GOMAXPROCS | Number of OS threads running Go code at once |
| GOMEMLIMIT | Go soft memory limit (Go 1.19+) |
containermaxprocs / updatemaxprocs | GODEBUG settings (Go 1.25) for cgroup-aware and updating GOMAXPROCS |
| php-fpm pm.max_children | Maximum php-fpm worker processes, the pool's concurrency and memory ceiling |
| Memory per worker | RSS of one busy php-fpm or queue worker process, the sizing unit |
| Queue worker autoscaling | Scaling queue:work Pods on queue length or lag |
| PodDisruptionBudget interplay | Which disruptions honour PDBs (evictions) and which do not (deletes, node pressure) |
| Graceful scale-down | Draining work on SIGTERM within the grace period when a replica is removed |
pod-deletion-cost | Annotation that orders which Pods a ReplicaSet deletes first |
References
- Kubernetes: Resource Management for Pods and Containers https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ — Pod QoS classes https://kubernetes.io/docs/concepts/workloads/pods/pod-qos/ — Local ephemeral storage https://kubernetes.io/docs/concepts/storage/ephemeral-storage/ — Downward API https://kubernetes.io/docs/concepts/workloads/pods/downward-api/
- Kubernetes scheduling: kube-scheduler https://kubernetes.io/docs/concepts/scheduling-eviction/kube-scheduler/ — Scheduling framework https://kubernetes.io/docs/concepts/scheduling-eviction/scheduling-framework/ — Resource bin packing https://kubernetes.io/docs/concepts/scheduling-eviction/resource-bin-packing/ — Scheduler performance tuning https://kubernetes.io/docs/concepts/scheduling-eviction/scheduler-perf-tuning/ — Scheduler configuration https://kubernetes.io/docs/reference/scheduling/config/
- Kubernetes placement: Assigning Pods to Nodes https://kubernetes.io/docs/concepts/scheduling-eviction/assign-pod-node/ — Taints and tolerations https://kubernetes.io/docs/concepts/scheduling-eviction/taint-and-toleration/ — Topology spread constraints https://kubernetes.io/docs/concepts/scheduling-eviction/topology-spread-constraints/ — Pod priority and preemption https://kubernetes.io/docs/concepts/scheduling-eviction/pod-priority-preemption/ — Pod overhead https://kubernetes.io/docs/concepts/scheduling-eviction/pod-overhead/ — Well-known labels, annotations and taints https://kubernetes.io/docs/reference/labels-annotations-taints/
- Kubernetes eviction: Node-pressure eviction https://kubernetes.io/docs/concepts/scheduling-eviction/node-pressure-eviction/ — API-initiated eviction https://kubernetes.io/docs/concepts/scheduling-eviction/api-eviction/ — Disruptions https://kubernetes.io/docs/concepts/workloads/pods/disruptions/ — ReplicaSet (scale-down order) https://kubernetes.io/docs/concepts/workloads/controllers/replicaset/
- Kubernetes policy: LimitRange https://kubernetes.io/docs/concepts/policy/limit-range/ — Resource quotas https://kubernetes.io/docs/concepts/policy/resource-quotas/
- Kubernetes autoscaling: Horizontal Pod Autoscaling https://kubernetes.io/docs/concepts/workloads/autoscaling/horizontal-pod-autoscale/ — HPA walkthrough https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough/ — Vertical Pod Autoscaling https://kubernetes.io/docs/concepts/workloads/autoscaling/vertical-pod-autoscale/ — Resize container resources https://kubernetes.io/docs/tasks/configure-pod-container/resize-container-resources/ — Node autoscaling https://kubernetes.io/docs/concepts/cluster-administration/node-autoscaling/ — Resource metrics pipeline https://kubernetes.io/docs/tasks/debug/debug-cluster/resource-metrics-pipeline/ — CPU management policies https://kubernetes.io/docs/tasks/administer-cluster/cpu-management-policies/
- Kubernetes devices: Dynamic Resource Allocation https://kubernetes.io/docs/concepts/resource-management/dynamic-resource-allocation/ — Pod-level effective requests https://kubernetes.io/docs/concepts/resource-management/effective-pod-requests-limits/
- Kubernetes API reference: HorizontalPodAutoscaler v2 https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/horizontal-pod-autoscaler-v2/ — Pod v1 https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/pod-v1/ — LimitRange https://kubernetes.io/docs/reference/kubernetes-api/policy-resources/limit-range-v1/ — ResourceQuota https://kubernetes.io/docs/reference/kubernetes-api/policy-resources/resource-quota-v1/ — PriorityClass https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/priority-class-v1/ — PodDisruptionBudget https://kubernetes.io/docs/reference/kubernetes-api/policy-resources/pod-disruption-budget-v1/ — Job https://kubernetes.io/docs/reference/kubernetes-api/workload-resources/job-v1/ — RuntimeClass https://kubernetes.io/docs/reference/kubernetes-api/cluster-resources/runtime-class-v1/ — KubeletConfiguration https://kubernetes.io/docs/reference/config-api/kubelet-config.v1beta1/ — KubeSchedulerConfiguration https://kubernetes.io/docs/reference/config-api/kube-scheduler-config.v1/
- Kubernetes feature gates (stages): https://kubernetes.io/docs/reference/command-line-tools-reference/feature-gates/ — Releases https://kubernetes.io/releases/
- Cluster Autoscaler FAQ https://github.com/kubernetes/autoscaler/blob/master/cluster-autoscaler/FAQ.md — README https://github.com/kubernetes/autoscaler/blob/master/cluster-autoscaler/README.md
- Vertical Pod Autoscaler: README https://github.com/kubernetes/autoscaler/blob/master/vertical-pod-autoscaler/README.md — components https://github.com/kubernetes/autoscaler/blob/master/vertical-pod-autoscaler/docs/components.md — quick start https://github.com/kubernetes/autoscaler/blob/master/vertical-pod-autoscaler/docs/quickstart.md — features https://github.com/kubernetes/autoscaler/blob/master/vertical-pod-autoscaler/docs/features.md — known limitations https://github.com/kubernetes/autoscaler/blob/master/vertical-pod-autoscaler/docs/known-limitations.md — API https://github.com/kubernetes/autoscaler/blob/master/vertical-pod-autoscaler/docs/api.md
- metrics-server https://github.com/kubernetes-sigs/metrics-server — Descheduler https://github.com/kubernetes-sigs/descheduler
- Karpenter: concepts https://karpenter.sh/docs/concepts/ — NodePools https://karpenter.sh/docs/concepts/nodepools/ — Disruption https://karpenter.sh/docs/concepts/disruption/ — Scheduling https://karpenter.sh/docs/concepts/scheduling/ — Amazon EKS best practices for Karpenter https://docs.aws.amazon.com/eks/latest/best-practices/karpenter.html
- KEDA 2.21: concepts https://keda.sh/docs/2.21/concepts/ — scaling deployments https://keda.sh/docs/2.21/concepts/scaling-deployments/ — scaling jobs https://keda.sh/docs/2.21/concepts/scaling-jobs/ — authentication https://keda.sh/docs/2.21/concepts/authentication/ — ScaledObject spec https://keda.sh/docs/2.21/reference/scaledobject-spec/ — ScaledJob spec https://keda.sh/docs/2.21/reference/scaledjob-spec/ — scalers: Kafka https://keda.sh/docs/2.21/scalers/apache-kafka/ — RabbitMQ https://keda.sh/docs/2.21/scalers/rabbitmq-queue/ — Redis lists https://keda.sh/docs/2.21/scalers/redis-lists/ — Prometheus https://keda.sh/docs/2.21/scalers/prometheus/ — Cron https://keda.sh/docs/2.21/scalers/cron/
- Linux kernel: Control Group v2 https://docs.kernel.org/admin-guide/cgroup-v2.html — CFS bandwidth control https://docs.kernel.org/scheduler/sched-bwc.html
- Go: Go 1.25 release notes https://go.dev/doc/go1.25 — Go 1.19 release notes https://go.dev/doc/go1.19 — GC guide https://go.dev/doc/gc-guide — GODEBUG https://go.dev/doc/godebug — runtime docs https://go.dev/src/runtime/extern.go —
GOMAXPROCSdoc comment https://go.dev/src/runtime/debug.go — uber-go/automaxprocs https://github.com/uber-go/automaxprocs - PHP-FPM configuration https://www.php.net/manual/en/install.fpm.configuration.php
- Laravel 13: Queues https://laravel.com/docs/13.x/queues — Horizon https://laravel.com/docs/13.x/horizon —
RedisQueue.phphttps://github.com/laravel/framework/blob/13.x/src/Illuminate/Queue/RedisQueue.php —config/database.phphttps://github.com/laravel/laravel/blob/13.x/config/database.php — RabbitMQ driver https://github.com/vyuldashev/laravel-queue-rabbitmq - Google Cloud: Best practices for running cost-optimized Kubernetes applications on GKE https://cloud.google.com/architecture/best-practices-for-running-cost-effective-kubernetes-applications-on-gke — Autopilot resource requests https://cloud.google.com/kubernetes-engine/docs/concepts/autopilot-resource-requests
- Amazon EKS best practices: cost optimization https://docs.aws.amazon.com/eks/latest/best-practices/cost-opt.html