Bun Fixes Critical Container Resource Detection Bug with cgroup-Aware CPU Core Counting
Key Takeaways
- ▸Bun now respects Docker and Kubernetes CPU limits instead of spawning threads based on host core count, preventing resource exhaustion in containerized deployments
- ▸Unified CPU detection system feeds thread pool sizing, JavaScript APIs (navigator.hardwareConcurrency, os.availableParallelism), and internal thread management through a single WTF::numberOfProcessorCores() function
- ▸Implementation supports both cgroup v1 and v2 hierarchies with hierarchy traversal to identify the tightest CPU quota constraints
Summary
Bun has resolved a significant performance issue where the JavaScript runtime was ignoring Linux container CPU limits and spawning excessive threads based on host core counts instead of container constraints. The fix implements cgroup-aware CPU detection that properly respects Docker and Kubernetes resource limits, preventing resource exhaustion and system throttling in containerized environments.
The update routes navigator.hardwareConcurrency, os.availableParallelism(), and bun.getThreadCount() through a unified WTF::numberOfProcessorCores() function that now consults sched_getaffinity and cgroup CPU quotas on Linux. Previously, Bun would report the full host core count (e.g., 96 cores) even in containers limited to 2 CPUs, causing the runtime to spawn ~96 threads that would exceed the container's quota and trigger kernel descheduling, resulting in sawtooth latency patterns and garbage collection stalls.
The implementation handles both cgroup v1 and v2 hierarchies, walks the cgroup hierarchy to find the tightest CPU quota, and caches results after the first call. This brings Bun's behavior in line with Node.js's libuv approach and directly addresses issue #17723 where Bun migration on Kubernetes caused CPU and memory spikes leading to container crashes.
- Fix addresses a critical production issue where Bun migrations on GKE and other Kubernetes platforms caused immediate CPU and memory spikes leading to container crashes
Editorial Opinion
This fix represents an important maturation of Bun's production-readiness in containerized environments. Container-aware resource detection is a fundamental requirement for any modern JavaScript runtime, and Bun's previous behavior—spawning 96 threads in a 2-CPU container—was a serious oversight that directly prevented adoption in cloud-native deployments. The implementation correctly handles both cgroup versions and hierarchy traversal, demonstrating thoughtful engineering. However, the lack of runtime cgroup resize support (matching Node's current limitations) remains a gap for environments using Kubernetes in-place vertical scaling.



