百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
k8s-cpu-limits-analyzed

k8s-cpu-limits-analyzed

> 云原生
免费

Kubernetes 的 CPU 限制使您的应用程序变得(非常)缓慢且昂贵。分析了 CPU 限流情况,并提供了证据。

113 stars0 点赞4 次浏览
GitHub

工具介绍

Kubernetes 的 CPU 限制使您的应用程序变得(非常)缓慢且昂贵。分析了 CPU 限流情况,并提供了证据。

Kubernetes CPU limits: the mistake, the why, and proof

TL;DR: set requests.cpu, requests.memory, and limits.memory, but remove limits.cpu.

This isn't new advice. It's a best practice from Kubernetes and Google themselves:

"Always set memory limit == request. Never set CPU limit" ~ Tim Hockin, Kubernetes co-founder (source)

Google's GKE docs say the same thing: for the CPU request, "specify the minimum CPU needed... according to your own SLOs," then "set an unbounded CPU limit" (source).

Most teams still set a CPU limit anyway, then spend their time fighting the throttling that follows. This analysis explains why the advice is right, and why so many people still get it wrong. Most charts set two CPU numbers, a request and a limit, and people treat them like the same setting with a bit of headroom.

  • The request is how much CPU is reserved for your pod if it needs it.
  • The limit is a hard cap: hit it and the kernel throttles the pod, even when the node still has spare CPU.

This is the most common source of unexpected CPU throttling on Kubernetes. A CPU limit does not protect neighboring pods; their protection comes from their own requests. There are exceptional use cases for using CPU limits (they exist for a reason), but your situation is unlikely one of them, meaning you probably should NOT set CPU limits, see conclusion.

Contents: why requests are enough, what average CPU hides, the benchmark, .NET and thread pools, CPU limits and OOMKills, conclusion, common questions, run it yourself.

Why CPU requests are enough

Linux already shares a busy node's CPU fairly among pods. That sharing is called CFS (Completely Fair Scheduler). A request is a weight in the cgroup, not a pinned core. If the node is busy, CFS splits time in proportion to those weights: a 16 CPU request gets about sixteen times the CPU of a 1 CPU request. If the other pods are idle, a pod can use the leftover; when they need CPU again, those cores go back. None of this requires a CPU limit.

One caveat: the request guarantees your proportion of CPU over time, not exactly when you get it. Under heavy contention your share arrives in slices, so tail latency can still move a little even with a correct request. A limit does not fix that, it only adds throttling on top.

A limit is a separate cap, also enforced by CFS. Every 100 ms the kernel gives your pod a budget of CPU time, and every thread in the pod shares that budget. When it is gone, the pod is throttled until the next 100 ms. The node can be idle and the pod still waits. A 1 CPU limit on a 32-core node can still run on all 32 cores for a few milliseconds, then sit out the rest of the window. Four threads working at once burn a 500m budget in about 12 milliseconds. It is an average, not a reserved core.

What average CPU hides

The CPU graph on your Kubernetes dashboard usually averages a minute. CPU throttling lasts a tenth of a second. So the graph can look fine while the app is being throttled all the time. Watch container_cpu_cfs_throttled_periods_total, not average CPU.

People put a limit on because they are afraid some other app will starve their pod. That is what the request is for. The app you care about is protected by its own request. A runaway next door can use leftover CPU, but it cannot take the share you reserved. If leftover on the node is huge, the requests are too small. If teams can deploy with no request at all, give them a default request instead of putting a CPU limit on whoever looks greedy.

The same blindness poisons right-sizing. Usage recorded under a CPU limit can never go above the limit: the cap clips every burst, so the history shows what the kernel allowed, not what the app wanted. Size a request from that history and you copy the cap's distortion into the request. Drop the limit first, let the app run for a while, then measure and set requests from numbers that were free to move.

Proof: the same app with and without a CPU limit

In a controlled burst test, adding a CPU limit took typical latency from 23 ms to roughly 87 ms (about 4x slower), with the limited pod throttled in half of all CFS windows, while the average CPU graph looked fine the whole time.

I ran the same .NET app twice on a local 8-CPU minikube. Both asked for 250m, and I pinned .NET to 4 CPUs on both so I was not accidentally comparing "app thinks it has 1 core" against "app thinks it has 8." One pod had a 500m limit. The other did not.

The useful test is a burst that on average stays under 500m, but for a moment uses several threads at once, which uses up the limit budget inside one 100 ms window. That is by design: it is the pattern that produces throttling while the average CPU graph stays green, which is the exact blind spot this whole article is about. Typical response time went up about 4x, and the limited pod was throttled about half the time. There were no errors, and a normal CPU graph would have looked fine.

I also sent a short traffic spike that did go over the cap, and the limited pod was throttled on almost every window. Then I put another pod on the same machine that just burns CPU in a loop, with no limit of its own. The app without a limit did not get slower. That first test still had spare cores on the node, so run.sh also fills the node completely with that busy neighbor pod, then measures the unlimited app again with no spare CPU left anywhere on the node. The request was enough.

More numbers and charts: results/run.md.

.NET looks at the limit

If you do not set DOTNET_PROCESSOR_COUNT, .NET counts CPUs from the limit. A 500m limit (or the common 100m default) shows up as 1 CPU, so the thread pool and garbage collector follow that and you start with one worker thread.

