6核CPU满跑Node.js+Socket.io时MySQL的CPU资源占用问题咨询
Great question—this is a super common point of confusion when you’re running multi-core Node.js setups alongside database services like MySQL. Let’s break this down clearly:
First, the Core Truth: The OS Controls CPU Scheduling
Node.js processes (or any user-space process) don’t "own" CPU cores—your server’s operating system kernel is the one that manages how CPU time is allocated across all running processes.
When a Node.js process shows 100% CPU usage on a core, that just means it’s using as much of that core’s available time as possible. The OS will still interrupt it periodically (via time slicing) to give CPU time to other processes like MySQL, system daemons, or background tasks. The catch? If Node.js is hogging nearly all the time slices, MySQL will get far less CPU time than it needs, leading to slower query responses, increased latency, or even timeouts under load.
Key Distinction: "100% CPU Usage" vs. "CPU Affinity Binding"
You mentioned each core runs a Node.js app—let’s clarify two scenarios here:
1. Node.js is CPU-Bound (No Explicit Core Binding)
If your Node.js apps are just doing heavy CPU-intensive work (like complex calculations, data processing) that drives core usage to 100%, the OS will still schedule MySQL on those cores. It just won’t get much time. Think of it like a crowded highway: Node.js is taking almost all the lanes, but MySQL can still squeeze in occasionally.
2. Node.js is Bound to Specific Cores (via taskset, PM2, etc.)
If you’ve used tools to set CPU affinity (forcing each Node.js process to stick to a specific core), this doesn’t lock that core exclusively to Node.js. It’s just a hint to the OS scheduler that Node.js prefers running on that core. MySQL (by default) has no affinity restrictions, so the scheduler can still assign it to those "bound" cores if needed. That said, if Node.js is consistently using 100% of that core’s time, MySQL’s access will still be limited.
Practical Implications & Fixes
- Problem Signs: If MySQL starts showing slow query logs, increased connection wait times, or reduced throughput, it’s a clear sign it’s starved for CPU.
- Quick Fixes:
- Reserve at least one core for system processes and MySQL. Don’t run Node.js on every single core—leave 1-2 cores free (or use CPU affinity to bind Node.js to only 4-5 cores).
- Adjust process priorities: Use the
niceorrenicecommands to lower the priority of your Node.js processes, which tells the OS to prioritize MySQL and system tasks when CPU is tight. - Optimize Node.js workloads: If possible, offload CPU-heavy tasks to a separate service (like a worker pool) so your main Node.js processes aren’t constantly maxing out cores.
Hope this clears up your confusion—let me know if you need help tuning your specific setup!
内容的提问来源于stack exchange,提问作者Ümit Aparı

