HANDS-ON LAB Advanced

Diagnosing & Fixing Kubernetes CPU Throttling: CFS Quota Mechanics, cgroups v2 Metrics & SRE CPU Limit Standards

Deep dive into Kubernetes CPU throttling: Linux kernel CFS quota mechanics, diagnosing with cgroups v2 cpu.stat, the multi-threading latency trap, and SRE best practices for setting CPU limits.

Vibe DevOps·· ~12 min read
KubernetesLinux cgroups v2CFS SchedulerPrometheusDocker

Key Takeaways & Prerequisites

  • Kernel CFS Bandwidth Control: Kubernetes CPU limits are enforced by Linux CFS over a 100ms period (100,000us). Misconfigured limits are the leading cause of p99 latency spikes despite low average CPU utilization.
  • The Multi-Threading Trap: Highly concurrent applications (Go, Node.js, Java) can exhaust their period quota in just 10–15ms of real wall-clock time, causing the kernel to hard-throttle the entire container for the remaining 85–90ms.
  • cgroups v2 Diagnostics: Inspect /sys/fs/cgroup/cpu.stat directly for nr_periods, nr_throttled, and throttled_usec, and monitor throttling ratios via container_cpu_cfs_throttled_periods_total on Prometheus.
  • SRE Best Practices: Always set accurate cpu.requests for scheduling; for latency-sensitive API workloads, avoid cpu.limits (or set 3x–5x bursts), and enable CPUCFSQuotaBurst on Kubernetes >= 1.22.

Architecture & Execution Flow

  1. 01 →100ms CFS PeriodKernel quota scheduling window
  2. 02 →Multi-thread BurstQuota burned in milliseconds
  3. 03 →Kernel ThrottlingContainer frozen & p99 spikes
  4. 04 →SRE TuningRemove limits or enable CFS Burst
Table of Contents

In production Kubernetes environments, one of the most elusive and frustrating incidents encountered by Site Reliability Engineers (SREs) is the following anomaly: API latency (particularly p95 and p99) spikes by orders of magnitude, while average CPU utilization dashboards on Grafana remain deceptively low, hovering between 20% and 35%.

The affected Pod is not OOMKilled, its status reports Running 1/1, and application logs reveal zero panic or crash signatures. Yet, downstream clients and upstream ingress controllers continuously fail with HTTP 504 Gateway Timeouts or gRPC DeadlineExceeded errors. The root cause of this behavior is CPU Throttling, induced by the Linux kernel's Completely Fair Scheduler (CFS) Quota bandwidth enforcement mechanism when resources.limits.cpu is declared.

This guide explores the kernel-level mechanics of CFS Bandwidth Control, details how to extract precise throttling telemetry via cgroups v2, demonstrates an end-to-end lab reproduction, and presents battle-tested architectural strategies for standardizing CPU limits in production.


Production Symptoms: The Low CPU Utilization vs. p99 Latency Spike Paradox

Consider a typical microservices failure mode:

A critical payment processing backend service (payment-api) implemented in Go or Node.js is configured with the following resource specifications:

resources:
  requests:
    cpu: "250m"
    memory: "512Mi"
  limits:
    cpu: "500m"
    memory: "1Gi"

During moderate peak traffic: 1. CPU Usage (1m rate): Sourced via rate(container_cpu_usage_seconds_total[1m]), telemetry indicates the container consumes only 0.18 to 0.22 cores (roughly 36% to 44% of its 500m limit). 2. Memory: Consumption is completely stable; no container restarts or OOMKilled events occur. 3. Latency: Baseline response times of 25ms suddenly degrade to 1,200ms–2,500ms for p95 and p99 request distributions. 4. The False Reflex: Operations engineers assume the backend lacks capacity, scaling out replica counts. However, p99 tail latency fails to recover.