This lab sets DOTNET_PROCESSOR_COUNT=4 on both pods so the test is about the limit, not about .NET shrinking itself. In a real fleet, set one default after you drop limits, or the same service will behave differently on a 4-core node than on a 16-core node:

yaml
- name: DOTNET_PROCESSOR_COUNT
  value: "4"

The same idea applies to any runtime that reads the quota: Go reads it into GOMAXPROCS, the JVM has its own equivalent. Pin these once at the platform level after you drop limits. Do not keep a CPU limit just to shrink the runtime.

A tight CPU limit can also look like a memory problem. The garbage collector needs CPU to free memory, and if it is throttled most of the time, memory grows and the pod gets killed as an OOM even though nothing leaked. Others have hit the same wall: Fairwinds lists throttling as an indirect cause of OOMKilled ("slowing garbage collection or other memory-reclaiming work"), and this JVM-on-Kubernetes writeup shows how a GC burst over the limit turns into throttling and longer pauses. Check container_cpu_cfs_throttled_periods_total before you raise the memory limit.

This repo reproduces it. See the OOMKilled proof below.

How CPU limits cause memory issues and OOMKills

This can seem backwards: CPU is the compressible resource, run out and you wait, nothing dies. But memory is where a CPU deficit accumulates. Wherever work arrives faster than a throttled pod can process it, the difference sits in RAM until the kernel ends the pod. The lab reproduces three common shapes of this, each as an A/B pair: two pods running the same app, the same memory limit, the same load, with limits.cpu as the only difference in the YAML. Nothing leaks in any of them; every byte would have been freed if the pod had been allowed to run the code that frees it. All three evidence files are in results/oom.md.

Shape 1: the backlog

This is the shape of any in-memory queue: a consumer buffering messages from Kafka or RabbitMQ faster than it can process them, an unbounded channel between two components, a server holding request payloads while handlers run behind.

Work arrives at 20 jobs per second; each job costs 40 ms of CPU time (measured on the thread CPU clock, so throttling can't hide it) and holds 2 MiB of memory until a worker finishes it. That is ~800m of CPU demand against a limits.cpu: 500m cap, with 1Gi of memory on both pods.

The uncapped pod handles the full 800m of work, so its queue stays empty and memory stays flat. The capped pod is limited to 500m, so it clears at most 12.5 jobs per second (a bit less in practice, since receiving and copying payloads draws from the same budget) while 20 keep arriving. The backlog holds memory, the backlog only shrinks with CPU the pod isn't allowed to use, and the kernel eventually OOMKills it.

In the recorded run (scripts/oom.sh), the capped pod drained 10.3 jobs per second against 20 arriving and was OOMKilled after 29 seconds of load (exit code 137, lastState.terminated.reason: OOMKilled), throttled in 96% of CFS periods during that window. The uncapped pod drained 21.6 jobs per second with an empty queue, flat memory, and zero restarts. Numbers vary slightly run to run (see the note on SDK-image page cache in results/oom.md); the outcome doesn't.

A bounded worker pool doesn't prevent this: it bounds CPU concurrency, not memory. The common shape is a bounded pool fed by an unbounded handoff queue, and the lab's own worker pool is size one. Unbounded buffers are also more common than they look: RabbitMQ's prefetch is unlimited unless basic.qos is set, and Kafka consumers that hand records to an in-process queue to keep polling within max.poll.interval.ms and avoid a rebalance have effectively rebuilt the unbounded buffer one layer down. Even a properly bounded buffer is usually sized for the healthy drain rate, which the cap just cut in half. And a consumer with real backpressure everywhere does not remove the deficit, it relocates it: lag piles up in the broker instead of in RAM. The CPU limit decides which resource absorbs the shortfall; only removing the limit removes the shortfall itself.

Shape 2: GC starvation

This is a completely different scenario, one that involves the garbage collector instead of a queue or buffer. Every request builds a reference-dense graph of 10,000 small objects (~1.5 MiB) and holds it only while doing real work; once the request finishes, the graph is garbage. Nothing is retained anywhere, on purpose. What runs short here is the garbage collector's own CPU budget: on the capped pod (limits.cpu: 100m, the same value as the production incident this test is based on), in-flight requests pile up, the live object count grows with them, each GC cycle gets more expensive, and the collector fights the workload for the same shrinking quota.

In the recorded runs (scripts/gc.sh, three of three, on .NET 10 with adaptive DATAS GC enabled), the capped pod stopped answering its own stats endpoint, kept digesting its backlog after the load generator had already stopped, and was OOMKilled anyway (exit 137). The identical uncapped pod finished the same load with a 9.3 MiB heap and one request in flight. This is also the shape where monitoring goes dark first: a pod too throttled to answer a stats scrape is a pod whose dashboards and probes are already lying.

Shape 3: API server

No queue

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

cpukubectlkubernetes

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年9月9日
最后更新2026年9月18日
分类云原生
定价免费

> 相关工具

K
Kubernetes
容器编排事实标准
H
Helm
Kubernetes 包管理器
S
seaweedfs
SeaweedFS is a distributed storage system for object storage (S3), file systems, and Iceberg tables,