ACCESS TO IT INTEL GRANTED

Profile Bun CPU Hotspots with the Built-In --cpu-prof Sampler

TARGET_ENV: Bun 1.1.x+ on Ubuntu 22.04, Debian 12, macOS 13+
[ TAGS: bun, snippet, profiling, performance, cpu, debugging ]

Bun embeds a sampling CPU profiler activated with the --cpu-prof flag, which writes a Chrome DevTools-compatible .cpuprofile JSON file. The profiler hooks into Bun's internal event loop and V8-compatible JSC sampling infrastructure at roughly one millisecond intervals, capturing JavaScript and native frames. The resulting file can be loaded into Chrome DevTools Performance panel or analyzed with tools like speedscope without any additional instrumentation code.

This is critical for production debugging of latency regressions in Bun-hosted services. When a request handler mysteriously slows down after a dependency upgrade, running the service under --cpu-prof for a bounded window and diffing flame graphs against a known-good baseline isolates the regression quickly. It is also useful for optimizing cold-start times in serverless deployments where the first 100 milliseconds dominate billing, and for validating that a refactor actually reduced CPU rather than just moving work around.

The profiler adds measurable overhead, typically 5 to 15 percent, so never leave it on in steady-state production; gate it behind a feature flag or run it on a canary instance. The .cpuprofile files contain function names and file paths, which can leak internal module structure if shared externally, so scrub or restrict access. A common pitfall is that --cpu-prof only captures the main thread; worker threads and Bun.spawn subprocesses need separate profiling. Also, writing the profile on abrupt SIGKILL will lose data, so send SIGTERM and let Bun flush the file. Combine with --cpu-prof-dir to write to a mounted volume in containers.

> System.Execute()

# Profile a script and write to a specific directory
bun --cpu-prof --cpu-prof-dir=/var/log/bun-profiles --cpu-prof-name=api-run.cpuprofile run ./src/server.ts

# Analyze with speedscope after copying locally
npx --yes speedscope@latest /var/log/bun-profiles/api-run.cpuprofile

# Container-friendly one-liner with SIGTERM flush
bun --cpu-prof --cpu-prof-dir=/tmp/prof run ./src/server.ts & PID=$!; sleep 30; kill -TERM $PID; wait $PID

> Architecture & Security Context

Verified for Valters IT Hub. When deploying this configuration in a production homelab or enterprise environment, ensure that you monitor system resources and implement strict access controls. Administrator privileges are required.


ID: VALTERSIT-027881564019

← BACK_TO_VAULT → CVE_DATABASE