The underlying mechanics stem from the fundamental difference between resource types: CPU is a compressible resource, whereas Memory is an incompressible resource. When a container breaches its memory limit, the Linux kernel invokes the Out-Of-Memory Killer (exit code 137) to terminate the process. Conversely, when a container breaches its allocated CPU quota, the kernel does not terminate the task; it suspends thread execution (throttling) until the scheduler replenishes quota in the subsequent enforcement period.


Under the Hood: CFS Bandwidth Control and the Multi-Threading Trap

To understand why a container experiences severe throttling despite low average utilization, we must examine how the Linux kernel and container runtimes (containerd/CRI-O) enforce limits.cpu.

1. CFS Period and Quota Cycles

Within the Linux kernel, the Completely Fair Scheduler regulates CPU runtime using two primary cgroup parameters: - cpu.cfs_period_us: The duration of an enforcement cycle. The default across Linux distributions and Kubernetes kubelet implementations is 100,000 microseconds (100 milliseconds, or 0.1s). - cpu.cfs_quota_us: The total cumulative CPU execution time all threads within a cgroup are permitted to consume within that period.

When specifying limits.cpu: "500m" in Kubernetes, the container runtime computes:

$$\text{quota} = 500\text{m} \times 100,000\mu\text{s} = 50,000\mu\text{s} \text{ (50ms CPU time)}$$

This establishes a firm boundary: Within every 100ms of real-time elapsed wall clock, all threads in the container combined may execute for at most 50ms of CPU compute time.

2. The Multi-Threading Trap

CPU allocation (cpu.cfs_quota_us) measures the cumulative execution runtime across all active threads, not elapsed wall-clock time.

Consider the payment service running on a Go runtime configured with GOMAXPROCS=4 (or a Node.js process utilizing worker threads, or a JVM running background parallel Garbage Collection): - An incoming burst of HTTP requests arrives, simultaneously waking 4 worker threads to handle computationally intensive tasks. - All 4 threads execute concurrently across 4 distinct physical CPU cores on the host node. - After just 12.5 milliseconds of real-world wall-clock time: $$\text{Total CPU Consumed} = 4 \text{ threads} \times 12.5\text{ms} = 50\text{ms CPU time!}$$ - The container has fully depleted its 50ms quota for the current 100ms cycle. - The Linux CFS scheduler immediately unschedules the container's threads, freezing execution for the remaining 87.5 milliseconds of the period!

Completely Fair Scheduler (CFS) quota mechanism and CPU throttling
Figure 1: CFS Quota 100ms enforcement cycle illustrating multi-threaded container stall

During this 87.5ms freeze, the container cannot process incoming network packets, complete TLS handshakes, or handle I/O callbacks. Pending traffic buffers inside kernel socket queues. When the next 100ms period begins, the quota replenishes; the application runs for another 12.5ms burst and gets throttled once more.

This cycle can repeat thousands of times per hour: - Average CPU utilization sampled by metrics scrapers (typically aggregated over 15-second or 1-minute intervals) appears minimal because the process was only running 12.5% to 25% of the total wall-clock duration. - Meanwhile, tail latency (p95/p99) compounds across these successive 87.5ms stalls, directly violating customer SLOs.


Diagnostic Engineering: Inspecting cgroups v2 Directly and Measuring with Prometheus

1. Direct Inspection via the cgroup Pseudo-Filesystem

On modern Linux environments (Kernel >= 5.8 and Kubernetes >= 1.25 operating with cgroups v2 by default), all scheduler throttling metrics are exposed directly via the cpu.stat file.

To inspect these counters directly from within a Pod (or from the host node under the pod's cgroup path):

# Inspect cgroup v2 CPU statistics
cat /sys/fs/cgroup/cpu.stat

Sample output:

usage_usec 481928341
user_usec 391024910
system_usec 90903431
nr_periods 245000
nr_throttled 86450
throttled_usec 4210940000

Field descriptions: - nr_periods: Total count of CFS periods (100ms intervals) elapsed since container initialization. - nr_throttled: Total count of enforcement periods in which the container exhausted its quota and suffered execution throttling. - throttled_usec: Cumulative duration (in microseconds) that threads within the cgroup spent suspended awaiting quota replenishment.

The Throttling Ratio is computed as:

$$\text{Throttling Ratio} = \frac{\text{nr_throttled}}{\text{nr_periods}} \times 100\% = \frac{86,450}{245,000} \times 100\% \approx 35.28\%$$

For any latency-sensitive service, a sustained throttling ratio exceeding 15% to 20% warrants an immediate critical alert.

Analyzing cgroups v2 cpu.stat metrics to detect throttling
Figure 2: Evaluating cpu.stat metrics on cgroups v2 to determine throttling severity

Note for legacy cgroups v1 environments: The corresponding path is /sys/fs/cgroup/cpu/cpu.stat, which tracks nr_periods, nr_throttled, and throttled_time (recorded in nanoseconds rather than microseconds).

2. PromQL Queries for Real-Time Throttling Telemetry

cAdvisor, embedded natively in the Kubelet daemon, exports these CFS metrics: - container_cpu_cfs_periods_total: Monotonic counter tracking elapsed CFS periods. - container_cpu_cfs_throttled_periods_total: Monotonic counter tracking periods during which the container was throttled. - container_cpu_cfs_throttled_seconds_total: Cumulative duration (in seconds) the container spent throttled.

The standard PromQL expression to compute per-container throttling percentages over 5-minute rolling windows:

sum(rate(container_cpu_cfs_throttled_periods_total[5m])) by (namespace, pod, container)
/
sum(rate(container_cpu_cfs_periods_total[5m])) by (namespace, pod, container) * 100
Configuring Prometheus Rule and PromQL to monitor CPU Throttling
Figure 3: Setting up a Prometheus alerting rule for throttling ratios exceeding 20%

Hands-on Lab: Reproducing CPU Throttling and Profiling Latency Impact

We can reproduce this scheduler bottleneck in an isolated environment using a Docker container bound by strict CFS CPU quotas.

Step 1: Provisioning a Container with a Constrained CPU Quota

Start an Ubuntu container configured with a CPU limit of 0.2 cores (equivalent to 200m in Kubernetes, enforcing a 20,000us quota per 100,000us period):

docker run -d --name cfs-test-lab \
  --cpus="0.2" \
  ubuntu:22.04 sleep infinity

Verify the underlying kernel cgroup settings inside the container:

# Verify quota on cgroups v2
docker exec cfs-test-lab cat /sys/fs/cgroup/cpu.max
# Output: 20000 100000 (quota = 20000us, period = 100000us)

Step 2: Executing Multi-Threaded Burst Workloads

Install Python and execute a multi-threaded workload designed to generate concurrent computational bursts (simulating JSON deserialization, cryptographic hashing, or template rendering):

docker exec -i cfs-test-lab bash << 'EOF'
apt-get update -qq && apt-get install -y -qq python3 > /dev/null

cat << 'PYEOF' > /tmp/burst_load.py
import time
import concurrent.futures

def cpu_heavy_task(n):
    start = time.time()
    # Compute Fibonacci/hash simulating CPU burst
    total = sum(i * i for i in range(1_500_000))
    return time.time() - start

if __name__ == '__main__':
    print("Starting multi-threaded burst load scenario (4 worker threads)...")
    wall_start = time.time()
    with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
        futures = [executor.submit(cpu_heavy_task, i) for i in range(4)]
        durations = [f.result() for f in futures]
    wall_elapsed = time.time() - wall_start
    print(f"Total wall-clock execution time: {wall_elapsed:.4f} seconds")
    print(f"Per-thread execution time: {[round(d, 4) for d in durations]}")
PYEOF

python3 /tmp/burst_load.py
EOF

Step 3: Correlating Throttling Telemetry

Immediately following the execution of the script, inspect the updated cpu.stat file:

docker exec cfs-test-lab cat /sys/fs/cgroup/cpu.stat

Observations from this run: - nr_periods increases predictably. - nr_throttled spikes sharply across each burst. - Real-world elapsed wall-clock duration (wall_elapsed) is 3x to 4x higher compared to executing the identical script on an unconstrained environment without --cpus="0.2".

Tear down the lab container:

docker rm -f cfs-test-lab

Production Hardening: SRE Strategies for Sizing CPU Limits

The Kubernetes and SRE communities (including infrastructure teams at Zalando, Buffer, Datadog, and Kubernetes SIG-Node) have debated the trade-offs of the "No CPU Limits" paradigm extensively.

The following architecture patterns provide an optimal balance between stability, performance, and multi-tenant isolation:

1. Workload Classification Matrix

Workload Type Characteristics Recommended cpu.requests Recommended cpu.limits
API / Web Services (Latency-Sensitive) Strict p99 SLOs, rapid bursts (Node.js, Go, Java, Python). Mandatory: Calibrate accurately to p90 historical consumption. Do NOT configure limits (or configure loose limits at 3x–5x requests).
Batch Processing / Background Workers Background workers, web scrapers, media encoders, queue consumers. Calibrate to baseline needs. Mandatory limits to prevent node-wide CPU starvation.
Databases / Caches (StatefulSets) Redis, PostgreSQL, MySQL requiring predictable performance. Configure Request = Limit (Guaranteed QoS). Configure Request = Limit.

2. Node Protection Without CPU Limits

A frequent operational concern is: "If we remove cpu.limits, will a single Pod with an infinite loop consume 100% of node compute and starve adjacent containers?"

The answer is no, due to how CFS Shares operate under contention: - Under CPU contention, the Linux scheduler divides available CPU cycles proportionally using the cpu.shares weighting derived directly from resources.requests.cpu. - A Pod configured with requests.cpu: 500m is mathematically guaranteed twice the CPU time of a Pod configured with requests.cpu: 250m. - A misbehaving container running an infinite loop can only scavenge idle CPU cycles that neighboring containers are not requesting. The moment a critical service requires compute, the scheduler immediately prioritizes its execution according to its allocated shares.

3. Leveraging CPU CFS Quota Burst (Kubernetes >= 1.22)

Beginning with Kubernetes 1.22, the CFS Quota Bursting feature was introduced (advancing across Beta and GA milestones) specifically to mitigate the multi-threading trap.

Mechanics: When a container does not fully consume its allocated quota during a given period, the surplus quota is banked into a burst balance pool. If a concurrent load burst arrives during subsequent periods, the container can draw from its banked balance to exceed its standard quota ceiling without inducing scheduler throttling.

To enable this capability within the node's KubeletConfiguration:

apiVersion: kubelet.config.k8s.io/v1beta1
kind: KubeletConfiguration
featureGates:
  CPUCFSQuotaBurst: true
cpuCFSQuotaPeriod: "100ms"

Summary and Production Remediation Checklist

When triaging unexplained API latency spikes on Kubernetes clusters, follow this 5-step checklist:

  1. Audit Throttling Metrics: Run PromQL queries tracking container_cpu_cfs_throttled_periods_total. If the throttling ratio exceeds 15%, CFS throttling is your primary bottleneck.
  2. Profile Application Concurrency: Reconcile your active runtime concurrency (Go GOMAXPROCS, Node.js worker pools, JVM GC threads) against configured limits.cpu.
  3. Audit CPU Limits Configuration:
  4. For user-facing HTTP/gRPC APIs, eliminate resources.limits.cpu entirely or scale the ceiling to 3x–5x the configured requests.cpu.
  5. Keep resources.limits.memory strictly defined to protect the node from memory leaks.
  6. Enable CPUCFSQuotaBurst: On modern Kubernetes releases, enable CFS Quota Bursting on worker node kubelet daemons.
  7. Establish AlertManager Policies: Trigger proactive alerts when container throttling ratios exceed 20% over a 5-minute window to remediate starvation before SLOs degrade.

Official References and Further Reading

Read critically, test before applying. Examples reflect Vibe DevOps lab environments; adjust parameters to your infrastructure and verify in staging first.← Back to Hands-on Labs

Next Recommended Labs